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
Peios

Peios

Using and developing the Peios operating system.

Single-page view · as markdown

What Is Peios

Peios / Introduction

Peios is an operating system. Its kernel is based on Linux, and adds its own security model, configuration store, event system, layered storage, and network packet policy. Above the kernel, Peios has its own service manager, sign-in service, and system services, and a desktop that you use from a web browser. A few ideas run through all of it, and knowing them makes the rest of this documentation easier to follow.

One security model for everything #

Every decision about who can do what goes through one security model, built into the kernel:

  • Every account, group, and service has a security identifier (SID) that never changes.
  • Every running program acts with an access token that says who it is, which groups it belongs to, and which privileges it holds.
  • Every protected object, whether a file, a registry key, a service, or a process, has a security descriptor that says who can do what to it.

When a program opens a file or changes a setting, the kernel compares the program's token with the object's security descriptor. No account is exempt from that check because of its number or name. An administrator has more access because policy grants it, not because the check is skipped.

Configuration lives in the registry #

Almost all configuration lives in the registry: a tree of keys holding typed values, with a security descriptor on every key. Service definitions, network profiles, sign-in policy, and desktop preferences are all registry values.

Configuration can come in layers. An installed role and a policy can each set the same value, and the registry decides which one is in effect without losing the other. Removing a layer restores what was there before.

Every event takes one path #

The kernel and every service report what they do through one event path. eventd stores the events, logs, and metrics, and answers queries for them according to who is asking. Each component documents the events it can emit, and no component is allowed to emit a field that isn't documented. See Interpreting Events.

Services are defined and supervised #

peinit starts the machine, starts each service in the order its dependencies require, restarts services that fail, and shuts the machine down. Each service is defined in the registry, and runs with an identity of its own. See Services and Jobs.

A desktop in your browser #

You can use Peios from a desktop in a web browser, at a local console, or over SSH. The desktop's applications run on the Peios machine, with the authority of the account you signed in with. See Signing In and The Desktop.

Where to start #

These pages are good places to begin:

  • How Peios Fits Together for a map of the components and how a machine starts.
  • Preparing a PC to install Peios.
  • Finding Your Way to find the guide for a task.

How Peios Fits Together

Peios / Introduction

A Peios machine is built from a small number of components, each with one job. This page names them, shows the order in which they start, and says where each is documented. When something goes wrong, the component that owns the job is where to look.

The kernel #

The kernel manages the hardware and runs every program. Peios adds five subsystems of its own to it:

SubsystemJob
Kernel Access Control Subsystem (KACS)Access control: tokens, security descriptors, privileges, and every access decision
Layered Configuration Subsystem (LCS)The registry: keys, values, layers, watches, and transactions
Kernel Mediated Event Subsystem (KMES)Events: the single path every event takes, with trusted details about its sender
StrataFSLayered storage: several directories, the strata that give it its name, presented as one directory tree
Network Traffic Filtering Engine (NTFE)The network packet filter, which enforces network policy from the registry

The subsystems rely on each other. The registry and the file systems use KACS security descriptors, and KACS reports its access decisions through KMES. The Peios Kernel product documents all five.

Starting the machine #

A machine starts in this order:

  1. The firmware loads one boot file that holds the kernel, a temporary file system loaded into memory, and the kernel's settings.
  2. Prelude runs from that temporary file system. It prepares the devices, mounts the real disk, and hands over to peinit. See Prelude.
  3. peinit, the service manager, prepares the system, then starts the registry service, loregd, and the sign-in service, authd.
  4. peinit then reads the service definitions from the registry and starts every service in dependency order. See Boot and Boot Modes.
  5. You sign in at the console, over SSH, or from a browser, and authd creates the token your session runs with. See Signing In.

If the machine can't finish starting, peinit starts it in a recovery mode with a console for repairs.

System services #

These services run on every machine:

ServiceJobGuide
peinitStarts, supervises, and stops services and scheduled jobsServices and Jobs
authdChecks credentials and creates access tokens; its partner lpsd stores local accountsLocal Accounts
loregdStores the registry's dataThe Registry
eventdStores events, logs, and metrics and answers queries for themReading Records
netdConfigures network interfaces, addresses, and routesNetwork Configuration
resolvdResolves names to addressesDiagnosing Name Resolution
timedKeeps the clock correct and manages the time zoneKeeping the Time
trustdMaintains the certificates the machine trustsThe Trust Store

The desktop #

Three programs make the desktop that you use from a browser. The Graphical Extensible Web Interface (GXWI) serves the session and handles sign-in from the browser, Fenestra arranges the windows, and Fenesh provides the dock, launcher, and settings. A set of desktop applications covers files, terminals, and system administration. See The Desktop.

Tools and development #

The command-line utilities include the familiar file and text commands, and tools for Peios's own features: reg for the registry, sd for security descriptors, and token for identities. The installer installs Peios to a disk and runs first-boot setup.

To build software for Peios, start with the Peios SDK.

Kinds of documentation #

Each kind of documentation answers a different question:

KindRead it to find out
These Learn pagesHow something works, and how to get a task done
Man pages, through manExactly what a command, file, or function does, with every option
Registry manuals, through regmanWhat a registry value means and which values are valid
Event manuals, through evmanWhat an event or one of its fields means
Technical reference manualsHow one component works inside
SpecificationsThe contracts that independent programs must agree on

A command's --help output is a short reminder of its man page.

Finding Your Way

Peios / Introduction

Each task on a Peios machine belongs to the component that owns it, and each component documents its own tasks. This page sends you to the right guide. Before you change authentication, the network, or the service that provides your session, keep a second way in: a console, or another signed-in session. That way a mistake can't lock you out.

Installing and first use #

To install Peios, prepare a boot medium with Preparing a PC, then follow Installing to Disk. Installing erases the disk you choose, so identify it and save anything you need first.

On a machine with first-boot setup, Completing Setup sets the machine's name and creates the first administrator. Then continue with Signing In. In a browser, check the machine's certificate before you enter your password.

Everyday work #

The desktop applications cover files, text editing, terminals, and system tools. Desktop Settings changes your desktop's appearance and preferences. A tool can't give you permission you don't have: it acts with your access token, and a machine-wide change affects every user.

Accounts and security #

TaskGuide
Create an account or change membershipLocal Accounts or Managing Accounts in Principals Manager
Change your own password, keys, or display nameChanging Your Account Settings or Changing Your Password
Change the privileges and integrity level that sign-ins receiveGranting Access
Find out why access was refusedDiagnosing an Access Refusal
Trust or distrust a certificateThe Trust Store

Changing an account doesn't change the tokens of programs already running. Test a fresh sign-in before you close the session you made the change from.

Software and services #

TaskGuide
Install, remove, or upgrade softwareManaging Packages and Upgrading Peios from the Desktop
Turn a feature on or offManaging Features in Feature Manager or from the command line
Start, stop, or inspect a serviceControlling Services
Read a service's outputFinding Service Logs
See what is running and what it usesInspecting Tasks and Sessions
Shut down or rebootShutting Down and Rebooting

Installing a package and setting up its feature are separate steps. Remove a feature while the package that supplies its cleanup is still installed.

Network, time, and storage #

TaskGuide
Configure a network connectionConfiguring Profiles or Changing Network Settings in Network Manager
Diagnose a connectionChecking Connectivity
Set the clock or the time zoneKeeping the Time
Inspect disks and file systemsDisk Manager and Filesystem Layout

When you change a network connection remotely, use a method that rolls the change back if you lose contact. Disk Manager inspects storage but doesn't change it.

Configuration #

Most settings live in the registry. Before you change a setting, read its manual with regman: it gives the type, valid values, and when a change takes effect. Then change it with reg or Registry Editor, and check that the component using the setting picked it up.

Reference #

Learn explains and links. The facts themselves live in reference forms that ship with the system:

  • Commands, files, and functions: the man pages, read with man.
  • Registry settings: the registry manuals, read with regman.
  • Events: the event manuals, read with evman.
  • How a component works inside: its technical reference manual, under Reference.

If something fails, start with Troubleshooting a Problem before you repeat a change or restart a service.

Troubleshooting a Problem

Peios / Introduction

Investigate the failed operation before changing the machine. A restart can remove useful state, and retrying a request can repeat a change whose reply was lost.

Before you start #

Keep the exact error, time, affected account, and resource name. Preserve a working console or administrator session if the problem affects remote access. Save unsaved work before an action that can end a session.

Investigate and verify #

  1. Identify which component performs the operation. Use the symptom guide below to inspect its state and relevant records.
  2. Distinguish a rejected request from an unavailable service or a lost reply. Read back inspectable state before repeating a mutation.
  3. Record the proposed correction and existing value. Change one cause at a time through the component's documented interface.
  4. Repeat the original operation and inspect the resulting state. Keep the initial evidence and the outcome of the correction.

Browser access or sign-in #

Check the address and port in Signing in from a Browser. A listener bound only to loopback is not reachable from another machine. For a certificate warning, follow The Machine's Certificate; do not enter credentials when the fingerprint differs from a trusted observation.

At a reachable console, inspect net status and the gxwid service. During installation and first boot, an address, overlay, or reboot can change what the browser reaches. Return to that workflow's guide.

For a credential refusal, use Diagnosing Authentication. A wrong credential and an unknown account share an authentication failure response; the response alone does not prove the account is absent. Authority and source events answer different parts of the decision.

Services and network state #

Service Troubleshooting covers identity, dependencies, configuration, and repeated exits. A process existing is not proof that it is ready. In Services Manager, Logs… opens the relevant Event Viewer filter; widen the time range when the failure is older.

Use Network Manager or net status to distinguish these cases:

  • An unmanaged interface needs its profile-selection rules checked.
  • A rejected configuration can leave the last complete configuration active.
  • A local address does not prove there is a route beyond the local network.
  • Working addresses with failing names need resolver diagnosis.

Displays labeled Example data are not measurements of live traffic. For clock problems, inspect time sources and clock state before changing the time or time zone.

Storage and interrupted changes #

Keep the failing path and exact error. df and du answer different questions about filesystem capacity and reachable directory contents. Permission failures or incomplete scans do not establish that deletion is the appropriate remedy.

For interrupted package, upgrade, or feature work, inspect that tool's recorded state and recovery instructions. Feature cleanup and package transaction recovery are separate operations. Repeating the original action without checking its state can make diagnosis harder.

Denied access or missing records #

Inspect the operation's required access, the caller's token, and the target's security descriptor before widening permissions. The task guide identifies the needed access; the permissions editor does not grant extra authority.

An empty event query does not prove that nothing happened. Check the time range, filters, read policy, retention, and collection failures. Event Viewer explains its access notices; Saving Event Evidence covers a capture for later investigation.

Installer Interfaces

Peios / Installing Peios

Peios Installer separates the work that changes the machine from the interface that asks you questions. You can use a terminal or browser while the same service owns the installation conversation.

installerd selects and modifies disks. oobed creates the first account and applies machine settings after installation. The services send questions, progress, and results through the Multi-Surface Interaction Protocol (MSIP), an independent protocol shared with their frontends.

The available interfaces have these roles:

TaskTerminalBrowser
Fresh installationinstall-tuiinstaller-gxwi
Upgrade or repairinstall-tuiNot supported
First-boot setupoobe-tuioobe-gxwi

The browser interfaces are GXWI overlays. Everyone who reaches the overlay sees the same conversation, without first signing in. Coordinate with other people using it and keep the machine on a trusted network until setup ends. Closing a browser or terminal does not cancel a running installation.

The interface process does not perform disk or account operations itself. Its configured identity still matters: the supplied first-boot terminal service runs as SYSTEM so it can reach setup before any administrator exists.

See Installing to Disk for a fresh installation and Conversation Lifetime for reconnect and failure behavior. Command details belong to installerd(8), install-tui(1), installer-gxwi(1), and oobed(8).

Preparing a PC

Peios / Installing Peios

Use an x86-64 UEFI image appropriate for the machine and a USB device large enough for that exact image. Preserve needed data from both the USB device and the intended installation disk. Writing the medium and installing the system are two separate destructive operations.

Prepare and boot the medium #

Use a raw image-writing workflow, not a file copy onto an existing filesystem. Check the whole USB device by model, size, and resolved identity; unmount its filesystems before writing and wait for a successful flushed write. A stable name does not replace checking the target.

The live boot hook looks for a disk, disc, or stick holding the medium's ISO 9660 filesystem. A multi-image loader that merely exposes an ISO file is not established as supported. If the boot hook cannot find its medium, check the image write and device discovery before rewriting or changing firmware.

Choose the UEFI entry in the one-time boot menu. Check the image's signing instructions against firmware trust; a development image is not automatically trusted by Secure Boot. Record firmware changes, particularly storage-controller mode changes that could prevent another installed system from booting.

Keep the live system on an appropriate setup network: installation and pending first-boot surfaces can be available before ordinary user sign-in. Use the image's documented live credentials rather than assuming every image has the same account or password policy.

Confirm the machine before installation #

Check the detected storage controller, intended disk, and network state. An unreadable or unrecognized filesystem is not empty. A visible wireless interface does not prove a usable wireless connection; use the deployed network tool's supported configuration path.

If using a browser, verify its certificate fingerprint against a trusted local console before submitting sensitive information. Certificate transfer to the installed system is best-effort, so repeat that verification if the fingerprint changes after installation. A browser reconnect failure is not proof that the installation failed; verify the local boot and address.

Continue with Installing to Disk. For an existing installation to preserve, use the documented repair or upgrade workflow instead of fresh installation. Keep the medium connected through the job, then remove it before selecting disk boot. Returning to the installer can mean firmware selected the USB device again, not that another installation is required.

After disk boot, complete the image's first-boot setup and verify sign-in. Hardware reports are evidence for their exact image and configuration, not a general compatibility certification for every model sharing a brand name.

Installing to Disk

Peios / Installing Peios

Use the installer to replace a whole disk with Peios. The installation copies the medium's pristine system and creates the files needed to boot from that disk.

Before you start #

Prepare these prerequisites:

  • A booted Peios installation medium appropriate for the machine.
  • A backup of every file you need from the target disk.
  • A way to identify the target by its device, model, and size.
  • Access to the terminal interface or the medium's GXWI browser overlay.

Warning

A fresh installation erases the entire selected disk. It does not preserve another operating system or provide a custom partitioning workflow.

Install the system #

  1. Select Install Peios on the first page.
  2. Select the target disk after checking its device, model, and size.
  3. Select Next to review the disk and the data that will be erased.
  4. Confirm the installation. In the browser, hold the confirmation button until its indicator completes.
  5. Wait for partitioning, formatting, copying, and boot preparation to finish. If a phase fails, read the reported error before retrying.
  6. Remove the installation medium when the machine is ready to boot from its disk, then use the offered restart action.

The installer refuses to partition a disk it finds mounted. The daemon's --force option only permits replacement of an unrecognized partition table; it does not bypass that guard or the confirmation page.

Check the result #

Confirm that the machine boots from the installed disk. An installation completion message reports that the job finished; it does not prove that firmware selected that disk or that the system booted successfully.

If the installed image includes first-boot setup, continue with Completing Setup. An image can instead provision accounts through its own configuration.

The browser saves job output through its log download. Keep that output if installation fails. Reconnecting to a running daemon can recover the conversation, but restarting the daemon loses its in-memory state.

Recovery and Upgrades

Peios / Installing Peios

The terminal installer can repair or upgrade a Peios system found on a disk. These operations have narrower purposes than a fresh installation; choose the operation that matches the fault.

Repair operations #

The repair flow provides three operations:

OperationEffectLimit
Boot repairRebuilds the initramfs and unified kernel image from the installed systemDoes not replace the system with the medium's release
Filesystem checkRuns a forced ext filesystem check with automatic safe repairsRefuses a mounted target and can require a restart
Permissions repairReplaces the root directory's security descriptorDoes not restore every explicitly set descriptor in the tree

Repair changes the selected system. Back up recoverable data before using it. A filesystem check can report a fault it cannot repair automatically; read the job result before using the disk again.

The supported layout has an Extensible Firmware Interface (EFI) system partition followed by the root partition. Repair is not a general disk-layout reconstruction tool. It does not guarantee recovery from every failed installation or setup attempt.

Upgrading from a medium #

The upgrade flow compares the installed release with the release carried by the medium. It requires the same edition and a newer version it can order. The flow rejects an equal version, a downgrade, an edition change, or versions it cannot compare.

An upgrade reconciles packages against the medium and applies the installed system's upgrade seeds, then regenerates boot files. It preserves the installed machine's GXWI key rather than carrying the medium's key over.

Use install-tui(1) for either workflow. The graphical installer does not render the later upgrade and repair pages and refuses to advance into them.

Installation Process

Peios / Installing Peios

A fresh installation builds a disk-based system from the installation medium. Understanding the stages helps distinguish a discovery problem from a failure after the target has already changed.

Discovering disks #

The daemon lists devices, partitions, and recognizable systems so you can identify the target. When it inspects an unmounted filesystem, it uses a read-only loop device. Ext filesystems also use the noload option to avoid journal replay during inspection. An already mounted filesystem is read through its existing mount.

To identify a Peios release, the daemon reads the closure the disk's package store names SYSTEM: its edition from its os-release, and the edition's version from its inventory. The name must name a closure in the store, and the inventory and os-release must open as regular files; symbolic links and special files are rejected. A system with no edition is named by its closure's identity. Unsupported or unreadable content is not proof that a disk is empty.

Creating the layout #

After confirmation, the daemon creates an Extensible Firmware Interface (EFI) system partition and a root partition using the remaining space. It formats the first as FAT32 and the second as ext4. The root filesystem receives its security descriptor during formatting, before normal access to the copied system begins.

This workflow replaces the whole disk. It does not configure disk encryption, a separate home partition, or another operating system's boot menu.

Composing the installed system #

The installed system is composed from the medium's packages, not copied from the live session. The medium says what an installed system holds, in /install/system.toml and /install/initramfs.toml. The daemon copies the packages those need from the medium's store into the target's /system/artifacts, builds them into two closures, and names them SYSTEM, the installed system's /usr, and INITRAMFS, what its initramfs is built from. The root's directories outside /usr come from the root skeleton file. Changes made while running the installer, including live account changes, don't reach the installed system.

The installer carries the medium's local policy and settles its registry seed queues. Seeds staged only for installation are promoted into the target queue; live-session provisioning is not copied as an instruction to repeat on every installed boot.

The GXWI key and certificate are carried from the live session. Their transfer preserves browser continuity when it succeeds, but installation is allowed to continue if that transfer fails.

Preparing disk boot #

The installer generates the kernel command line using the root filesystem's universally unique identifier (UUID), so a later device-name change does not select a different root by accident, and keeps the consoles the medium was booted with.

Boot preparation composes the initramfs from INITRAMFS and builds the unified kernel image from it and SYSTEM's kernel, at the EFI fallback location. It checks that the initramfs includes the disk root-mount hook and excludes the live one. At boot, that hook mounts the root partition and mounts the SYSTEM closure at /usr.

These checks validate generated content. Firmware selection and a successful boot still need to be observed on the target machine or a representative disposable guest.

Completing Setup

Peios / First-Boot Setup

First-boot setup creates an administrator account and names the machine. The terminal and browser interfaces use the same conversation, so you can change interfaces without starting a second setup.

Before you start #

Make sure you have these prerequisites:

  • An installed image that includes and activates the first-boot services.
  • Access to the machine's console, or its trusted GXWI browser connection.
  • A password for the administrator account you will create.

For browser setup, verify the machine's certificate through a trusted console before entering a password. See Browser Setup.

Complete the conversation #

  1. Continue from the welcome page. Language and keyboard choices shown as unavailable are configured after setup in System Settings.
  2. Review the network state. Continue without networking on the console, or supply a manual address for a wired interface if needed.
  3. Enter the administrator account name and matching passwords, then select Next. Correct any field errors before continuing.
  4. Enter a machine name or accept the suggestion.
  5. Select Finish to create the account, set the machine name, and apply any manual network setting.
  6. Sign in with the account and password you created.

The machine name is a single label of up to 63 letters, digits, and hyphens. It cannot start or end with a hyphen or be localhost. Account names are trimmed and must fit the local account store's rules. Reserved group names and peios-oobe-setup are rejected.

Passwords cannot contain a carriage return or line feed. Setup rejects those characters before starting account creation; it preserves Unicode, spaces, and tabs in accepted passwords.

The browser's password strength meter offers advice. It does not replace the daemon's validation or guarantee that a password is hard to guess.

Check the result #

Confirm that your account can sign in and that the machine uses the name you chose. If you configured a manual address, check reachability from a device on that network. A subsequent boot should reach sign-in without repeating setup.

Setup removes its service definitions only after successful completion. Closing the interface or encountering an error leaves setup available for another boot. A sign-in prompt after an abandoned attempt does not prove that an account was created.

If no usable account exists and setup repeatedly fails, use the installation medium for diagnosis. Repair operations have specific limits; they are not a general account-recovery mechanism.

Browser Setup

Peios / First-Boot Setup

The browser setup page is a GXWI overlay available before normal sign-in. oobed owns the setup operation, while oobe-gxwi presents the conversation and forwards your answers.

A shared conversation #

All connected browsers observe the same page and completed choices. Coordinate with anyone else using setup. Typed account fields stay in the browser until submission, and the frontend does not broadcast the password to other viewers.

The overlay is available without normal sign-in. Before offering it, oobed creates or reuses the passwordless account peios-oobe-setup and includes that account in the setup socket's intended access descriptor. The account has no groups. A sign-in mechanism that accepts passwordless accounts can also accept this account while it exists.

Successful setup removes the overlay and the temporary account and its home directory. An unfinished setup keeps them for another attempt. Keep the machine on a trusted network during this period.

Check the connection #

Use the address advertised on the machine's own console. When GXWI uses a self-signed certificate, compare its SHA-256 fingerprint with the trusted console's reading before sending credentials. A page received over the unverified connection cannot authenticate that same connection.

The console reads the fingerprint from /var/state/gxwi/certificate.sha256. The browser installer deliberately does not present that value as a source of trust.

A fresh installation attempts to copy the medium's GXWI key and certificate to the installed system. Failure to copy them does not fail installation. Verify the certificate actually presented after restart; installation success does not establish that the certificate stayed the same.

Direct development listeners created with --listen serve HTTP without GXWI's TLS termination. Use those listeners only with synthetic credentials in an isolated development environment. Production certificate handling belongs to GXWI.

Returning to sign-in #

After setup completes, oobed removes the overlay and GXWI restores its sign-in page. The browser waits for that transition. If automatic return fails, check the machine's console and reopen its verified address.

A manual network change is applied at the end of setup. The browser can lose access if its device cannot reach the resulting network, or if the new address needs a fresh certificate trust decision. Verify the address and certificate before entering credentials again.

Network Choices during Setup

Peios / First-Boot Setup

Setup shows network state reported by net status. You can continue on the console without a network, or configure a manual address for a wired interface. Joining a wireless network is not part of this setup flow.

The network page reports each interface and its addresses, gateway, and name servers. Check again refreshes that state. In a browser, the page also identifies the interface used to reach the machine when it can match the address.

A manual address is saved as a pending choice. It does not change the connection while you complete the account and machine-name pages. Setup applies it after creating the account and naming the machine.

The daemon writes an ordinary network profile and an interface rule under Machine\System\Network. The rule identifies the interface by its stable identifier. These settings belong to the network service and can be changed through its normal tools after setup.

Before finishing, check that your browser's device can reach the address you chose. If it cannot, use the console to finish and inspect the connection. A browser that stays on its waiting page does not prove that the network change failed.

Signing In

Peios / Signing In

Use a sign-in route enabled by the machine's image and configuration. On an installed image with setup enabled, complete first-boot setup first. A custom image needs a first-account provisioning route.

Choose a client #

ConnectionGuideCheck before entering credentials
Browser desktopSigning in from a BrowserVerify the machine's certificate fingerprint through a trusted route
Local consoleUsing a ConsoleUse the managed console on the intended machine
Remote terminalSigning in with SSHVerify the SSH host fingerprint

Switching virtual consoles does not lock or end the session left behind. Rejoining a browser desktop can return to its existing session rather than create a new one.

Change your own account #

Use My Settings for your display name, password, and SSH keys, or passwd from a terminal. Self-service credential changes require the proof accepted by the principal source; a session token alone does not replace that proof.

Changing another account is an administrative operation. Start with Local Accounts or Principals Manager.

A stored password and credential policy are separate. Setting a password does not stop credential-free sign-in until the account's policy requires it. Follow Managing Credentials, then verify a fresh sign-in before closing the working session.

Recover from a refusal #

Follow Diagnosing Authentication and preserve a working administrator route. Do not delete the local store to clear an error: it holds account identities, and an unreadable store is not an unprovisioned machine.

For the model behind the prompt, read Authentication Conversations and Sessions and Account Changes.

Signing in from a Browser

Peios / Signing In

GXWI displays the Peios desktop in a browser. Applications run on the Peios machine, using the authority of the account that signs in.

Before you start #

You need the machine's address, its configured HTTPS port, and an account on that machine. The default port is 7780. A machine that listens only on the built-in address 127.0.0.1 needs a reachable listen address and network policy before another device can connect.

You also need a trusted way to read the machine's certificate fingerprint, such as its local console. Do not enter credentials before verifying an unfamiliar certificate.

Open the desktop #

  1. Open https://<machine-address>:7780 in your browser. Replace <machine-address> with the machine's address or name. Use its configured port if it differs from 7780.
  2. If the browser warns about the certificate, follow Verifying the Machine's Certificate.
  3. Enter your account name and complete the requested authentication.
  4. Check that your desktop appears. Open an application to confirm that the session is ready.

An HTTP request redirects to HTTPS. GXWI does not serve a desktop over an unencrypted connection.

If an installer or setup program appears, the machine is using an overlay. Follow that program's instructions. Normal sign-in and existing desktops remain inaccessible while the overlay is configured.

Leave and return #

Closing a browser tab does not request the end of the desktop session. Sign in again to reconnect to a running session. Unsaved application state survives only while the application and its session remain running.

Use the desktop's sign-out action to end the session. Do not treat closing a tab on a shared device as signing out of the machine.

Verifying the Machine's Certificate

Peios / Signing In

GXWI creates a certificate for the machine rather than relying on a public certificate authority. Verify its fingerprint before trusting an unfamiliar certificate or entering credentials.

Before you start #

Use the machine's trusted local console or another independently verified channel. A page delivered through the connection being checked cannot establish that connection's identity.

Compare the fingerprints #

  1. At the trusted console, read /var/state/gxwi/certificate.sha256. The file contains the certificate's SHA-256 fingerprint and is public.
  2. In the browser's certificate details, find the SHA-256 fingerprint of the certificate presented by the machine.
  3. Compare all 32 byte pairs. Spaces or colons between pairs do not affect the value. If the fingerprints differ, do not sign in.
  4. If they match, check the certificate's name and validity period before accepting it or importing it into your browser's trust store.

A matching fingerprint ties the presented certificate to the certificate read through the trusted channel. It does not establish that a different hostname is valid for that certificate.

Trust the verified certificate #

The public certificate is /var/state/gxwi/certificate.pem. Transfer it through a trusted channel and import it using your browser's or operating system's certificate controls. Import only the certificate, never key.pem.

The generated certificate includes the hostname at creation, localhost, 127.0.0.1, and ::1. Other network addresses are not included automatically. Inspect the certificate actually presented; importing it does not fix a name mismatch or expiry.

Browser trust affects more than the warning page. The waiting page uses a service worker, which requires a browser environment that permits it. A certificate exception does not guarantee that the browser permits service workers.

Check again after a change #

Certificate renewal changes the fingerprint even when the private key stays the same. Verify the replacement through the trusted channel before importing it.

Installation and first boot #

Installation, a restored machine image, or loss of persistent certificate state can also change the presented certificate. Installation completing does not prove that the certificate was retained. Verify the installed machine's fingerprint before entering credentials.

Signing in at a Console

Peios / Signing In

The login(1) client collects credentials at a terminal, receives a token from authd, installs it, and replaces itself with your shell. Use the managed console provided by the system; running login does not grant an ordinary process permission to originate a logon.

Sign in #

Follow these steps:

  1. At the console's account prompt, enter your account name.
  2. Answer the credential prompts. Password input is not echoed.
  3. Check that the intended account's shell starts in its home directory.

The terminal client supports password prompts. Accounts restricted to SSH public-key authentication need a client that supports that exchange.

Credential input uses buffers that erase their contents when released. This also applies to partial input when reading a credential from a pipe fails. The input source and any copies made by the caller remain their owners' responsibility.

If the account's home is unavailable, login reports the failure and starts in /. A successful sign-in does not prove that the recorded home or shell is usable. A shell that cannot be executed causes the client to fail.

Named attempts and automatic sign-in #

A managed console can select an account before presenting a prompt:

  • A named account: a refusal ends that attempt.
  • --try: a nonfatal refusal falls back to an account prompt.
  • --try-no-password: an attempt that offers no credential collection; an account needing credentials falls back to the ordinary prompt.

A fallback is explained if the attempt already displayed a credential prompt or message. If nothing was displayed, the client moves directly to the account prompt. An unavailable authority or a caller that cannot originate the logon ends the attempt: asking for another account would not repair that failure.

The preliminary account lookup uses read and write timeouts. If the client cannot set those timeouts, it treats the lookup as unavailable and continues without claiming that the account exists or is absent.

These options do not bypass authentication. authd and the principal source still decide whether to grant a token. The -f authentication bypass is not supported.

Credential-free automatic sign-in requires an account whose credential policy permits it. Its use is not restricted to one console by the account policy alone. Keep such accounts limited to deliberate development or live image use.

Managed console services #

The shipped console seed defines the primary login-console service and additional prompts on tty1, tty2, and tty3 when those devices exist. Images choose whether to apply that seed. The primary console's precedence prevents a second prompt taking the same terminal; first-boot setup takes precedence over ordinary prompts.

Peinit fixes /dev/console to its selected terminal when loading the service configuration. Switching virtual consoles does not move that service or lock the session left behind. Its terminal ownership and exit rules control cleanup and the next prompt.

System Settings changes the selected account through the console service's arguments. The next service start uses the changed arguments; it does not replace an already running session or change the account's credential policy.

Session preferences #

Without -p, the client constructs the shell environment from the granted profile. It sets the account and home variables, sets PATH to /bin, and preserves or chooses the terminal type.

Locale preferences come from the machine and the granted account's user registry settings. The client removes inherited LC_ALL and LANGUAGE and refreshes locale preferences even with -p. Locale changes apply to later sessions, not programs that already inherited an environment.

The managed --console mode also prepares terminal input and waits for first-boot setup to finish before accepting credentials. Browser-address information is optional; its absence does not prevent terminal sign-in.

The browser banner is printed once per invocation. It contains configured addresses and the machine's certificate fingerprint, not a health check of the browser service. A reachable address still needs the certificate check described in Signing in from a Browser.

For all flags and environment details, read login(1). For failures, use Diagnosing Authentication.

Signing in with SSH

Peios / Signing In

Use Secure Shell (SSH) to open a remote shell, run commands, or transfer files with SFTP. The dev.peios.openssh package provides the sshd service. SSH Settings and the ssh-settings command manage the same server settings.

Every SSH connection uses a RemoteInteractive logon, including commands without a terminal and SFTP transfers. The account must permit that logon type. See Granting Access.

Passwords require a credential policy of password or either and a stored password. SSH keys require an enrolled key and a policy of key or either. An account with policy none cannot sign in over SSH. The server does not read authorized_keys files. Principal key enrollment belongs to lpsd.

Connect from another computer #

Before you start, establish a trusted administrator connection at the local console or through a certificate-verified GXWI browser session.

  1. Read the network address, server status, port, and host-key fingerprint:

    net status
    ssh-settings
    ssh-settings fingerprint
    

    Check that the server is running. Choose an address reachable from the other computer. See The net Command. A VM's forwarded host port can differ from the server's listening port.

  2. From the other computer, connect with the observed port:

    ssh -p <observed-port> <account-name>@<machine-address>
    

    Compare the first-connection fingerprint with the trusted reading. This is the SSH host key, not GXWI's TLS certificate fingerprint. If the fingerprints differ, stop and investigate. Do not accept the key or remove a remembered key to suppress a warning.

  3. Sign in and verify that a new shell opens. An existing session does not prove that a new connection can authenticate.

Looking #

Show the server settings:

ssh-settings

The output reports whether the service runs, its port, whether passwords are accepted, and the host fingerprint. SYSTEM and Administrators can read the host key; other users see an explanation instead of its fingerprint.

The server uses these settings:

SettingSourceShipped value
Start at bootMachine\System\Services\sshd DisabledOn where the service seed is installed
Listening portMachine\Software\OpenSSH Port22
Password sign-inMachine\Software\OpenSSH PasswordAuthentication1
Host identity/var/state/sshd/ssh_host_ed25519_keyCreated on first start

Port and PasswordAuthentication are REG_DWORD values. The startup helper passes them to sshd on its command line. Setting either option in /lcl/etc/ssh/sshd_config has no effect. That file holds other administrator overrides, subject to the Peios port's fixed restrictions.

Turning it on and off #

Start the service and configure it to start at boot:

ssh-settings on

Stop the service and keep it from starting at boot:

ssh-settings off

Stopping or restarting the service disconnects every SSH session. Keep a separate console or GXWI administrator connection available before doing so.

Changing the boot setting requires write access to the service registry key. Starting or stopping the service also requires peinit's service-control rights. Without those rights, the command saves the boot setting and explains that it cannot change the running service.

Moving the port #

Move the server to port 2222:

ssh-settings port 2222

The command changes the port setting, sshd's port reservation, and its firewall rule in one registry transaction. If the optional ssh firewall rule is absent, the command does not create it. A running server then restarts and disconnects all SSH sessions. Reconnect using the selected port.

A port reserved exclusively for another service is refused. A broader reservation, such as tcp:1-1023, permits a more specific reservation within its range. See Port Reservations and Configuring Profiles.

Keys only #

Turning off SSH password authentication changes the server's accepted methods. It does not change account credential policy. Keep an account's policy either if its password must also work through GXWI, which uses password sign-in. An account with policy password cannot sign in over SSH while SSH password authentication is off.

Before turning off passwords:

  1. Enroll a key for each account that needs SSH. Use My Settings where permitted, or have an administrator run lps key add. Adding a key does not change policy; an administrator can select either with lps policy. See Managing Credentials.
  2. Check lps show and lps key list for the enabled account, enrolled key, credential policy, and permitted remote-interactive logon type.
  3. Make a fresh SSH connection that authenticates with the enrolled key. Password fallback does not count as a key test. Stop if this fails.
  4. Verify a separate administrator sign-in at the console or through GXWI. Keep that connection available. Another SSH session is insufficient: restarting sshd disconnects every SSH session.

After verifying both routes, turn off SSH password authentication:

ssh-settings passwords off

Make another fresh key-authenticated connection and verify that its shell opens. If this fails, use the surviving administrator route to restore password acceptance:

ssh-settings passwords on

This also restarts sshd and leaves account credential policy unchanged. The last-administrator guard does not prove that a working sign-in route exists. Keep the separate route until fresh SSH access works again.

The host key #

Read the host-key fingerprint through a trusted administrator connection:

ssh-settings fingerprint

The service creates its Ed25519 host key on first start, validates an existing key, and never rotates it automatically. The private key is installation state, not a package file. Do not share it or copy it between machines.

On the desktop #

Open SSH Settings from the launcher. The page shows the service, port, password setting, and host-key fingerprint. Use Copy to copy the fingerprint. Unavailable operations show the reason.

Starting the server takes effect immediately. Stopping it, moving its port, or changing password acceptance requires confirmation because it disconnects SSH sessions. The result states whether the running service changed or the saved setting applies when the service next starts.

Supported sessions #

The server supports interactive shells, remote commands, terminals, and internal SFTP. TCP, Unix-socket, agent, X11, and tunnel forwarding are off. Host-based authentication, keyboard-interactive authentication, certificates, and external authorized-key providers are not accepted by this port.

The shared PGSS SSH public-key authentication specification defines the authd, lpsd, and monitor contract. The Peios port accepts plain Ed25519 and RSA SHA-256/SHA-512 signatures with RSA keys from 3072 through 8192 bits. The monitor binds authentication to the initial SSH exchange. Principal policy and account status still determine whether authentication succeeds.

Exit status #

The CLI uses these exit codes:

CodeMeaning
0The operation or display succeeded.
1The operation failed or was refused.
64The command line was invalid.

The Desktop

Peios / Using Peios / Desktop Basics

The Peios desktop runs in a web browser. You sign in to the machine from a browser page, and the machine shows your desktop session there: application windows, a dock, a launcher, and a top bar. The applications themselves run on the Peios machine, with the authority of the account you signed in with. Knowing which program provides each part tells you where to look when something is missing or doesn't apply.

The parts of a session #

Three programs work together in every desktop session:

  • GXWI serves the session. It presents the sign-in page, asks the machine's authentication service to check your credentials, and carries the session's traffic between your browser and the machine.
  • Fenestra is the compositor. It tracks the applications in the session and arranges their windows into tiles and workspaces.
  • Fenesh is the shell. It provides the background, top bar, dock, launcher, and power menu, and the Desktop Settings and Get started applications.

Fenestra and Fenesh run as your account, so they can do only what your account can do. Fenestra starts whichever shell the machine is configured to use. If none is configured, Fenestra shows its own minimal taskbar and launcher instead. The Desktop Shell and The Desktop Compositor describe each program in more detail.

One session on several devices #

You can open the same session from more than one device. Some state belongs to the session, and some to each browser page:

StateBelongs to
Open applications and their windowsThe session
The workspace each window is onThe session
Window size, position, and focusEach browser page
The workspace you are viewingEach browser page

Closing a window or moving it to another workspace therefore affects every device attached to the session. A new window opens on the workspace that was last selected on any device.

Closing a browser tab doesn't end the session. Sign in again to return to it, or use the desktop's sign-out action to end it.

Where to start #

These guides cover everyday use of the desktop:

  • Using the Launcher and Dock to start applications and switch between windows.
  • Arranging Windows and Workspaces to resize tiles and move between workspaces.
  • Desktop Settings to change the wallpaper, clock, dock, and keyboard shortcuts.
  • Everyday Applications to find the application for a file, account, or system task.

If something doesn't appear or doesn't apply, start with Troubleshooting Desktop Settings and Applications or Troubleshooting Windows and Desktop Connections.

The Desktop Shell

Peios / Using Peios / Desktop Basics

Fenesh provides the background, top bar, dock, launcher, and power menu in a Peios desktop session. GXWI serves the session, and Fenestra arranges its windows. Fenesh is the shell application inside that session.

The component includes three programs:

ProgramRole
feneshDesktop shell surfaces and session controls
fenesh-settingsDesktop Settings for personal choices and machine defaults
fenesh-welcomeThe Get started window with introductory desktop actions

The shell runs as the signed-in account. Fenestra grants the configured shell its desktop role. Starting an unrelated application does not make it part of the shell. Desktop Settings and Get started are ordinary desktop applications, with the same account permissions as the session.

What the shell stores #

Fenesh stores personal wallpaper, clock format, dock pins, and the welcome marker in your registry settings. Machine defaults are separate. Deleting a personal override restores the corresponding machine default, except for the welcome marker, which enables another automatic welcome attempt.

Fenesh does not own account credentials, window tiling rules, the application catalog format, or shared keyboard-shortcut and file-opening contracts. Those belong to the components that provide them. Desktop Settings presents controls for some of those shared settings.

The Desktop Compositor

Peios / Using Peios / Desktop Basics

Fenestra arranges windows in a Peios desktop session. Its Rust process tracks applications and surfaces, while its browser page chooses each window's size, position, and focus. The same session can appear on several devices with different layouts.

GXWI starts Fenestra after sign-in and routes authenticated session traffic to it. Fenestra runs as the session account. It does not receive your password or perform the browser's sign-in authentication.

Compositor and shell #

The compositor manages surfaces; the shell provides controls such as a dock and launcher. Fenestra starts the configured shell and grants it access to desktop-wide operations. Fenesh is one shell that uses those operations. Fenestra also includes a minimal taskbar and launcher for sessions without a configured replacement.

The package contains three programs:

ProgramRole
fenestraSession compositor, application connections, and desktop page
fenestra-taskbarFallback panel with a button for each window
fenestra-launcherFallback application search overlay

The fallback programs do not provide Fenesh's wallpaper settings, pinned dock, welcome application, or power menu. Choosing a shell changes those controls without replacing Fenestra's window manager.

Shared and local state #

Application surfaces and their workspace assignments belong to the session. Closing a surface or moving it to another workspace affects every device attached to that session. Window geometry, focus, dialog position, and the workspace being viewed belong to each browser page.

The workspace last selected on any device determines where a subsequent application window opens. Two devices viewing different workspaces therefore share the choice of destination for that window.

Using the Launcher and Dock

Peios / Using Peios / Desktop Basics

Use these controls inside a signed-in desktop session. Your active shortcuts appear in Get started and Desktop Settings.

Start an application #

Use the launcher to find an installed application:

  1. Select the Peios mark at the bottom of the dock, or press the launcher shortcut. The built-in shortcut includes Ctrl+Space.
  2. Type part of the application's name.
  3. Use the arrow keys to select a result, then press Enter. You can also select the result with the pointer.

Press Esc to close the launcher. It shows up to 12 matching applications. It reads application declarations from the system catalog, so a program needs a valid declaration to appear.

Pass simple arguments #

The launcher accepts whitespace-separated arguments after an application selector. For example, use an application ID followed by a file path that contains no spaces. The selected application's declared arguments come before the additional arguments.

If the entire input matches an application's name or ID, the launcher treats all of it as the selector. Otherwise it treats the first word as the selector and the remaining words as arguments. It does not implement shell quoting, variable expansion, pipelines, or shell commands. Use a terminal when you need those features.

Switch between windows #

The dock shows pinned applications first, followed by other running programs. Select a running program's icon to cycle through its windows, or select a window's dot to focus that window directly. With the built-in shortcut, Alt+1 through Alt+9 select the first nine dock entries.

Separate processes can have separate dock entries even when they belong to the same application. The first running instance occupies its pin; additional instances appear with other running programs. An idle pin starts the application when selected.

Use an application's menu #

Open a dock entry's context menu to see its available actions. Declared applications offer Open or New window, and pin controls. Running programs offer Close or a control to close all their windows. Closing requests are sent to the application, which decides how to handle unsaved work.

To keep an application on the dock, select Pin to the dock. Drag its pin to change its position. Select Unpin from the dock to remove it. For default and error behavior, see wallpaper, clock, and dock.

Arranging Windows and Workspaces

Peios / Using Peios / Desktop Basics

Use these controls inside a signed-in desktop session. Keyboard examples use the built-in assignments; personal or machine shortcuts can replace them.

Arrange tiled windows #

Application windows share the available desktop area. A window opening on a workspace takes part of the focused tile, and closing a tile returns its space to its neighbor.

To resize adjacent tiles:

  1. Find the separator between the windows.
  2. Drag the separator to the required position.
  3. Release it to keep that split on this browser page.

For keyboard operation, press Tab until the separator has focus, then use the arrow keys along its direction. The layout keeps both sides within its allowed minimum size. Resizing on one device does not resize another device's layout.

Alt+J focuses the previous tile and Alt+K focuses the next tile. On a viewport narrower than 640 pixels, only the focused tiled window appears. Side panels move to the bottom so they do not consume the narrow width.

Change workspaces #

Workspaces group windows within the session. To move between them:

  1. Press Ctrl+Alt+Right Arrow to select the next workspace, or Ctrl+Alt+Left Arrow to select the previous one.
  2. Open an application to place its window on the last selected workspace in the session.

To move the focused window and follow it, add Shift to the corresponding workspace shortcut. A dialog can also move between workspaces.

Fenestra supports up to 16 workspaces. Below that limit, an empty workspace is available after the last occupied workspace. Empty gaps collapse as windows move or close, so workspace numbers can change. The last selected workspace is retained while empty.

Use dialogs #

Dialogs float over tiled windows instead of taking a tile. You can continue using other windows while a dialog is open. To reposition one, drag its title strip. The position changes on this browser page only.

Selecting a dialog brings it in front of other dialogs. Closing it returns focus to the earlier window when that window still exists. On a narrow viewport, the dialog uses the available window width.

Inspect a window's identity #

Select the application icon in a window's title strip to show the application and process information supplied by Fenestra. Select it again to hide the information. This information comes from the connected process, rather than text supplied inside its page.

If an application page cannot cooperate with desktop keyboard handling, the strip keeps an explanatory identity label visible. Use the compositor controls or another cooperating window when a shortcut is not received inside that application.

Using the Welcome and Power Controls

Peios / Using Peios / Desktop Basics

The Get started window introduces the launcher, dock, and desktop layout. Its shortcut hints use your active assignments. Buttons to open files or a terminal appear only when the corresponding applications are installed.

Reopen the welcome window #

Use the launcher in a signed-in desktop session:

  1. Open the launcher from the Peios mark on the dock.
  2. Search for Get started.
  3. Select the application.

You can also select Show Again in the Dock section of Desktop Settings. That action clears the automatic welcome marker as well as attempting to open the window.

At session startup, Fenesh attempts to open Get started when the welcome application is installed and the account has no welcome marker. It writes the marker before launching. A launch failure therefore does not retry at every subsequent session. If the marker cannot be read, Fenesh skips the automatic launch; if it cannot be written, Fenesh also skips the launch.

End a session or shut down #

Save your work before using the power menu:

  1. Open the power menu from the top bar.
  2. Choose the action for your intended result.

The menu offers three actions:

  • Log off ends your desktop session through the session service.
  • Restart requests a machine restart from the service manager.
  • Shut down requests a machine power-off from the service manager.

Restart and shutdown affect the machine, including other sessions. The service manager authorizes the request using your account; Fenesh does not bypass its policy. If the request fails or is refused, Fenesh restores the desktop and displays the error. Read that error before retrying.

Session Transitions

Peios / Using Peios / Desktop Basics

Fenestra's browser page connects the sign-in screen to the desktop and shows when a session or machine becomes unavailable. These displays communicate session state; they do not authorize a restart or prove that a machine has powered off.

Entering the desktop #

When GXWI passes its sign-in animation state to the page, Fenestra shows the arrival transition while the shell starts. Without that saved state, the page displays the desktop directly. Reduced-motion preferences shorten the movement.

The first-session greeting is selected when Fenestra creates the account's CurrentUser\Software\Fenestra key. An existing key means the session is not treated as the first, even if another application created the key. A registry failure also uses the non-first-session behavior. Only the session's first browser attachment receives the first-session flag.

The arrival display waits for shell panels and backgrounds to become ready. A shell can declare how many parts to expect. Without that count, the page uses readiness and a settling interval. A 10-second upper bound prevents the arrival display from waiting indefinitely for a broken shell. The desktop appearing after that bound is not evidence that every shell program started successfully.

Reconnecting a page #

The compositor sends a complete surface list and the active shortcut map when a page attaches. A disconnected page reconnects and receives another snapshot. A page that falls too far behind the compositor's change stream is disconnected so it can reconnect from a complete snapshot.

An application surface lasts while its application connection exists. Reconnecting a browser does not recreate a process that has exited. Raw application pages can also have browser-local state that does not survive a page reload; shared live application state belongs to the application process.

Restart, shutdown, and loss of contact #

A trusted shell can announce a restart or shutdown to every page showing its session. The page displays the departure animation and checks whether GXWI answers again. The shell remains responsible for requesting the machine operation from the service manager.

If the shell withdraws its announcement after a refusal, the page returns to the desktop and stops the outstanding availability check. Delayed callbacks from that canceled attempt cannot redirect the restored desktop or interfere with a later attempt. A shutdown message in the browser is not an independent hardware power-state check.

When a session connection closes and GXWI also stops answering, the page reports loss of contact and waits for the address to return. This can mean a machine restart, a network interruption, or another availability problem. It does not identify the cause. When the expected reconnect conditions are met, the page returns to sign-in.

Using the Fallback Taskbar and Launcher

Peios / Using Peios / Desktop Basics

Fenestra starts its companion taskbar and launcher when the machine has no valid shell override. These controls are separate from Fenesh's dock and launcher. Use this guide when your session shows the minimal taskbar.

Select a window #

The taskbar has one button per ordinary window, including its icon and title. Select the button to focus that window on your device. With the built-in shortcuts, Alt+1 through Alt+9 select the first nine buttons.

The taskbar lists windows rather than application groups. Several windows from one application therefore have separate buttons. Dialogs are not listed as ordinary windows. The taskbar does not store pinned applications.

Start an application #

Use the fallback launcher inside the desktop session:

  1. Press Ctrl+Space or Alt+P to show the launcher, unless your shortcuts have been changed.
  2. Type one word from the application's title or its application ID.
  3. Use the up or down arrow to select a match, then press Enter.

The launcher shows up to 12 matches. Press Esc to close it and clear the search. It reads the installed application catalog when matching or starting an application.

Supply arguments #

The first whitespace-separated word selects applications. Every remaining word becomes an additional argument after the application's declared arguments. A multiword application title is therefore not treated as one selector. Use its ID or a single matching word when supplying arguments.

The launcher does not support shell quoting, variable expansion, or pipelines. Use a terminal for commands that need those features. An application that fails to start is reported in the launcher's error output.

Change shortcuts #

The taskbar and launcher follow the session's shared shortcut settings. The taskbar uses DockItem, and the launcher uses Launcher. Changes are watched while the session runs.

Desktop Settings, when installed, provides the controls for personal and machine shortcuts. It is part of Fenesh, not the fallback shell. The installed Fenestra registry reference describes the stored values.

Troubleshooting Desktop Settings and Applications

Peios / Using Peios / Desktop Basics

Use the visible error message first. Fenesh also writes diagnostic messages to standard error. Where those messages are collected depends on how your desktop session was started.

A changed setting does not appear #

Check the setting and its scope before restarting anything:

  1. Reopen the relevant section in Desktop Settings and check whether the value was saved.
  2. Check for a personal override if you changed a machine default. Choose System Default for your account if you want to follow that default.
  3. Read any permission or save error in the settings window.
  4. If an immediate shell setting is saved but unchanged on the desktop, inspect the shell's error output for a failed registry watch. Start another desktop session to reread the settings.

Sign-in appearance, icon themes, and advanced settings have their own activation points. See settings for all users.

A wallpaper falls back to the embedded image #

Check that the selected path is absolute, readable by the session account, and names a supported regular image file of at most 16 MiB. Symlinks to regular files are accepted; pipes and other special files are rejected. A machine wallpaper must be readable by every intended account. A selected but unusable personal image falls back to the embedded image, not the machine image.

A supported extension does not prove that image contents can be decoded. Try a known valid image. If you replaced a file at the same path, select it again or start another session; Fenesh does not watch image files.

An application or pin is missing #

The launcher lists declared applications in the system catalog. Check that the package and its application declaration are installed. A running program without a declaration can appear on the dock but cannot be pinned or restarted from its menu.

A pin for an uninstalled application stays in your saved list and is hidden. Reinstalling that application makes the pin visible again.

A shortcut is refused #

Choose a combination that includes Ctrl, Alt, or Meta and that the browser does not reserve. If another action has that shortcut, remove the existing assignment before adding it to the intended action. A reset can also create a conflict with an override; resolve the reported conflict first.

The welcome window does not open automatically #

Search for Get started in the launcher. If it is absent, install the welcome application. If it opens manually, use Show Again in Desktop Settings to clear the marker for another automatic attempt. Check the shell's error output if reading or writing the marker fails.

Troubleshooting Windows and Desktop Connections

Peios / Using Peios / Desktop Basics

Fenestra writes failures and shell restarts to standard error. The place those messages are collected depends on how GXWI starts the session. Keep session authentication failures separate from compositor failures: GXWI owns sign-in and browser routing.

Shell controls are absent #

Check startup and configuration before repeatedly restarting the session:

  1. Read the session's Fenestra messages for display-socket or shell errors.
  2. Inspect Machine\Software\Fenestra Shell. An empty list intentionally starts no shell; an absent value selects the fallback programs.
  3. Check that each configured executable exists and can run as the session account. A valid but missing executable does not select the fallback.
  4. Correct the cause and start another desktop session.

Fenestra needs the runtime directory provided by GXWI to bind its display socket. If binding fails, it reports that applications are unavailable and does not start shell applications. A browser page appearing is therefore not enough to establish that application transport is working.

A window is missing #

Check the workspace and application before assuming data was lost:

  1. Move through the workspaces using your configured shortcuts.
  2. If the viewport is narrow, focus another tiled window with the taskbar, dock, or tile shortcut. Only one tiled window is visible at a time.
  3. Check whether the application process has exited or disconnected.

Moving a window from another device changes its workspace for the whole session. Window geometry and focus remain local to each device. A closed application connection removes its surfaces from every attached page.

Shortcuts do not work inside an application #

A browser can reserve a combination before the desktop receives it. Choose a different shortcut in Desktop Settings if available. An application's raw page also needs to cooperate with desktop keyboard forwarding. An explanatory label stays visible on pages that do not cooperate.

When shortcuts were edited directly, check for conflicting assignments. The window manager's claimed shortcut takes precedence over a shell claim. Among shell claims, the first claim wins. Use the settings controls to avoid introducing these conflicts.

A debug window appears unexpectedly #

The desktop page includes diagnostic key bindings when the compositor page itself has keyboard focus. Space requests a debug surface. Enter attempts to start gxwi-hello-app beside Fenestra; Shift+Enter requests its raw-page mode. These are diagnostic controls, separate from the application launcher. Focus an application window to enter ordinary application input.

The page waits for the machine #

Check whether the machine and its GXWI address are reachable from another administrative connection. A loss-of-contact display cannot distinguish a network failure from a stopped service or machine. Avoid repeating a power operation until the actual machine state is known.

Desktop Settings

Peios / Using Peios / Desktop Settings

Desktop Settings changes your wallpaper, clock, dock, keyboard shortcuts, and default apps. Open the launcher from the Peios mark on the dock, type desktop, and select Desktop Settings.

The window separates personal choices from machine defaults:

GroupSectionsScope
For YouWallpaper, Clock, Dock, Keyboard Shortcuts, Default AppsYour desktop settings
All UsersSign-In Screen, Desktop, Keyboard Shortcuts, Default Apps, AdvancedMachine settings and defaults

System Settings handles other machine settings. My Settings handles your account, including your password. Those applications are separate from Desktop Settings.

How defaults work #

For settings that support personal choices, your choice takes precedence over the machine default. Without either choice, the component uses its built-in default. System Default removes your personal override, so later changes to the machine default apply to you too.

An empty dock or a shortcut action with no keys is an explicit choice. It does not mean System Default. An unreadable wallpaper has different fallback behavior; see wallpaper, clock, and dock.

Permission to change settings #

Desktop Settings runs as your account. The registry decides which settings you can change. Machine settings are normally writable by Administrators; controls that your account cannot use show the reason. Desktop Settings does not request elevated access or change your account's permissions.

The window refreshes stored settings every four seconds. It keeps text that you are editing rather than replacing it with an external change. A successful save is reported at the bottom of the window. Some machine settings take effect at the next desktop session or GXWI restart.

Choose a task #

Use the following guides for each group of settings:

  • Wallpaper, clock, and dock
  • Keyboard shortcuts
  • Default apps
  • Settings for all users

Changing the Wallpaper, Clock, and Dock

Peios / Using Peios / Desktop Settings

Open Desktop Settings in a signed-in desktop session. The sections under For You affect your account; machine defaults continue to apply until you make a personal choice.

Wallpaper #

Choose a supplied picture or a file that your account can read:

  1. Select Wallpaper under For You.
  2. Select a picture in the gallery. To use another file, select Choose Picture…, find the image, and confirm the file selection.
  3. Check that the background changes. If saving fails, read the message at the bottom of Desktop Settings.

Supported file extensions are PNG, JPEG, SVG, WebP, AVIF, and GIF. The maximum size is 16 MiB. The choice stores a path, so keep the image at that path. A readable file with an image extension still needs valid image contents for the browser to display it.

Select System Default to remove your override. Fenesh then selects the machine wallpaper, or its embedded Strata image if no machine path is set. If a selected path is invalid or unreadable, Fenesh displays the embedded image; an invalid personal path does not select the machine path.

Changing the file alone does not trigger a desktop refresh. Choose the picture again or start another desktop session after replacing its contents. Avoid relying on a same-path replacement for immediate updates.

Clock #

The top bar uses the machine's time zone. To change the hour format:

  1. Select Clock under For You.
  2. Set Time Format to 24-Hour (14:05) or 12-Hour (2:05 PM).
  3. Check the clock in the top bar. The selection applies without an additional save step.

System Default uses the machine's format, which falls back to 24-hour time. Changing the hour format does not change the time zone.

Dock #

Use the dock or launcher to change pinned applications:

  1. Open an application's context menu and select Pin to the dock or Unpin from the dock.
  2. Drag a pinned application along the dock to change its position.
  3. Check the dock. If a registry write fails, the dock keeps the saved list and displays an error indicator above the launcher button.

Your first change copies the effective machine list into your personal settings and applies the change. Later machine defaults do not replace that list. Pins for uninstalled applications are hidden and retained; they return when the application is installed again.

To restore the machine list, select Dock under For You, then Use System Default. This removes your personal list. Removing every pin individually instead keeps an explicitly empty personal list.

Open the welcome window #

In Dock, find Get Started and select Show Again. If the welcome application is installed, it opens with your active keyboard shortcuts. This action also clears the first-session marker, allowing Fenesh to open the window at your next desktop session. It does not reset other settings.

Assigning Keyboard Shortcuts

Peios / Using Peios / Desktop Settings

Desktop shortcuts work across application windows, including text fields. Open Desktop Settings and select Keyboard Shortcuts under For You to change your choices.

Assign a shortcut #

Each action can have several shortcuts or none. To add one:

  1. Find the action and select + Add or + Set.
  2. Hold Ctrl, Alt, or Meta and press the other key in the combination.
  3. Check the displayed shortcut. If it conflicts with another action, remove that assignment first and try again.

Press Esc or select elsewhere to cancel recording. A modifier pressed alone does not complete the recording. Browser-reserved shortcuts cannot be assigned to the desktop; choose another combination if it is refused.

For Open Dock Item, select Change, hold your chosen modifiers, and press a number from 1 to 9. The modifiers apply to all nine positions. For example, Alt selects dock items with Alt+1 through Alt+9.

Remove or reset shortcuts #

Use the action's controls to change its assignments:

  • Select × beside a shortcut to remove it. Removing every shortcut disables that action's keyboard binding for your account.
  • Select Reset to restore one action's System Default.
  • Select Reset All to System Default to remove your personal overrides.

Changes apply to your desktop session as they are saved. A reset can be refused if the restored combination conflicts with another assignment. Resolve the reported conflict and retry. If a reset of several actions fails partway through, review the displayed assignments before retrying.

Administrators can set machine defaults under All Users. See settings for all users.

Choosing Default Apps

Peios / Using Peios / Desktop Settings

Default apps determine which application opens a type of file when the application opening it uses Peios' default-app selection. Desktop Settings lets you choose among installed applications that declare support for the type.

To choose your default:

  1. Open Desktop Settings.
  2. Select Default Apps under For You.
  3. Find the file type and select an application from its list.
  4. Open a file of that type from a desktop application that uses the shared default-app selection, such as Gexora, to check the result.

The choice is saved when you select it. System Default removes your personal choice and restores the machine or built-in selection. Choosing an application does not give it support for additional file formats.

The section lists declared types with at least one available application. No Choices means there are no types to display. Install an application that declares support for the type before expecting it to appear in the selection.

For machine defaults, use Default Apps under All Users. The First Available choice removes the machine's override for that type. Personal choices continue to take precedence over machine defaults.

Setting Defaults for All Users

Peios / Using Peios / Desktop Settings

The All Users sections of Desktop Settings affect machine settings or defaults for accounts that have no personal override. You need permission to write the relevant registry keys. The application displays a reason when your account cannot change a setting.

Sign-in screen #

To change the name or notice displayed before sign-in:

  1. Select Sign-In Screen under All Users.
  2. Enter Machine Name and select Apply, or select Change… beside Notice, edit the text, and select Save.
  3. Check the save result. The changes take effect when GXWI next starts.

The displayed machine name is separate from the network hostname. It accepts up to 64 characters. The notice accepts up to eight paragraphs and 2,000 characters in total, with paragraphs separated by blank lines.

Desktop #

To set defaults for other accounts:

  1. Select Desktop under All Users.
  2. Choose a wallpaper or Time Format. For a custom wallpaper, select a file readable by every intended account, such as an installed file under /usr/share.
  3. To make your effective dock list the machine default, select Use My Pins beside Pinned Apps.
  4. Check the save result and a session without personal overrides.

These defaults do not replace existing personal choices. Wallpaper and clock changes reach active Fenesh sessions through registry notifications. A failed notification watch is reported in the shell's error output; start another desktop session if a saved change does not appear.

To choose icon themes, select Change… beside Icon Themes, enter one installed theme folder name per line, and select Save. Folder names come from /usr/share/icons, in preference order. The base theme is the final fallback. Theme changes apply to new desktop sessions.

Keyboard shortcuts and default apps #

The Keyboard Shortcuts and Default Apps sections use the same controls as the personal sections. Reset All to Built-In removes machine shortcut overrides. First Available removes a machine default application for a file type. Accounts with personal overrides retain them.

See keyboard shortcuts and default apps for the controls.

Advanced #

Advanced settings select the programs that provide the desktop and the address that serves it. Keep an independent administrative way to recover configuration before changing them. An overlay can prevent access to both sign-in and the desktop.

To apply a change:

  1. Select Advanced under All Users.
  2. Edit the fields you need. Leave a field empty to remove its override.
  3. Select Review Changes… and read the consequences shown.
  4. Select Apply Changes to save, or Cancel to return to editing.
  5. Check the result message and the affected settings before restarting GXWI or starting another desktop session.

The fields have different operational consequences:

FieldWhat to consider
Listen AddressUse an IP address and port. A changed address applies when GXWI next starts and can disconnect existing pages.
CompositorUse the absolute path of a trusted program that runs as each desktop user.
ShellEnter trusted shell program paths separated by spaces. Paths containing spaces cannot be represented in this field.
OverlaySelect a trusted program shown instead of sign-in. While enabled, normal desktop sign-in is unavailable.
Overlay AccountSpecify the account under which the overlay runs.

Shell programs can observe desktop windows, start applications, and receive desktop shortcuts. Permission to replace these programs is a security-sensitive capability. The review prompt does not grant it.

Advanced changes span more than one registry key. If saving fails after one key is written, earlier changes can remain applied. Review every field and correct the partial change before restarting affected services.

Essential Desktop Applications

Peios / Using Peios / Everyday Applications

GXWI Essentials is a suite of desktop applications for everyday work and system administration. Each application is installed separately. They run inside your GXWI session and use your account's access rights; opening an administration window does not give it additional authority.

The suite supplies applications, not the desktop compositor or shell. Fenesh and Fenestra provide separate desktop interfaces. Their launchers can open the applications installed on the machine.

Choosing an application #

Use the application whose scope matches the task:

TaskApplication
Browse, copy, move, or remove filesFile Explorer
Edit a small text fileText Editor
Run a shell or terminal programTerminal
Inspect running processes and sessionsTask Manager
Control or define a serviceServices Manager
Inspect disks and mountsDisk Manager
Configure interfaces, name resolution, or firewall rulesNetwork Manager
Inspect registry keys and valuesRegistry Editor
Change machine time, locale, startup, or nameSystem Settings
Install, update, or remove packagesPackage Manager
Enable or disable installed feature definitionsFeature Manager
Upgrade the Peios releaseUpgrade Peios
Change your own account settingsMy Settings
Administer local users, groups, and privilegesPrincipals Manager
Manage certificate trustSecurity Policy
Read events, logs, and metricsEvent Viewer

The file dialog and permissions editor are shared dialogs opened by these applications. They are not standalone launcher tasks.

Reading an outcome #

A displayed setting is not proof that its consuming service accepted it. After a change, read the application's result and check the affected service, file, or connection. A disabled control or incomplete view can mean access was refused; it does not mean the underlying object is absent.

Two interfaces have explicit implementation limits. Disk Manager's change forms do not modify storage. Network Manager marks several firewall activity displays as Example data. Their guides describe what remains real and what needs separate verification.

The command manuals use the executable names gxwi-file-explorer, gxwi-text-editor, and gxwi-terminal, alongside the other gxwi-* application names.

File Explorer

Peios / Using Peios / Everyday Applications

File Explorer shows a directory and opens its contents with the installed applications. A window owns its current directory, selection, and sort order. Devices showing the same session window see that shared state; open another window to browse a different location independently.

Opening an entry #

Opening a folder navigates into it. Opening an executable starts it. Other files use an application that declares support for their file type: your default takes precedence over the machine default, then the available candidates are ordered by title. The entry menu lets you choose another candidate.

The listing identifies file types from their names without reading every file. When an unknown type is opened, File Explorer can check whether its contents are text. This probe reads at most 4 KiB from a regular file; it does not wait for data from a pipe or device. A directory's menu offers applications that open directories, including Terminal when it is installed.

A directory listing displays at most 2,000 entries and reports when the limit is reached. An incomplete listing is not evidence that an omitted file is absent.

Copying and moving #

Cut and copy select an entry for a later paste. That selection is shared between File Explorer windows through the session runtime directory. Without that directory, the selection belongs to one window.

Pasting a copy under an occupied name chooses a copy name. Pasting a cut entry does not overwrite an existing name; the entry remains selected for a later move. Copying a directory includes its contents and runs while the window continues to respond.

Removal and permissions #

Delete asks for confirmation and removes the entry. A directory is removed with its contents. There is no trash or undo store, so preserve anything you need before confirming.

Permissions opens the shared descriptor editor. File Explorer retains a handle to the selected object so applying a descriptor targets that object even if its name changes. The dialog does not supply extra rights. It offers the access list and the owner for editing as the kernel allows, found by opening the object for the right to change each one alone. Those opens read nothing and never conflict with other programs' opens. Where the kernel cannot say, as for a device or pipe, both are offered and the kernel decides when you apply. See The Permissions Editor and gxwi-file-explorer(1).

Names that are not UTF-8 #

A filename that cannot be displayed as UTF-8 uses replacement characters in the listing. Local navigation, rename, and deletion retain the original filename bytes, so identical-looking labels do not identify the same entry. The shared clipboard accepts only UTF-8 paths and reports other paths as unsupported rather than silently changing their names.

Filenames and launching applications #

File Explorer keeps the original filename when selecting or changing a file. The application launch protocol carries UTF-8 text. If a filename cannot be represented as UTF-8, File Explorer reports that it cannot open the file through another application. It does not change the filename or launch a different file. The same check applies when opening a terminal in a folder.

Managing Files

Peios / Using Peios / Everyday Applications

Use File Explorer to organize files within the access your account has. Copying keeps the original; cutting and pasting moves it. Deleting removes it without a trash folder.

Before you start #

You need File Explorer in a running GXWI desktop and access to the source and destination directories. Keep a separate copy before deleting data you might need again.

Copy or move an entry #

  1. Open File Explorer from the launcher and navigate to the source directory.
  2. Open the entry's context menu and choose Copy or Cut.
  3. Open the destination directory in this or another File Explorer window. Open the directory's context menu and choose Paste.
  4. Wait for the operation's result before starting another operation on the same entry.

Check the result #

Inspect the destination entry and open it when appropriate. A copy leaves the source intact; a successful move removes it from the old directory. If a cut name is already occupied, choose a different destination or rename an entry after reviewing what is there.

Rename or delete #

Select Rename from an entry's context menu and enter an unused name. File Explorer refuses an occupied destination instead of replacing it.

For deletion, review the selected entry, choose Delete, and read the confirmation. Confirm only the intended entry and subtree. Check the listing afterward; a refusal means the operation did not complete as requested and needs review, not repeated confirmation without inspection.

Use the directory context menu to create a new folder or file. Its name must identify a new entry. The manual gxwi-file-explorer(1) describes launch arguments and listing limits.

Editing Text Files

Peios / Using Peios / Everyday Applications

Text Editor edits one file per window. Unsaved text belongs to the application window, so reconnecting a browser does not discard it. Closing the application window asks about unsaved changes.

Before you start #

You need Text Editor in your GXWI session and permission to read the file. The editor accepts UTF-8 text without NUL bytes, up to 349,525 bytes. Use a tool suited to larger or binary files when a file exceeds those limits.

Edit and save #

  1. Open a text file from File Explorer, or start Text Editor for a new document.
  2. Make the intended change. Press Ctrl+S to save. A new document asks for a name when first saved.
  3. To save under another name, press Ctrl+Shift+S and choose an unused name. This operation does not overwrite an existing file.

Check the result #

Read the result shown by the editor and confirm that the document has no unsaved changes. Saving an existing file writes it in place, preserving its identity rather than replacing it with another file. Uniform CRLF line endings are preserved; mixed endings are written as LF.

Changes made elsewhere #

The editor checks the file every two seconds. If another program changes it while your buffer is unchanged, the editor reloads it. If both versions changed, it asks which to keep. Read both the conflict and the file's purpose before discarding either version.

Saving in place is not an atomic replacement transaction. Keep a backup when editing a file whose previous contents need to remain recoverable. See gxwi-text-editor(1) for the supported input and shortcuts.

Using a Terminal

Peios / Using Peios / Everyday Applications

Terminal runs a shell or another program on a pseudoterminal inside the desktop. The running terminal belongs to the application, so a browser reconnection shows the terminal state that remains on the machine.

Before you start #

You need Terminal installed and a running GXWI session. Commands run with your account's permissions and can change files or system settings within those permissions.

Open and use the terminal #

  1. Open Terminal from the launcher. It starts your configured absolute shell path, or /bin/sh, in your home directory.
  2. Enter a command and press Enter. Programs that need a desktop connection inherit the session environment.
  3. Use Ctrl+Shift+C to copy selected text and Ctrl+Shift+V or Shift+Insert to paste.

Check the result #

Read the program's output and exit status as you would in another terminal. Ending the shell closes its window. Closing the application window hangs up the terminal, which can terminate work still running in it. Closing a browser page is a different operation from closing the application window.

To open a shell in a folder, use the folder's application menu in File Explorer. The command interface also accepts one absolute directory path, or a program followed by its arguments; see gxwi-terminal(1).

The desktop retains its own keyboard shortcuts while the terminal has focus. A shortcut reserved by the desktop does not become input to the terminal program.

When input waits #

Terminal keeps up to 1 MiB of pending input in each browser page. It sends that input in order as the running program accepts it. If the buffer fills, typing pauses while the program catches up; its output continues to appear. A paste that does not fit the remaining space is refused in full with a message. Wait for the program to read, or paste a smaller amount.

If the connection breaks with input pending, Terminal warns that some input might already have reached the program. It does not replay that input after reconnecting, because replaying a command could run it twice. Input already received by the application might still reach the program. Check the output before deciding what to type again. The warning remains after reconnection until you start entering new input.

The File Dialog

Peios / Using Peios / Everyday Applications

The shared file dialog lets an application ask you for a file to open, a name to save, or a folder. The dialog chooses a path; the calling application opens, writes, or uses that path. A successful selection does not grant the caller new filesystem rights.

The dialog shows folders first and filters files by the kind the caller requested. Up, Home, and the path field change the location. Hidden files includes names beginning with a dot. In save mode, the selected kind can supply a missing extension, and an occupied name asks for confirmation.

An application that asks for a folder gets a dialog that shows folders only. Choose Folder chooses the folder you picked or, with nothing picked, the folder you are in; the dialog shows which path it will choose before you press it. Only an application that asks for a folder can be given one: opening and saving never return a folder, and opening one goes into it instead.

The dialog can also create a folder, rename an entry, or delete it. Deletion is real: a directory goes with its contents. The dialog runs as you and disables operations it cannot perform.

Canceling, pressing Esc, or closing the dialog reports cancellation to the caller. The dialog also ends when its caller closes the input channel. It is not meant to be started as a standalone launcher task.

Developers use the file-choosing protocol or the companion Rust client. The protocol's shared contract belongs to the Peios userspace specifications; this suite owns the dialog implementation. See gxwi-file-dialog(1) for transport and lifecycle details.

The selection protocol returns a UTF-8 path. A path that cannot be represented as UTF-8 is refused explicitly and leaves the dialog open. Local operations still identify the original entry independently of its displayed label. Rename refuses an occupied destination, including one created after the dialog's initial check.

GXWI Service

Peios / Using Peios / The Desktop Service

The Graphical Extensible Web Interface (GXWI) provides browser access to Peios desktop sessions. It handles TLS, authentication conversations, session connections, and installation or setup overlays. The compositor and desktop shell are separate programs.

Service and desktop responsibilities #

The programs divide responsibility as follows:

ProgramResponsibility
gxwidMachine identity, privileged setup, and session lifetime
gxwi-serverRestricted network-facing HTTP and TLS worker
Configured compositorDesktop presentation and application surfaces
Desktop shellPanels, launchers, settings, and other desktop tools

Fenestra is a compositor. Fenesh is a desktop shell. GXWI does not require those names in its protocol; the configured compositor determines the session program. gxwi-hello provides a diagnostic session when no compositor is configured.

Authentication and authority #

GXWI asks authd to authenticate an account for a Remote Interactive logon. The resulting access token controls the desktop job. Applications inherit session authority unless another explicit mechanism changes it.

Rendering a button does not grant permission to perform its action. The service or kernel handling an operation still checks access. A disabled button is a usability choice, not an authorization boundary.

Persistent sessions #

A session can continue after browser connections disappear. A later successful sign-in can reconnect to the same running session. Session persistence is not disk persistence: restarting a compositor or ending its job loses process state that applications have not saved.

The service keeps normal sessions separate from machine overlays.

Configuring the GXWI Service

Peios / Using Peios / The Desktop Service

Configure GXWI through Machine\Software\GXWI. The registry's access checks determine who can change these values. The complete types, defaults, and validation rules are in regman for that path.

Before you start #

Use an account with write access to the required registry values. Keep a trusted console available when changing remote access. A failed listener or compositor change can prevent browser access.

Change the listener #

  1. Set Listen to the numeric address and port to bind, such as 127.0.0.1:7780 for local access. Hostnames are not accepted.
  2. If other machines need access, configure the corresponding network policy under Machine\System\Network\Rules\Flow.
  3. Restart the gxwid service to apply the listener change.
  4. Verify that the configured address accepts HTTPS and presents the expected certificate before entering credentials.

Changing the listener does not add a name or address to the certificate. Verify both reachability and certificate identity.

Choose the compositor #

  1. Set Compositor to the absolute path of the session program.
  2. Start a separate test session to verify that the program can start and serve a desktop.
  3. End and reopen existing sessions when they need the changed compositor.

The value applies to sessions created after the change. A missing executable fails session startup; GXWI does not validate program availability when the registry value is written.

Anyone who can change Compositor chooses a program that runs with the authority of users who start sessions. Protect this value as carefully as the executable itself.

Set public labels #

Under Machine\Software\GXWI\Logon, Name supplies a machine label and Notice supplies paragraphs displayed before authentication. Restart gxwid to apply changes. Both are plain text and visible to anyone who can reach the service. Do not put secrets in them.

Machine Overlays

Peios / Using Peios / The Desktop Service

A GXWI overlay replaces normal browser sign-in and desktop access with one shared program. Installation and first-boot setup can use this mechanism. An overlay is separate from an application overlay surface inside a desktop.

Shared authority #

OverlaySession under Machine\Software\GXWI names the program. OverlayUsername names its account. GXWI requests a credential-free Remote Interactive logon for that account. authd must permit that logon; GXWI does not bypass an account's credential requirement.

Everyone who reaches the service shares the overlay program and its account authority. Choose an account with only the rights the setup program needs. Browser visitors do not authenticate individually before using it.

Write access to either registry value therefore controls a public program and the authority it receives. Protect both values and the executable.

Activation and failure #

GXWI watches the configuration. Setting an overlay starts it. Changing its program or account replaces it. Removing OverlaySession restores normal sign-in and access to existing sessions.

Normal desktop sessions continue behind the overlay but cannot be reached through the browser while it is active. The overlay has its own job, socket, and runtime directory.

If a configured overlay cannot start, GXWI shows a not-ready page and retries. The delay increases from 1 second to at most 30 seconds. It does not expose normal sign-in as a fallback. Read the service log to identify an unavailable program, missing account, or refused credential-free logon.

An invalidly typed or malformed registry value is rejected according to the setting's validation rules. Read regman for the distinction between invalid configuration and a valid program path that cannot run.

Reconnection and the Waiting Page

Peios / Using Peios / The Desktop Service

A browser connection and a desktop session have different lifetimes. Losing network access does not save or end applications. Reconnection works only while the relevant service, session, and application state remain available.

The waiting page #

GXWI supplies a service worker at /.gxwi/sw.js. When browser policy permits registration, it caches the waiting page and that page's assets. It does not cache ordinary application content as an offline desktop. Requests marked cache: "no-store" bypass its interception. Cache cleanup removes only obsolete GXWI waiting-page caches, preserving unrelated caches.

A failed navigation or a navigation taking more than 10 seconds can show the waiting page. A navigation timeout aborts the underlying fetch rather than leaving it running. Caller cancellation remains cancellation. The page checks for the machine every 1.5 seconds and returns when it can reach it. A browser that cannot register the service worker can show its own network error instead.

Trust the machine's certificate through the browser's supported controls. An exception at a certificate warning does not guarantee that the service worker can run.

Worker and session recovery #

gxwid retains the listening socket when gxwi-server restarts. This allows connections to queue while the worker is unavailable, within the operating system's backlog limits. It does not guarantee that every client request survives a restart.

The privileged daemon retains session jobs independently of the network worker. A browser might need to authenticate again after worker state is lost. Reconnecting to a surviving session differs from restoring a stopped application.

Diagnose a failed connection #

Check the failure in order:

  1. Confirm that the machine is reachable at the configured address and port.
  2. Verify the certificate through a trusted console.
  3. Check the gxwid service log for worker, authentication, or compositor startup failures.
  4. Check whether a machine overlay intentionally hides normal sessions.
  5. Verify that the compositor and application processes remain running.

Certificate Identity and Renewal

Peios / Using Peios / The Desktop Service

GXWI keeps a private key and a certificate in /var/state/gxwi. The private key identifies the machine cryptographically. A renewed certificate uses the same key but has a different fingerprint.

Stored identity #

The identity files have different access requirements:

FilePurposeIntended read access
key.pemPrivate ECDSA P-256 keySYSTEM
certificate.pemPublic certificateEveryone
certificate.sha256Public SHA-256 fingerprintEveryone

Protect the private key when backing up or restoring machine state. Sharing one key between machines also shares their cryptographic identity. GXWI does not silently replace an unreadable key; startup fails instead.

Renewal #

A generated certificate starts 1 day before creation and expires 1 year after creation. GXWI checks certificates at startup, every 24 hours, and on service reload. It renews a certificate with fewer than 30 days left. It also replaces certificates outside the accepted lifetime policy.

Renewal uses the machine's hostname at that time. Renaming the machine does not itself renew an otherwise acceptable certificate.

An authorized operator can request the reload check with:

svctl reload gxwid

This requests the normal check; it does not force renewal of an otherwise acceptable certificate or end existing desktop sessions.

Existing TLS connections continue. Subsequent connections receive the replacement certificate. A browser that trusted the preceding certificate can require verification and import again. See Verifying the Machine's Certificate.

Renewal records #

The event gxwid.certificate.renewed records the preceding fingerprint, the replacement fingerprint, and the certificate subject. Consult evman gxwid.certificate.renewed for its fields. Initial certificate creation is distinct from renewal.

A renewal record identifies the certificate change; it does not prove that a browser has imported the replacement. Use the trusted fingerprint file when verifying a connection.

Browser policy #

GXWI does not send a Strict-Transport-Security header. HTTPS remains the only transport for desktop content. Browser name, expiry, and trust checks still apply.

Configuring the Session Shell

Peios / Using Peios / The Desktop Service

The machine's shell setting controls which programs Fenestra starts for every desktop session. Shell programs receive desktop-wide capabilities, so choose trusted programs and preserve an independent administrative way to recover a broken configuration.

Choose shell programs #

Before changing the configuration, install the intended programs and confirm that your account can write the machine's Fenestra settings. Desktop Settings provides an Advanced section when Fenesh is installed.

To change the shell with the Registry Editor:

  1. Open Machine\Software\Fenestra.
  2. Set Shell to a REG_MULTI_SZ containing the absolute path of each shell program. Use a separate entry for each program.
  3. Start another desktop session and check that the expected controls appear. Existing sessions keep their shell selection.

The list accepts up to 16 programs. Entries are executable paths, not commands with arguments. One invalid relative path invalidates the whole value. An absent, unreadable, or mistyped value selects the companion fenestra-taskbar and fenestra-launcher beside the compositor executable.

An explicitly empty list starts no shell. It does not restore the default. Delete the value to restore the fallback programs. A valid path whose program cannot start is reported; Fenestra does not replace that entry with a fallback program.

Understand the authority granted #

Configured shell processes receive the surface list and can ask Fenestra to start programs, close another application's surfaces, or end the session. Their browser surfaces can control focus, overlays, and global shortcuts. Shell programs retain the session account's operating-system permissions; their desktop role does not make them administrators.

Fenestra identifies a shell connection from a tracked child process and kernel-reported peer identity. A surface title, role, or application name does not grant that role. Protect write access to the machine's Shell value as carefully as access to the selected executables.

Restart behavior #

Fenestra restarts a shell program after it exits, with a 1-second delay. It stops retrying after three consecutive runs shorter than 5 seconds. A run lasting at least 5 seconds resets that consecutive-failure count. A failure to start the executable stops that program's supervisor without retrying.

Correct the program or configuration, then start another desktop session after the supervisor has stopped. Configuration changes are read at session startup rather than while a supervisor is running.

Icons and keyboard shortcuts #

Fenestra reads the shared icon-theme chain at session startup and serves icons for desktop pages. Changes to the chain apply to another session. The base theme remains the final fallback. The detailed icon contract belongs to the Peios General System Standards, rather than this guide.

Keyboard shortcuts use personal overrides, then machine overrides, then built-in defaults. An empty value turns off an action's shortcut; removing the value restores its fallback. Fenestra watches shortcuts while running. The installed registry reference lists the actions and accepted values.

Working with Text and Archives

Peios / Using Peios / Command-Line Basics

Install the tools needed for the task. Package availability in the system root does not imply availability in an initramfs.

Inspect and compare #

Use grep for matching lines, sed for line transformations, awk or gawk for fields and records, and find with xargs for selecting files and passing arguments. diff, cmp, diff3, and sdiff compare contents. Peiosutils supplies basic tools including cat, head, tail, cut, paste, join, sort, uniq, tr, and wc.

grep -n 'error' output.txt
awk '{ print $1 }' records.txt
diff before.txt after.txt
less output.txt

In less, Space advances, b goes back, /pattern searches, n repeats the search, and q quits. Its edit command needs a separately installed editor. For terminal editing and its save/recovery rules, see Editing With nano.

Create, inspect, and extract #

  1. Choose a format supported by the recipient and install its compressor command as well as the archive tool. A compression library alone does not provide the executable GNU tar invokes.

  2. Create and inspect an archive:

    tar -caf backup.tar.xz documents/
    tar -tf backup.tar.xz
    
  3. Extract into a fresh directory and inspect the resulting contents:

    mkdir restored
    tar -xf backup.tar.xz -C restored
    

GNU tar's -a selects compression by suffix, such as .tar.gz, .tar.xz, .tar.zst, or .tar.bz2. The associated commands are gzip, XZ, Zstandard, and bzip2. file ARCHIVE identifies contents independently of the name.

For ZIP exchange, use zip -r documents.zip documents/, inspect with unzip -l documents.zip, then extract with unzip documents.zip -d restored-zip. These formats carry conventional metadata and contents, not a complete Peios backup of native security descriptors and registry state.

Editing with Nano

Peios / Using Peios / Command-Line Basics

The org.gnu.nano package supplies nano and rnano. Its common package supplies syntax definitions, translations, and manuals. The vendor nanorc enables bundled syntax definitions. HOME and XDG data conventions select user state.

Edit and check a document #

  1. Open nano path/to/file. Use Ctrl+G for help.
  2. Edit the intended buffer. Ctrl+O writes it; Enter confirms the filename.
  3. Confirm the write succeeded before Ctrl+X exits. Check the saved contents when recovery or an external writer makes the result uncertain.

An existing regular file is written in place. Its owner, DACL, audit policy, and integrity label remain, and hardlinks still refer to that object. This is not atomic replacement or a guarantee against interrupted storage writes. New documents use destination inheritance. FACS controls access; numeric root and Unix modes do not grant permission. Saving does not itself require permission to rewrite the descriptor, while synchronization needs its applicable handle right.

Choose backup and recovery behavior #

nano --backup file requests a backup, normally file~. Backups, emergency .save files, and formatter/speller scratch files are private to the effective token's user SID before contents are written. They do not clone the document's sharing policy or ownership. Normal mandatory and audit controls still apply.

On a hangup or fatal error nano attempts an emergency save and reports its path on success. Space, directory authority, and private-creation failures can prevent it. There is no fallback to Unix 0600. If backup fails, the prompt lets the user decide whether to save the original without a backup; do not mistake that choice for a successful recovery copy.

History and lock files #

Search/replace/command history and cursor-position history are optional, selected by --historylog and --positionlog. nano uses a suitable existing ~/.nano or its XDG/default local-data directory. Its private state policy must already hold for existing files and directories. It validates opened files and refuses symlinks, multiple hardlinks, and incompatible policy rather than silently changing permissions. A history error disables the affected operation without disabling ordinary editing.

Advisory lock files use nano's interoperable format and normal inheritance. They expose editing identity/path metadata, not buffer contents, and do not authorize access. rnano's restricted editing mode also grants no new native authority.

Choosing Session Locales

Peios / Using Peios / Command-Line Basics

A locale controls character handling, sorting, and regional formats such as dates and numbers. It is separate from a console keyboard layout, console font, or the desktop clock's 12-hour or 24-hour display preference.

Before you start #

Install the locale data needed by the intended sessions. locale -a lists available locales when the locale tools are installed. Installing language data does not select it. The Peios session resolver falls back to C.UTF-8; a minimal image must supply its locale data for that fallback to work.

Choose the scope: machine defaults affect users without an override, while personal preferences affect one account. You need write access to the chosen registry key and destination layer. Record the old values before changing individual format categories.

Select and verify a locale #

  1. For personal preferences, open My Settings and choose Language & Formats. For machine defaults, use System Settings, Language & Keyboard.

  2. Choose an installed language and the desired formats. Read the saved outcome. The forms write the language and their format categories together; use the registry interface for a change to only one category.

  3. Keep existing work safe, then start a new session through the intended client. Rejoining an existing browser session does not refresh its process environments.

  4. Inspect that new session:

    locale
    locale charmap
    locale -k decimal_point
    

Check the selected language, character set, and category values, not only the saved registry fields. An application can make its own locale choice.

Category precedence #

Machine preferences live under Machine\System\Locale; account preferences live under Users\<SID>\Locale. Read those keys' registry manuals for supported values and types. authd prepares the private user root at sign-in; it does not replace an existing root's descriptor.

A valid personal value overrides the same machine value. Categories without an explicit value use LANG. Changing personal LANG alone does not remove a machine category override. For example, a machine LC_NUMERIC can keep its number format even when the account selects another language.

System Default removes a personal language override. Match Language removes personal format overrides, so machine category overrides can still apply. To select one installed locale for language and all categories handled by the form, select it explicitly in both lists.

Wrong types, malformed names, and unavailable locale data are diagnosed and ignored, leaving the preceding valid default. A locale name is not a path. LC_ALL, LANGUAGE, and LOCPATH are not stored session preferences. For a one-command override, an environment setting such as LC_ALL=C can still be appropriate.

Client and service boundaries #

Console sign-in and new GXWI sessions clear inherited locale overrides before applying registry preferences. Console login -p refreshes locale even while preserving other environment values.

SSH applies the registry preferences as defaults. Explicit environment entries permitted by SSH configuration, user environment files, or administrator SetEnv settings can override them for that session. Check the effective result through the actual SSH route.

These settings do not rewrite running process environments or become peinit's global service environment. Services need their own documented configuration.

Configuring Console Keyboards and Fonts

Peios / Using Peios / Command-Line Basics

The kbd tools operate on Linux virtual consoles such as /dev/tty1. They do not change an SSH client's keyboard, a serial terminal, or the browser's layout. Install org.kernel.kbd and its matching common data package; keymaps and fonts live under /usr/share/kbd.

Inspect and apply #

  1. To parse an installed layout without changing the console, generate a binary map: loadkeys --bkeymap uk > uk.bmap.

  2. With authority for the console operation, apply the intended map:

    loadkeys -C /dev/tty1 uk
    
  3. Verify typing at the machine's text console. A map can affect other virtual consoles; a device selection is not a per-session layout promise.

setfont -C /dev/tty1 Lat2-Terminus16 loads an installed font when permitted. dumpkeys inspects the map, kbd_mode inspects or changes keyboard mode, fgconsole identifies the active console, and chvt switches consoles. Switching is neither authentication nor creation of a logon session.

Store a boot preference #

The console-keymap service reads the Keymap name under Machine\System\Console. A name selects installed data, never an arbitrary path. With the registry and service-control rights, adapt:

reg set Machine/System/Console Keymap sz:uk
svctl restart console-keymap

System Settings offers the corresponding Console Keyboard layout selection and requests a restart when available and permitted. A custom image without the service does not acquire a loader by storing a value. A configured boot-triggered service can apply the choice at next boot when an immediate restart is unavailable. An absent value leaves the built-in US layout; an invalid map leaves the existing layout and produces a diagnostic.

Inspect service status/output and verify actual console input. A saved value or accepted restart request does not establish that loading finished. Font persistence requires separate configuration. Installing kbd alone neither applies its service seed nor starts additional sign-in prompts.

Launch and package boundaries #

openvt launches with the caller's token and the existing console descriptor; it does not authenticate or grant identity. Its upstream --user mode is rejected on Peios. Use the managed console sign-in services for that purpose. The PAM-based vlock locker and optional XKB conversion are excluded from the recipe. Debug and source packages do not configure the console.

Choosing a Message Language

Peios / Using Peios / Command-Line Basics

Peiosutils can display help and diagnostics in different languages. You can choose a language for one command without changing the environment of your shell or other applications.

Before you start #

  • Install the matching peiosutils-common package with the utilities. It supplies translated messages, including the shared usage and error text.
  • Use a command with translations for your chosen language. Coverage varies between commands; missing messages fall back to English.

Choose a language #

  1. Set LANG for the command you want to run. For example, read the help for sort in French:

    env LANG=fr_FR.UTF-8 sort --help
    
  2. To read the same help in English, select the English locale:

    env LANG=en_US.UTF-8 sort --help
    

These assignments apply to the command launched by env. Your shell keeps its existing environment. See env(1) for other ways to control a command's environment.

Check the result #

The French help includes Utilisation:; the English help includes Usage:. Both should show readable usage text rather than an internal message name such as common-usage.

If the command remains in English, check that its translation is installed. A missing or unsupported language falls back to English. The shared message loader reads LANG; other locale-sensitive operations can use additional locale settings. Changing the language of help does not establish the sorting or numeric-formatting rules for every command.

Processes and Threads

Peios / Using Peios / Processes

A process groups a program's memory and resources. Its threads execute the work, sharing that process's address space and normally its open-resource table. Threads still have their own execution state, and a thread can impersonate a different principal while handling a request.

Use Task Manager to inspect running processes. Identify the command, owner, parent, and managing service or job; those answer different questions.

Identity across creation and program replacement #

A PID identifies a process while it exists and can later be reused. The Process GUID identifies that particular process across its lifetime and in historical records. Neither identifies the principal acting through it.

A fork creates a child with a new PID and Process GUID. Private memory starts from the parent's contents, while inherited descriptors can still refer to the same open resources. The kernel's token lifecycle defines identity inheritance, including the distinction between primary and impersonation tokens. Do not infer all inherited authority from a displayed account name.

Exec replaces the running program within a process. Its PID and Process GUID remain, but the executable and its signature-derived protection can change. A launcher commonly creates a child and then executes its program. Thread creation shares more state instead of creating another independent process. The exact creation flags and library contracts belong in runtime references.

A pidfd holds a particular process rather than whichever process later owns a number. Programs should use that handle for stable targeting. From a shell, recheck a PID's current command, owner, and workload before acting on an old number.

Workload relationships #

RelationshipWhat it identifies
Parent and childCreation and responsibility for collecting exit results.
ServiceA supervised definition whose processes can be restarted.
Submitted jobWork submitted to Peinit for management.
Process groupProcesses targeted together by terminal job control.
Job-control sessionProcess groups and their possible controlling terminal.
Logon sessionThe authentication record referenced by identity tokens.

A terminal pipeline and a submitted Peinit job are different uses of "job." A job-control session need not have a terminal and is not a security identity. With ordinary terminal settings, Ctrl-C and Ctrl-Z signal its foreground process group; an explicit signal to one PID has a narrower target.

Userspace ancestry normally leads to Peinit, PID 1. Orphaned descendants can be adopted by a nearer subreaper before PID 1 takes responsibility. Kernel threads and idle tasks are separate system work; a process listing is not only a list of applications started by people.

Identity and program protection #

The effective token describes who a thread acts as. The Process Security Block describes the process: its GUID, program protection, mitigations, and process security descriptor. Impersonation changes the effective identity, not the calling program's protection.

Reading a limited process summary does not grant permission to inspect its memory or stop it. A process's descriptor and Process Integrity Protection can refuse those operations even when its row remains visible. See Inspecting Process Security. For managed work, ask the manager to perform the intended operation through its own policy rather than repeatedly terminating a supervised PID.

Interpreting Process State

Peios / Using Peios / Processes

Inspect the process and its managing workload before deciding that a state means failure. Sleeping is normal for a program waiting for work.

Read the state #

StateInterpretation
Running or runnableExecuting or ready to be scheduled.
SleepingWaiting for an event; this alone does not indicate failure.
StoppedSuspended, with work able to continue after a resume.
TracedStopped under a debugger's control.
Uninterruptible waitWaiting on an operation that ordinary signals cannot interrupt.
ZombieExecution has ended; an exit result remains to be collected.

A persistent uninterruptible wait calls for inspecting the underlying I/O or kernel wait, not repeatedly sending a stronger signal. A zombie cannot be fixed by terminating it again. Inspect the parent that should collect its result; accumulated unreaped children can consume process-table resources.

Choose and verify an action #

  1. Identify the current process, its owner, parent, and service or job. Save work before requesting termination.
  2. Choose the intended scope. Use svctl stop NAME for a service or svctl job stop ID for a submitted job. Ending only a service's main process can trigger its restart policy.
  3. For one process, use Task Manager's End process, or kill PID to request orderly termination. Give the application time to finish.
  4. Refresh process and workload state. Successful signal delivery does not establish that termination has completed.
  5. If orderly termination fails and loss of unfinished work is acceptable, use the tool's force-termination operation. Recheck a numeric PID before using it again. Force termination skips application cleanup and cannot resolve an underlying uninterruptible wait.

kill -STOP PID and kill -CONT PID suspend and resume one process when permitted. They do not finish its work or target an entire service. Pausing a process can leave resources held and dependent work blocked.

Signal permissions depend on the operation, and process protection remains relevant. Sharing an account or terminal is not a general bypass. The kill guide and service controls describe the owning interfaces.

Exit and cleanup #

The parent collects a child's result through a wait operation. That result distinguishes ordinary exit from signal termination. Child-state notifications prompt the parent to check; they are not a replacement for collecting results. When a parent exits first, a subreaper or Peinit adopts remaining children.

Exit releases resources, but other owners can keep shared objects alive. Token handles elsewhere and unreaped processes can keep a logon session present after its visible work has ended. See Inspecting and Ending Sessions before interpreting a remaining session as a still-running application.

Inspecting Tasks and Sessions

Peios / Using Peios / Processes

Task Manager shows processes, resource use, jobs, and signed-in sessions. Use it to identify what is running before deciding whether to end one process, stop its service or job, or sign out a whole session.

Before you start #

You need Task Manager in a GXWI desktop. Access controls can hide process details or sessions and can prevent a stop operation. Missing details are not proof that the process has no owner or command.

Inspect and act #

  1. Open Task Manager and select Processes. Use Find or sort by CPU or Memory to locate the process.
  2. Select it and inspect its command, owner, parent, service or job, and session. Group by organizes the list by service or person.
  3. Choose the smallest intended scope. End process targets one process; Stop service and Stop job ask peinit to stop their managed workload.
  4. Review the confirmation. After an end request, a process still running after five seconds can offer End it now, which does not allow orderly completion.

Check the result #

Select Refresh or press F5 and inspect the process and its managed state. Ending a service's main process can trigger its restart policy. Use Stop service when the intended result is a stopped service. Task Manager retains a process handle for termination so a reused process ID does not redirect that request to a different process.

Sessions and visibility #

Signed in lists visible logon sessions and their processes. Sign out ends the selected session through authd; review carefully when it is your own session. A refusal or a process that cannot be ended can leave the session open. A service session is managed by its service.

The full kernel session list requires the corresponding access. Otherwise, Task Manager lists the sessions it can infer from visible processes. Protected processes can remain listed while their details and control are unavailable, including to an administrator whose process lacks the needed protection level. See gxwi-task-manager(1).

Performance Views

Peios / Using Peios / Processes

Task Manager's performance views describe recent activity on the machine. They help locate a resource bottleneck, but a graph is not a persistent monitoring history and does not explain a workload's cause on its own.

Performance groups processor, memory, disk, and network measurements. Select an item to see its graph for the last two minutes. Data is sampled every two seconds and discarded when the window closes.

Process CPU share is measured against the whole machine between samples, so it is available from the second sample. Each processor shows logical processors separately. Load averages describe runnable or waiting threads over their reported intervals rather than the percentage shown by the CPU graph.

Available memory estimates what programs can receive; cache is not all unavailable memory. Disk graphs show active time and transfer rates. Network graphs show transfer rates, not whether a remote service is reachable. Use Network Manager for addresses, routes, and name resolution.

The process list and Jobs add context. A job is work submitted to peinit outside a persistent service definition. Job visibility is checked separately from process visibility. A process can therefore be shown without details of the job it belongs to.

Do not infer a machine-wide absence from a filtered view. Task Manager reports access restrictions and protected processes; compare those notes with the list before drawing conclusions. Use Event Viewer when you need recorded events or retained metrics rather than this window's samples.

Files, Names, and Security

Peios / Using Peios / Files and Paths

File commands change names, contents, or metadata. Knowing which of those a command changes tells you whether data can be lost, and which security the result has. Every file on Peios has a security descriptor that decides who can use it, and copying, moving, and creating files treat that descriptor differently.

A name and an object are different #

A file is an object with contents, metadata, and a security descriptor. A name is an entry in a directory that refers to the object. One object can have several names, called hard links, and removing one name leaves the others. A symbolic link is a separate kind of file that stores a path, and that path can later lead to a different object, or to nothing.

Which security a file gets #

The command you use decides which security descriptor the result has:

OperationResult
Rename a file, including moving it within one filesystemThe same object, with its own security descriptor
Copy a file, including moving it to another filesystemA new object, which inherits security from its destination directory
Create a file or directoryA new object, which inherits security from its parent directory
Add a hard linkAnother name for the same object and descriptor

Moving a file into another directory doesn't apply that directory's inherited rules to it. Inheritance happens once, when an object is created, and doesn't keep existing objects in step with their parent.

cp, mv, mkdir, and the other creation commands can request specific security instead. Managing Files and Directories shows how. To see or change a file's security descriptor, use sd.

Results that need checking #

A recursive operation can fail after it has already changed part of a tree, and a command can report success while skipping files under an update policy. Check the result when every file matters.

Removing a name doesn't erase its data. Other hard links, snapshots, backups, and the storage device itself can keep copies.

What a listing shows #

A listing is for people to read. File names can contain spaces, tabs, and newlines, so don't parse ls output to find file names in a script.

The mode, user, and group fields that ls and stat print are kept for compatibility. They summarize some metadata, but they don't describe who can use a file: the security descriptor does.

Every listing, metadata query, or path check describes one moment. The file can change, be replaced, or disappear before the next command runs, so a program that must act on a particular file checks the file it opens.

Managing Files and Directories

Peios / Using Peios / Files and Paths

Use these commands to copy, move, create, link, and remove files in a terminal. Each section shows the common case and the Peios behavior that affects it. The man page for each command lists every option.

Before you start #

Use a terminal on a machine with the command-line utilities installed. To try the examples, work in an empty directory so that nothing you need is overwritten. The examples name files such as report.txt; create them first, or substitute your own.

Copy files #

Use cp to make a new file or directory tree from existing data:

cp -i report.txt report-backup.txt

-i asks before overwriting a file that already exists. To copy a directory and everything in it, use cp -R notes notes-copy. If the destination already exists as a directory, cp copies the source into it.

A copy is a new object, so it inherits security from its destination directory, and copying to another location can change who can read the data. To keep particular attributes, ask for them:

  • --preserve=timestamps keeps the access and modification times.
  • --sd-explicit carries the source's explicit access rules, and lets the destination directory add its inherited rules.
  • --sd copies the source's owner and its full access and audit lists.

Neither security option copies the security descriptor's group, so a copy is not a complete security backup. cp(1) describes every preservation option and the access each one needs.

Move and rename files #

Use mv to change a file's name or location:

mv -i draft.txt report.txt

Within one filesystem, a move is a rename: the file keeps its security descriptor, even in a directory with different inherited rules. Across filesystems, mv copies the file and then removes the source, and the copy inherits security from its destination. Requesting particular attributes also makes mv copy, even within one filesystem. See mv(1).

Create files and directories #

Create a directory, with any missing parents:

mkdir -p reports/2026/drafts

touch build.marker creates an empty file, or updates the timestamps of a file that exists without changing its contents. mkfifo creates a named pipe that passes a stream from one program to another, and mknod creates device nodes, which needs the relevant authority. mktemp -d creates a directory with a unique name and prints it, so another program can't claim the name first.

A new object inherits security from its parent directory. mkdir, touch, mkfifo, and mknod can request an owner, group, integrity label, or complete security descriptor for the object they create. mkfifo and mknod also accept a -m mode option, but it isn't how security is set on Peios. Check the result with sd show before you share the location, because choosing an owner doesn't on its own give that owner the access you meant. See mkdir(1) for the security options.

Link files #

Create a symbolic link, a file that stores a path to another file:

ln -s report.txt latest

A relative path in a symbolic link is resolved from the directory that contains the link. Without -s, ln creates a hard link: another name for the same object, sharing its contents and security. Hard links can't usually cross filesystems. link and unlink add or remove exactly one hard link, without the other choices ln and rm offer.

Remove files and directories #

Remove a file, with a confirmation prompt:

rm -i disposable.txt

Removal has no undo. rm removes a directory and its contents only when you ask for recursion. A prompt doesn't decide whether you can delete the file: the file's security descriptor does. rmdir removes only empty directories, which protects you from removing contents by mistake.

rm asks before deleting a read-only file, and needs -f to delete one in a script. See Read-Only Files and Creation Dates.

rm normally removes a file's name at once, even if a program still has the file open; that program carries on with a file that no longer has a name. To leave the name in place until the last program using the file closes it, as Windows does, use --when-closed:

rm --when-closed build.log

If a program has the file open, rm says the file will be removed when it is closed. Until then the name stays, and opening the file again fails. A directory goes when its last user closes it, if it is empty then. If a program has opened the file without allowing it to be deleted, rm reports it as in use either way.

shred overwrites a file's data before removing it, but snapshots, backups, journals, and the storage device can keep copies that it doesn't reach. When data must become unrecoverable, use a method designed for the storage, such as encryption with a key you can destroy.

Change a file's length #

truncate -s 1K size-sample.bin sets a file's length. Shrinking a file discards its end, and growing it again doesn't bring that data back. Work on a copy when you're unsure.

Check the result #

List the result and its security:

ls -l
sd show ./report-backup.txt

Check the security descriptor of anything you copied or created somewhere other people can reach. A recursive command that failed part way through can leave some files changed.

Commands on this page #

This page covers these commands:

CommandUse it toManual
cpCopy files and directory treescp(1)
mvMove or rename filesmv(1)
mkdirCreate directoriesmkdir(1)
touchCreate a file or update its timestampstouch(1)
mkfifoCreate a named pipemkfifo(1)
mknodCreate a device nodemknod(1)
mktempCreate a uniquely named file or directorymktemp(1)
lnCreate symbolic or hard linksln(1)
link, unlinkAdd or remove one hard linklink(1), unlink(1)
rmRemove files and directory treesrm(1)
rmdirRemove empty directoriesrmdir(1)
shredOverwrite a file's datashred(1)
truncateChange a file's lengthtruncate(1)

Read-Only Files and Creation Dates

Peios / Using Peios / Files and Paths

Every file on Peios can carry two special attributes besides its security descriptor: a read-only flag, and a creation date that copies can carry over. Windows programs set and check both, and Peios keeps them the same way.

The examples use a sample file named report.txt. Create it first, or substitute your own.

Make a file read-only #

Mark a file read-only:

attrib +r report.txt

No program can then open the file for writing, truncate it, replace it, or delete it, whoever runs the program, the file's owner included. Clear the flag to change the file again:

attrib -r report.txt

Run attrib with only file names to see which are read-only. The first column shows R for a read-only file and - for a writable one; the second shows the indexing preference described below:

attrib report.txt notes.md

Read-only guards against accidental change, not against other people. It grants and denies no one access, and anyone allowed to write the file's attributes can clear it. Use sd to decide who can use a file. A program that already had the file open for writing keeps that access, and you can still rename the file. A directory keeps the flag but isn't protected by it.

Delete a read-only file #

rm asks before deleting a read-only file:

rm report.txt

Answer y to delete it. rm -f deletes it without asking. In a script, where rm can't ask, it refuses and leaves the file unless you give -f, so a read-only file survives a cleanup that didn't mean to remove it. Deleting a read-only file needs the right to change its attributes as well as the right to delete it.

Keep files out of search #

A file or folder can say how far a search index may record it. Keep a file's contents out of search, while its name can still be found:

attrib +i report.txt

attrib then shows I in its second column. Keep a folder and everything in it out of search entirely, names included:

attrib --indexing=none Private

A folder's preference covers everything beneath it, so files created there later are covered too. To index one subfolder normally again, give it its own preference with attrib --indexing=all Private/Shared. attrib -i removes a file's own preference, so it follows its folder's again.

The preference narrows what a search indexer records. It doesn't hide the file from listings or change who can open it. Windows sees it as the file's "not content indexed" attribute through a share. A filesystem that keeps no extended attributes, such as a USB drive formatted for another system, can't keep it, and attrib says so.

See and set a creation date #

A file has two creation dates. Its birth time is when the filesystem created it, and nobody can change it. Its Created At is the date people and copy tools mean: a copy can carry its original's date, and you can set one. Until a file has a Created At, its creation date is its birth time.

stat shows both:

stat report.txt

Birth is the birth time. Created is the creation date, marked (birth) when it is only the birth time. Attributes shows read-only for a read-only file. For one value, use stat -c %k report.txt, or %K for seconds since the Epoch.

Set a file's Created At with touch, writing the date in any form touch -d accepts:

touch --created-at='2026-03-14 09:12' report.txt

This changes only the creation date. Add -d, -t, -r, -a, or -m to change the access and modification times as well. Remove the date again, so that the creation date is the birth time:

touch --no-created-at report.txt

Copy and move files #

A plain cp makes a new file, with today's creation date and no read-only flag. cp -p and cp -a keep the original's creation date and, if it is read-only, make the copy read-only too:

cp -p report.txt report-copy.txt

To keep the creation date without the flag, use --preserve without a value, or remove the flag from the selection with --no-preserve=readonly. Moving a file keeps both.

cp won't copy over a read-only file. cp -f clears the destination's read-only flag and copies over it, as xcopy /R does on Windows:

cp -f report.txt report-copy.txt

The copy is read-only afterwards only if you also preserve the flag and the original is read-only, as with cp -pf. A filesystem that has no special attributes, such as a USB drive formatted for another system, can't keep a creation date or the flag.

Commands on this page #

CommandUse it toManual
attribShow, set, or clear the read-only flag and the indexing preferenceattrib(1)
touchSet or unset a file's Created Attouch(1)
statShow a file's creation date and attributesstat(1)
cp, mvCopy or move a file, with its creation date and flagcp(1), mv(1)
rmDelete a read-only filerm(1)

Inspecting Files and Paths

Peios / Using Peios / Files and Paths

Use these commands to see what is in a directory, read a file's metadata, and work out what a path refers to. A path can be text you are building, a link's stored target, or a route to an existing file, and each needs a different command. The man page for each command lists every option.

The examples use sample file names such as report.txt. Create those files first, or substitute your own.

List a directory #

Show a directory's entries, with their metadata:

ls -l sample-directory

Names that begin with a dot are hidden. -a includes them, and -A includes them without the . and .. entries. dir and vdir use the same listing engine with fixed layouts: columns for dir, one detailed row per entry for vdir.

The ownership and permission fields in a long listing are kept for compatibility, and don't describe who can use the file. Use sd show for that. Don't parse ls output in a script: names can contain spaces and newlines, and the listing is meant for people.

To color listings, dircolors -b prints a shell setting that maps kinds of file to colors. Review the settings before adding them to your shell configuration, and keep listings readable without color.

Read a file's metadata #

Print selected properties of a file:

stat -c '%n: %s bytes' report.txt

Like ls, stat prints mode, user, and group fields for compatibility, and they don't describe access. A symbolic link has metadata of its own, so decide whether you want the link or the file it points to. A size can change before you read the file, so a program that limits how much it reads checks the file it has opened.

Without -c, stat also prints a file's creation date and its attributes. Birth is when the filesystem created the file. Created is the date a copy can carry over from its original, and is the birth time, marked (birth), if none has been set. Attributes shows read-only for a file that no one can change or delete until the flag is cleared. See Read-Only Files and Creation Dates.

Resolve a path #

Choose the command by the question you are asking:

  • What does this link store? readlink latest prints the path stored in a symbolic link. The path can be relative, and its target might not exist.
  • Where is this existing file? realpath -e reports/draft.txt follows every link and prints the absolute path. With -e, every part of the path must exist.
  • Where would this new file go? realpath reports/planned.txt allows the last part to be missing, and realpath -m allows missing parent directories too. The result is a planned path, not proof that you can create the file there.
  • Where am I? pwd -P prints the working directory with every symbolic link resolved. Your shell also has its own pwd.

A resolved path doesn't reserve a name or check access, and another program can change the file before you open it. The quiet mode of realpath hides error messages but not a failing exit status, so check the status before using the output.

Split and check path text #

basename and dirname work on the text of a path without reading the filesystem:

basename reports/draft.txt .txt
dirname reports/draft.txt

The first prints draft, the second reports. Neither checks that the file exists. pathchk reports/draft.txt checks that a proposed path meets naming limits, but success doesn't promise that creating the file will work.

Commands on this page #

This page covers these commands:

CommandUse it toManual
lsList directory entriesls(1)
dir, vdirList entries in a fixed layoutdir(1), vdir(1)
dircolorsConfigure listing colorsdircolors(1)
statRead file or filesystem metadatastat(1)
readlinkRead a symbolic link's stored pathreadlink(1)
realpathResolve a path to an absolute pathrealpath(1)
pwdPrint the working directorypwd(1)
basename, dirnameSplit a path's textbasename(1), dirname(1)
pathchkCheck a proposed path namepathchk(1)

Measuring Space and Copying Raw Data

Peios / Using Peios / Files and Paths

Use df and du to find out how much space is available and what is using it, and dd to copy an exact number of bytes. These commands measure and copy storage rather than files, so read their results with the storage model in mind.

The examples use sample file names such as source.bin. Create those files first, or substitute your own.

Check available space #

Show the space on the filesystem that holds the current directory:

df -h .

df reports space for the whole filesystem. Reserved space, metadata, snapshots, and files that are still open after removal all affect its totals, so free space isn't the size minus the files you can see.

Measure a directory tree #

Total the space used by a directory and everything in it:

du -sh measurements

du adds up the files it can reach. It can report allocated size, the storage blocks a file occupies, or apparent size, the file's logical length; the two differ for sparse and compressed files. A directory that du can't read makes its total incomplete, so check for errors.

df and du answer different questions, and a difference between them is a reason to look at what each one counts, not proof that either is wrong. For a full procedure, see Diagnosing Storage Pressure.

Copy an exact range of bytes #

Copy the first 4 bytes of a file into another file:

dd if=source.bin of=prefix.bin bs=4 count=1 status=none

if= names the input and of= names the output. dd overwrites the output without asking, so check of= before you run it, especially if it names a device: a mistake there affects a whole disk, not one file. Counts are in units of the block size bs= unless you choose byte units. dd finishing doesn't mean the data has reached the storage device; use its synchronization options or sync when that matters.

Commands on this page #

This page covers these commands:

CommandUse it toManual
dfShow filesystem capacitydf(1)
duMeasure a directory treedu(1)
ddCopy a byte stream in blocksdd(1)

Text Streams

Peios / Using Peios / Working with Text

The text utilities read a stream of bytes and divide it into records, usually one record for each line. Each command then does one thing to those records: shows some of them, combines them, reorders them, or changes their characters. You can join the commands in a pipeline, where each one reads the previous command's output. A few rules decide whether the result means what you expect.

Records and delimiters #

Most commands end a record at each newline. Commands that select fields, such as cut and join, also split each record at a delimiter character you choose. A delimiter is only a character, not a parsing rule: these commands don't understand quoted values or escaped delimiters, so use a parser for formats that have them.

Commands that count bytes rather than lines or characters can split a character that takes more than one byte. Use line or character counts for text that people will read.

Keep input and output separate #

The shell opens an output file before the command starts. Redirecting output to the file a command is reading empties that file before the command reads it:

sort counts.txt > sorted-counts.txt

Always write to a different file, check it, and only then replace the original. A command that exits with an error can leave partial output, so check its exit status, not only whether the output file exists.

Order and comparison rules #

Some commands compare records with each other. uniq compares neighboring lines only, so sort first to bring equal lines together. join and comm need both inputs sorted with the same rules.

Sorting depends on the locale, which sets the language rules for comparing text. Set the same locale for every command in a pipeline that compares records. LC_ALL=C gives an ordering by byte value that is the same on every machine:

LC_ALL=C sort names.txt

Commands for each task #

Choose the page by what you want to do:

  • Viewing and Combining Text to read files, select parts of them, and combine or split them.
  • Transforming Text to sort, count, translate, and reformat text.
  • Verifying Checksums and Encoding Bytes to check that data hasn't changed, or to carry bytes as text.

Viewing and Combining Text

Peios / Using Peios / Working with Text

Use these commands to read text files, pick out the parts you need, and combine or split them. None of them change the files they read; they write their result to standard output. The man page for each command lists every option.

The examples use sample file names such as names.txt. Create those files first, or substitute your own.

Read a file #

cat writes files to standard output one after another, which also combines them:

cat opening.txt details.txt > report.txt

cat -A shows tabs, line endings, and other invisible characters, and cat -n numbers the lines. For a long file, more shows one screen at a time: press Space for the next screen, / to search, and Q to stop. nl prints a numbered copy that leaves blank lines unnumbered, and tac prints lines from last to first.

Read the start or end #

Show the first two lines of a file:

head -n 2 names.txt

tail -n 2 progress.log shows the last two lines. Without -n, head shows 10 lines. To watch a log as it grows, use tail -f, which follows the file it opened. If a program replaces the log with a new file of the same name, tail -F follows the name instead and keeps going. Press Ctrl+C to stop. With several files, head and tail label each one, and the labels become part of the output.

Inspect raw bytes #

When a terminal would hide or reinterpret characters, od shows each byte as a number:

od -An -tx1 sample.bin

-tx1 shows one byte per hexadecimal value, and -An hides the offset column. Repeated rows are collapsed to * unless you add -v.

Select fields #

cut selects fields from each line, split at a delimiter:

cut -d : -f 1 counts.txt

A line without the delimiter passes through unchanged unless you add -s.

Combine files #

Choose by what links the lines together:

  • By position. paste names.txt counts.txt puts the first line of each file side by side, then the second, and so on. A missing line shifts every later pair.
  • By a shared key. join counts.txt colors.txt combines lines whose first field matches. Both files must be sorted on that field with the same rules, and a repeated key produces more than one output line.
  • By membership. comm compares two sorted files and shows the lines found only in the first, only in the second, or in both.

For join and comm, set the locale to the one you sorted with, for example LC_ALL=C join counts.txt colors.txt.

Split a file #

Split a file into pieces of two lines each:

split -l 2 original.txt piece-

The pieces are named piece-aa, piece-ab, and so on, and joining them in that order with cat restores the original. csplit report.txt '/Section/' splits at a line that matches a pattern instead. Both commands can overwrite existing files with the same names, so run them in an empty directory. New pieces inherit security from their directory.

Commands on this page #

This page covers these commands:

CommandUse it toManual
catWrite files to output in ordercat(1)
moreRead a file one screen at a timemore(1)
nlNumber linesnl(1)
tacPrint lines in reverse ordertac(1)
head, tailRead the start or end of a filehead(1), tail(1)
odShow bytes as numbersod(1)
cutSelect fields from each linecut(1)
pasteCombine lines by positionpaste(1)
joinCombine lines by a shared keyjoin(1)
commCompare two sorted filescomm(1)
split, csplitSplit a file into piecessplit(1), csplit(1)

Transforming Text

Peios / Using Peios / Working with Text

Use these commands to change the order, characters, or layout of text. Each writes a transformed copy to standard output and leaves its input unchanged. Decide which properties of the text carry meaning before you transform it: a reflow can break code, and a sort loses the original order. The man page for each command lists every option.

The examples use sample file names such as names.txt. Create those files first, or substitute your own.

Sort and count records #

Sort lines as numbers rather than as text:

LC_ALL=C sort -n counts.txt

Without -n, sort compares text, so 12 sorts before 3. Use a key field when each line holds both a name and a value. To write the result over the input, use the command's output option rather than shell redirection, which would empty the input first. See sort(1).

uniq compares neighboring lines only, so sort first to count every repeated value:

LC_ALL=C sort names.txt | uniq -c

wc -l -w -c names.txt counts lines, words, and bytes. The line count counts newline characters, so a last line with no newline isn't counted. Byte and character counts differ for characters that take more than one byte.

Translate characters #

tr changes or removes characters in standard input:

printf 'aster birch\n' | LC_ALL=C tr 'a-z' 'A-Z'

tr reads only standard input; it takes no file name. A range such as a-z doesn't convert letters in every writing system, so keep to ASCII text or use a tool that understands the language. Quote the character sets so that the shell doesn't interpret them.

Convert tabs and spaces #

expand -t 4 tabs.txt replaces each tab with the spaces needed to reach the next tab stop, and unexpand -t 4 spaces.txt turns suitable runs of spaces back into tabs. Without -t, expand puts tab stops eight columns apart. Keep the original when tabs carry meaning in the file's format.

Reflow and paginate #

fmt -w 30 notes.txt rejoins the words of each paragraph into lines of at most 30 characters. Use it for prose only: it changes the line breaks that code, tables, and markup depend on. fold -s -w 12 breaks long lines without joining short ones. pr adds page headings and margins for printing, so don't pass its output to a program that expects the original lines.

Order dependencies #

tsort reads pairs in which the first item must come before the second, and prints an order that satisfies every pair:

printf 'prepare build\nbuild test\n' | tsort

If the pairs form a cycle, no order exists and tsort fails; check its exit status rather than using partial output. Items with no dependency between them can come out in any order.

Shuffle and index #

shuf names.txt prints the lines in a random order, and can take a sample. Given a recorded random source, it repeats the same shuffle, which helps in testing but isn't suitable for choices that must be unpredictable. ptx builds a keyword index that shows each word with the text around it.

Commands on this page #

This page covers these commands:

CommandUse it toManual
sortSort linessort(1)
uniqCollapse or count repeated neighboring linesuniq(1)
wcCount lines, words, and byteswc(1)
trTranslate or delete characterstr(1)
expand, unexpandConvert between tabs and spacesexpand(1), unexpand(1)
fmtReflow paragraphsfmt(1)
foldWrap long linesfold(1)
prPaginate text for printingpr(1)
tsortOrder items by their dependenciestsort(1)
shufShuffle or sample linesshuf(1)
ptxBuild a keyword-in-context indexptx(1)

Verifying Checksums and Encoding Bytes

Peios / Using Peios / Working with Text

A checksum, or digest, summarizes a file's bytes so that you can later check whether they changed. An encoding represents bytes as printable text so that they can pass through an interface that carries only text. Neither proves who produced the data: that needs a trusted source for the expected value, or a signature.

The examples use sample file names such as release.txt. Create those files first, or substitute your own.

Record and verify digests #

Record a SHA-256 digest of a file, then check the file against it:

sha256sum release.txt > checksums.txt
sha256sum -c checksums.txt

The check reports each file and whether its bytes still match, and fails if any doesn't. Anyone who can replace both the file and its checksum list can make the check pass, so get the expected digest through a channel you trust, or verify a signature with a trusted key.

cksum offers several algorithms through one command. Name the algorithm so that a saved result says what it means:

cksum -a sha256 release.txt

The default cksum algorithm and the older sum checksum detect accidental changes, such as transmission errors. They have too few possible values to identify a file securely, so use a cryptographic digest such as SHA-256 for new work.

Encode and decode bytes #

Encode a file as Base64 text, then decode it:

base64 original.bin > encoded.txt
base64 -d encoded.txt > decoded.bin

base32 works the same way with a different alphabet. basenc selects among several encodings, such as --base64url, the variant used in web addresses. Use the encoding the receiving program expects: Base64 and its URL-safe form look alike but aren't interchangeable.

Encoding isn't encryption: anyone with the text can decode it. A decoder can write part of its output before it finds invalid input, so check its exit status, and don't let another program use the output until the whole decode has succeeded.

Commands on this page #

This page covers these commands:

CommandUse it toManual
sha256sum and the other digest commandsRecord and check file digestssha256sum(1)
cksumCalculate a checksum with a chosen algorithmcksum(1)
sumCalculate an older checksum another system requiressum(1)
base64, base32Encode bytes as textbase64(1), base32(1)
basencEncode with a chosen alphabetbasenc(1)

Printing Output and Reading Command Status

Peios / Using Peios / Scripts and the System

A command reports results in two ways: the data it writes to its output, and an exit status, a number where zero means success. Scripts use output for data and status for decisions. These commands are the building blocks for both. The man page for each command lists every option.

Your shell has its own versions of some of these commands, such as echo, printf, test, and kill. To run the utility itself, put peiosutils before its name, as some examples here do.

The examples use sample file names such as report.txt. Create those files first, or substitute your own.

Print messages and values #

echo prints its arguments, which suits a short fixed message:

peiosutils echo 'Build complete'

For any value that comes from elsewhere, use printf with a fixed format, so that the value can't be read as an option or as formatting:

peiosutils printf '%s: %d\n' Aster 3

Keep the format under your control and pass data as the later arguments. The format repeats if more arguments remain.

seq 2 2 8 prints numbers from 2 to 8 in steps of 2, and yes sample prints a line repeatedly until it is stopped. Don't pipe yes into a program to answer prompts you haven't read: use the program's own option for running without prompts. numfmt --to=iec-i shortens a byte count with a binary prefix, which scales by powers of 1024. The result is rounded, so keep the exact number for any calculation.

Run a command with a changed environment #

env runs one command with an extra or changed environment variable, without changing your shell:

env PEIOS_EXAMPLE=ready peiosutils printenv PEIOS_EXAMPLE

printenv prints one variable when you name it, and fails if the variable doesn't exist, which tells an empty value apart from a missing one. Without a command, env prints the whole environment, which can contain credentials, so don't share that output. A cleared environment helps make a command repeatable, but it isn't a security boundary.

Test conditions #

test reports a condition through its exit status and prints nothing:

if peiosutils test -f report.txt; then
  peiosutils printf '%s\n' 'Report is a regular file'
fi

Quote variables so that an empty value stays one argument. A file test describes one moment: the file can change before you use it. true and false exist only for their status. Don't add || true to hide a failure unless you've handled the failure you expect.

expr 7 + 5 evaluates a small integer expression; quote operators such as * that the shell would interpret. factor 84 prints the prime factors of a number.

Read exit statuses #

A false condition isn't always an error. expr, for example, uses one status for a zero or empty result, another for a true result, and a third for an invalid expression. In a pipeline, each command has its own status, and the shell decides which one the pipeline reports. Read a command's man page before treating every nonzero status the same way.

Save a stream while showing it #

tee writes its input both to standard output and to a file:

printf 'Starting\nFinished\n' | tee progress.log

tee replaces the file's contents unless you use append mode. A new file inherits security from its directory, and an existing file keeps its own, so choose the directory with care when the stream holds private data.

Commands on this page #

This page covers these commands:

CommandUse it toManual
echoPrint a short messageecho(1)
printfPrint values with a fixed formatprintf(1)
seqPrint a sequence of numbersseq(1)
yesPrint a line repeatedlyyes(1)
numfmtFormat numbers for people to readnumfmt(1)
envRun a command with a changed environmentenv(1)
printenvPrint an environment variableprintenv(1)
testCheck a conditiontest(1)
true, falseSucceed or failtrue(1), false(1)
exprEvaluate a small expressionexpr(1)
factorPrint prime factorsfactor(1)
teeCopy a stream to a file and to outputtee(1)

Reading System Information

Peios / Using Peios / Scripts and the System

Use these commands to read facts about the running system: the time, what is running, how much processing capacity is available, and the terminal you are using. Each value describes one moment, so don't rely on it staying the same. The man page for each command lists every option.

Read the time #

Print the current time in Coordinated Universal Time (UTC), in a form that other programs can read unambiguously:

date -u '+%Y-%m-%dT%H:%M:%SZ'

Printing a time doesn't change the clock. Setting the clock requires the relevant authority, and can affect scheduled jobs. To manage the clock and time zone, see Keeping the Time.

Identify the system #

uname -s prints the kernel's name and uname -o the operating system's. arch prints the machine architecture. These values don't tell you which version of each installed component you have, or whether a particular program will run: use the package information and each program's own checks for that.

hostname prints the machine's host name. Another machine can't necessarily find this one by that name; that depends on the network and its name service. Make a lasting change through the network configuration, because a configuration service can restore its own value over a name you set directly.

hostid prints a short identifier kept for compatibility. It can repeat across machines, so never use it to identify a machine securely.

Check capacity and load #

nproc prints the number of processors available to the current program, which can be fewer than the machine has. Memory and storage can limit parallel work too, so use it as a starting point when choosing how many jobs to run.

uptime shows how long the system has been running and its load: a measure of work that is running or waiting, not a percentage of processor use. For signed-in sessions, use Inspecting and Ending Sessions instead.

Check the terminal #

tty prints the terminal connected to standard input, and fails if input comes from a pipe or a file. A script can use that status to tell whether a person is typing. stty -a shows the terminal's settings, such as whether typed characters are echoed. If a script changes those settings, save them first and restore them even when the script fails.

Commands on this page #

This page covers these commands:

CommandUse it toManual
datePrint or set the timedate(1)
unamePrint system identifiersuname(1)
archPrint the machine architecturearch(1)
hostnamePrint the host namehostname(1)
hostidPrint the host identifierhostid(1)
nprocPrint the processors availablenproc(1)
uptimePrint how long the system has run, and its loaduptime(1)
ttyPrint the terminal connected to inputtty(1)
sttyRead or change terminal settingsstty(1)

Running and Controlling Commands

Peios / Using Peios / Scripts and the System

Use these commands to control how and how long another command runs. They suit short jobs in a terminal or a script. A job that must keep running, restart when it fails, or start when the machine starts belongs to the service manager instead; see Services and Jobs. The man page for each command lists every option.

Wait and set time limits #

sleep 0.1 pauses for a tenth of a second. A pause doesn't prove that anything finished, so wait for an explicit sign that a service is ready rather than sleeping and hoping.

timeout stops waiting for a command after a time limit:

timeout 1 peiosutils sleep 0.1

When the limit expires, timeout sends a signal, and the command must still respond to it. An option can force a stop after a grace period, but a command stopped part way through can leave partial output behind. See timeout(1) for its exit statuses.

Keep a command running after you disconnect #

nohup starts a command that keeps running when its terminal disconnects. Output that would have gone to the terminal goes to nohup.out in the working directory instead. A new nohup.out gets security that admits only you; an existing one is added to and keeps its own security. nohup doesn't put the command in the background (end the line with & for that), and it doesn't protect the command from failing, other signals, or shutdown.

Adjust priority and buffering #

nice -n 5 runs a command with a lower scheduling preference, so it yields to other work. Raising a command's preference needs extra authority. Niceness doesn't change the command's identity or what it can access.

When a pipeline's output arrives late because a program holds it in a buffer, stdbuf -oL asks the program to write each line as soon as it is complete. It works only for programs that use the standard C output functions; a program's own option for flushing output is more reliable.

Send signals #

peiosutils kill -l lists the signals. kill sends a signal to a process: a request to change state, which a program can handle. The usual stop signal lets a program clean up; a forced kill doesn't. Process numbers are reused after a process ends, so check the target first. Whether you can signal a process is an access decision, and knowing its number grants nothing.

Run a command in another root directory #

chroot runs a command with a different directory as its root, so that absolute paths are found inside that directory. The directory must contain everything the command needs, including its libraries. A changed root only changes where paths are looked up: it doesn't change the command's access token, privileges, network access, or open files, so it isn't a way to contain untrusted code. It also requires the relevant authority.

Flush pending writes #

sync asks the system to write pending changes to storage. How durable the data then is still depends on the filesystem and the device. sync doesn't make a half-written file complete or check that its contents are right.

Commands on this page #

This page covers these commands:

CommandUse it toManual
sleepPause for a timesleep(1)
timeoutRun a command with a time limittimeout(1)
nohupKeep a command running after a disconnectnohup(1)
niceRun a command with a different prioritynice(1)
stdbufChange a command's output bufferingstdbuf(1)
killSend a signal to a processkill(1)
chrootRun a command in another root directorychroot(1)
syncWrite pending changes to storagesync(1)

Checking Who a Command Runs As

Peios / Using Peios / Scripts and the System

whoami, id, groups, and logname give quick answers about the identity a command runs with. They show the account name and group memberships, but not everything that decides what the command can do. For that, read the command's access token with token.

Read the account name #

whoami prints the name of the account the command runs as. If the identity service can't find a name for the account, whoami fails, but the command still has an identity: a failed lookup is only a failed lookup.

logname prints the account that signed in to the session. It can differ from whoami when a program has taken on another identity.

Read identity numbers and groups #

id shows the account and its groups as numbers, with their names, and adds the user's security identifier (SID) and integrity level. The numbers are kept for compatibility. Peios decides access with SIDs and the other contents of the token, and the numbers can't show all of them: some groups have no number, and a deny-only group looks the same as an ordinary one. Two commands can print the same numbers and still be allowed different things.

groups prints the group memberships that have numbers.

Ask about the command or about an account #

Without an account name, id and groups describe the command you run them from, using its token. With an account name, they ask the identity service about the account record instead. A token includes groups added at sign-in, such as Everyone, that aren't stored in the account record, so the two answers can differ without either being wrong.

See the full token #

When an access decision depends on more than names and numbers, read the token:

token show --all

It shows every group with its attributes, the privileges, and the integrity level. See Inspecting Effective Identity.

Commands on this page #

This page covers these commands:

CommandUse it toManual
whoamiPrint the account a command runs aswhoami(1)
lognamePrint the account that signed in to the sessionlogname(1)
idPrint identity numbers, names, SID, and integrity levelid(1)
groupsPrint group membershipsgroups(1)
tokenShow the full access tokentoken(1)

Local Accounts

Peios / Using Peios / Local Accounts

Local accounts identify people and services known to this machine. The local principal source is lpsd. It stores those accounts and checks their credentials. Use lps(1) to administer the store through the daemon.

An account is one kind of principal: an identity that can receive access. Groups collect principals so that access rules can name a group instead of every member. Each local account and group has a security identifier (SID), which remains the same when its name changes.

Identity, credentials, and access #

Three separate decisions determine a sign-in:

  • The account: its name, SID, group memberships, and profile.
  • Its credentials: the password or public keys it holds and the policy selecting which credentials it accepts.
  • Machine policy: the privileges and integrity level that authd places on the resulting access token.

An access token records the identity and authority of a running process. lpsd supplies identity information; authd grants the token. A source cannot grant a privilege by adding it to an account's profile.

Changing a password and requiring that password are separate actions. For example, setting a password on an account with the none credential policy does not stop credential-free sign-in. Read Managing Credentials before changing the permitted methods.

Choose the right tool #

Use the tool for the task you need:

  • Inspect or administer local accounts: use lps as an administrator.
  • Sign in at a terminal: use the managed console's login(1) client.
  • Integrate an application: use the authentication client library.
  • Diagnose the daemons: start with Diagnosing Authentication.

lps does not edit the store file directly. lpsd checks the caller's token, applies the request, and saves the result. An ordinary signed-in account does not acquire administrative rights by running the command.

Changes and existing sessions #

An account change affects later requests and tokens. Removing a group, changing a password, or stopping an account from signing in does not rewrite access tokens already issued to it.

For retiring an account, distinguish stopping further sign-ins from ending existing work. Follow Retiring an Account, and keep a working administrator session while changing access.

For desktop administration, use Principals Manager. Personal display names, passwords, and keys are covered by My Settings. Those interfaces preserve the same distinction between identity, credentials, and machine grants.

Profiles and Claims

Peios / Using Peios / Local Accounts

A profile tells a client how to start a session. Claims describe account attributes that access rules can evaluate. Both are stored with the account, but they serve different purposes.

Profile preferences #

The profile includes a home path, shell path, and display name. An administrator changes it with lps set. For example:

lps set alice --display-name "Alice Chen"
lps show alice

The display name is presentation text. It is not a credential, an account lookup key, or evidence of a different identity. A person can change their own display name through the self-service account interface.

Changing a home path does not move files. Changing a shell affects later sessions rather than replacing a running shell. Use absolute paths for homes and shells; login rejects a relative profile path and uses its fallback.

Renaming an account with lps rename is a separate action. The account's security identifier (SID), group memberships, and recorded home remain unchanged.

Claims used in access decisions #

A claim has a name, a value type, and one or more values. An administrator can set a claim such as a department:

lps claim set alice Department string Engineering
lps show alice

The claim has an effect only where an access rule evaluates it. A string named Administrator does not grant administrator membership or a privilege by itself.

Claim names use per-character Unicode lowercase matching without normalization or full case folding. Équipe and équipe name one claim; ß and ss do not. Setting department replaces an existing Department claim. A claim with no values remains present and is different from removing the claim; access rules can distinguish the states.

Claims are copied into a token when it is issued. Changing a stored claim does not change tokens that already exist. Test the intended access rule with a fresh session after a claim change.

Octet claim values use pairs of ASCII hexadecimal digits. Invalid text, including non-ASCII characters, produces a usage error without changing the account.

The complete claim types and command syntax belong to lps(1). The machine's privilege grants are described separately in Granting Access.

Sessions and Account Changes

Peios / Using Peios / Local Accounts

A logon session groups work started with a granted identity. Its access tokens contain the account information and machine policy evaluated when the tokens were issued. Changing the stored account does not rewrite them.

Stop new access and active work separately #

Turning an account off, changing its password, removing a key, or removing a group membership changes later authentication and token creation. A program already running with a token can retain its previous access.

For an account retirement or suspected credential compromise, decide both whether further sign-ins are permitted and whether existing sessions must end. Neither action substitutes for the other.

Ending a session #

An authorized client asks authd to end a session. The authority finds processes whose primary tokens belong to it, asks them to exit, and kills survivors after a grace period. Repeated scans are bounded, so the result can report processes that remain.

The kernel removes the session when its last token reference is released. An external process holding a token reference can keep the session alive after its ordinary processes have exited. Ending a session is not a promise that every reference to its tokens has disappeared.

Who can request it #

A signed-in person can end their own eligible session. Ending another person's session requires access granted by SessionEndSecurity under Machine\Generic\Authn\Policy. SYSTEM, anonymous, and service sessions are protected from this operation.

The library offers a permission query so an application can decide whether to present an action. The actual request is checked again; a query is not a reservation of authority.

If the requesting application belongs to the target session, authd replies before ending its processes. Counts in that reply are prospective rather than confirmed terminations. The application can disappear before it renders the result.

Read authd(8) for termination behavior and the registry manual for Machine\Generic\Authn\Policy:SessionEndSecurity. Application authors should also read Self-Service Operations.

Creating an Account

Peios / Using Peios / Local Accounts

Create an account with lps when someone needs an identity held by this machine. Account creation saves the identity and profile; the home directory is prepared separately at sign-in.

Before you start #

Check these prerequisites:

  • Use a session with active Administrators membership or authorized LocalSystem access.
  • Confirm that lpsd is ready.
  • Keep an existing administrator account available. These instructions do not provision a machine's first account.

Create and inspect the account #

Follow these steps:

  1. Run the interactive account creator:

    lps add alice
    

    Replace alice with the account name. Supply the requested profile and password, review the proposed account, and confirm it. Leave additional groups empty unless the account needs them.

  2. Inspect the saved account:

    lps show alice
    

    Check its state, credential policy, groups, home, and shell. An ordinary account defaults to /home/alice and /bin/sh. No matching per-user group is created automatically.

  3. Keep your administrator session open and sign in as alice through a separate permitted console or client. Check that the intended shell starts and the home directory is accessible.

The final check tests the complete sign-in route. A saved account alone does not prove that a client can reach the authority or collect its required credentials.

Administrator accounts #

If the account must administer the machine, request the membership during creation:

lps add alice --group Administrators

This grants access to local account administration. The separate machine policy determines the privileges on tokens issued to that group.

Home directories #

lps records the home path without creating the directory. When authd grants a logon with a home path, it creates a missing home with access for the account, LocalSystem, and administrators. The descriptor blocks inherited grants from widening that access. The directory is created with that descriptor, so it never exists without it. The parent directory must already exist; authd creates the missing leaf, not a parent tree.

The shipped authd service retains SeRestorePrivilege to assign the new home's owner and group. If it is removed from the service's RequiredPrivileges, the kernel refuses the descriptor and no home is created. The authority's diagnostics record the failure, and the logon starts in /. Retrying a sign-in does not take over a directory that already exists.

An existing directory is left alone. Changing the recorded home does not move files or repair its ownership. If home preparation fails, the logon can still succeed; login reports an inaccessible home and starts in /.

Every kind of logon prepares the home by default, including network logons such as file sharing, so a file server can offer users their homes. To limit it, list the logon types that should prepare homes in Machine\Software\Authd ProvisionLogonTypes. For the Windows behavior, where a network logon creates no profile, leave out Network and NetworkCleartext. The same setting governs the account's per-user Registry root.

The first account #

On a machine with no store, lpsd creates an empty store and a machine domain. It does not invent an administrator or a password. An image must provide an authorized first-account setup route.

An installed image can use first-boot setup. A custom image must enable that service or provide another authorized provisioning route. A service that uses lps to provision an account starts after lpsd is ready; an early boot script running before the services cannot use its socket.

The optional dev.peios.authd-live-account package supplies a development bootstrap. Its credential-free administrator is a deliberate image policy choice, not a default for installed systems. Do not use that package to solve ordinary account creation on a production machine.

For exact creation options, read lps(1).

Managing Credentials

Peios / Using Peios / Local Accounts

Manage an account's credential material and its permitted methods as two separate steps. Adding a password or public key does not change which methods lpsd accepts for that account.

Before you start #

Prepare an alternate access route:

  • Use an administrator session for these lps commands.
  • Keep a working administrator route open while changing another route. Verify a fresh sign-in before closing it.

Inspect the account first:

lps show alice
lps key list alice

Replace alice with the account name. Credential policy selects the accepted proof:

PolicyAccepted proofRequired material
passwordPasswordStored password verifier
keySSH public-key proofEnrolled public key
eitherPassword or SSH public-key proofMaterial for the chosen method
noneNo credentialNone
deniedNo accepted methodNone

Missing material does not cause a fallback to another method. The client and authority also constrain which method and kind of logon are allowed. The terminal login client cannot perform an SSH public-key exchange.

Require a password #

Follow these steps:

  1. Set the password through the prompt, keeping it out of command history:

    lps password alice
    
  2. Select password authentication:

    lps policy alice password
    
  3. Inspect lps show alice, then verify a fresh sign-in with that password.

Both steps are needed when replacing none policy. Setting the password alone leaves credential-free sign-in permitted.

Add a public key #

Follow these steps:

  1. Enroll the public key file:

    lps key add alice /path/to/alice.pub workstation
    

    Replace the path with a public key file. workstation is a descriptive label. Do not supply a private key. Supported keys and input restrictions are documented in lps(1).

  2. Inspect lps key list alice and compare the fingerprint with the key you intended to enroll.

  3. If password access must remain available while checking the key, select both methods:

    lps policy alice either
    
  4. Verify a fresh connection through an SSH service configured to use this authority. Only after that check, use lps policy alice key if the account must accept keys exclusively.

Enrolling a key does not configure an SSH server or make one reachable.

Remove a key #

Follow these steps:

  1. Run lps key list alice and identify the key to remove.
  2. Pass its listed key ID to lps key remove alice <key-id>.
  3. Inspect the list again and verify the remaining sign-in route.

The administrative command takes the key ID, not its fingerprint. The public library's self-service removal operation takes a fingerprint; do not interchange the two interfaces.

Removing a key or changing policy invalidates pending SSH key proofs but does not end existing sessions. Stopping active access is a separate session operation.

Self-service changes #

A person changing their own password or keys uses an authentication conversation through authd, rather than the administrative socket. lpsd requires an accepted current password for these operations. An account with only a key, no credential, or no stored password needs an administrator's help.

Application authors can use the self-service client operations.

Managing Groups

Peios / Using Peios / Local Accounts

Use a local group when several accounts need the same access. The group has its own security identifier (SID), so its name can change without changing the identity named by access rules.

Before you start #

Check these prerequisites:

  • Use an administrator session with access to lpsd.
  • Create the account alice before following this example.

Create a group and add a member #

Follow these steps:

  1. Create the group with a description:

    lps group create developers "Local development team"
    
  2. Add the account:

    lps group add alice developers
    
  3. Check lps group list and lps show alice. Verify the group and the account's membership before using the group in an access rule.

  4. Start a fresh session for alice to receive a token with the changed membership. Existing tokens retain their previous groups.

Creating the group does not grant access to any file or service. Assign that access separately using the resource's security policy.

Name a group unambiguously #

lpsd resolves a group name, a qualified built-in name, or a literal SID. Well-known names such as Administrators take precedence over local names, and local groups cannot take those reserved names.

For automation or policy that must survive renaming, use the SID reported for the group. In authd's registry policy, use a local group's literal SID; local group names are not resolved there.

Change or remove a group #

Rename a group with lps group rename developers engineers. Its SID and members remain. A description can be changed separately with lps group describe.

To retire a group, first remove its memberships and replace any account's primary-group assignment. lps group delete refuses a group that still has members or is used as a primary group.

Before deletion, also review resources whose access rules name the SID. Deleting the group does not rewrite those rules. Recreating its name allocates a different SID and does not restore its access.

Read lps(1) for the full command syntax.

Retiring an Account

Peios / Using Peios / Local Accounts

Retire an account by stopping further sign-ins before deciding whether to delete its identity. Keeping the account preserves the security identifier (SID) used by its files and other access rules.

Before you start #

Prepare access and active work:

  • Use an administrator session other than the account being retired.
  • Keep another verified administrator route available.
  • Save work in sessions that must end. Ending a session can stop applications before they save their work.

Stop further sign-ins #

Follow these steps:

  1. Inspect the account with lps show alice and record its SID and groups.

  2. Stop it from signing in:

    lps disable alice
    
  3. Inspect lps show alice again to confirm the saved state.

  4. If active access must stop, use a session-management client to end its existing sessions. Account state changes do not revoke issued tokens.

To restore the account later, use lps enable alice, inspect its policy, and verify a fresh sign-in.

The last-administrator guard #

lpsd refuses several changes to the last account it counts as an active administrator. These include deletion, stopping sign-in, removing its administrator membership, and leaving it no permitted credential material.

The guard counts accounts that are turned on and hold administrator membership. It does not prove that another administrator has usable credentials, permitted logon types, or a reachable sign-in route. It also does not validate the whole machine's registry policy. Verify an alternate route yourself.

Delete only after reviewing ownership #

If the identity must be removed permanently, review files and access rules that name its SID before running lps remove alice.

The account's identifier is never reused. Creating another alice does not restore the deleted identity, its group membership, or its access. Deleting the account also does not remove its home directory.

Read Sessions and Account Changes for the limits of ending active access.

Principals Manager

Peios / Using Peios / Local Accounts

Principals Manager displays identities the machine knows and administers local users and groups through lpsd. Built-in identities such as SYSTEM and Administrators are defined by the system; they are not ordinary local accounts to recreate or delete.

Users and Groups show names, identifiers, membership, and available details. A user's page includes permitted sign-in methods, claims, and administrative credential information where access allows it.

Local-account changes go through lpsd. The backend enforces its rules, including retaining an enabled administrator that can sign in. The window reports a refusal rather than bypassing that safeguard.

Privileges edits local sign-in policy in the registry. Those records can set privileges, integrity, owner, and a default discretionary access control list. A user's page previews the combined policy for a new sign-in. Changing that policy is separate from editing the local account, and uses the policy key's write access.

Account administration requires the enabled Administrators group in the requester's token. Policy writes require the registry rights instead. The interface shows read-only data when it can inspect an object but cannot change it. Changes to sign-in policy apply to new sign-ins, not retroactively to existing tokens.

See Managing Local Accounts and gxwi-principals-manager(1). The account authority and shared sign-in semantics remain documented with authd and lpsd.

Reviewing local policy #

Privileges lists local policy records and a Denied to everyone entry. A denied privilege cannot be granted by another record. A user's policy preview combines the records for that user, their groups, and Everyone; select the intended kind of sign-in before interpreting it.

New record selects a principal. Edit changes its privileges, integrity, owner, or default DACL. An empty field makes no assignment for that field. Delete removes the record; it does not imply a deny if another applicable record still grants access. Default DACL text must be valid SDDL understood by authd.

The editor warns before removing SeChangeNotifyPrivilege from Everyone or Administrators because losing directory-traversal privilege can prevent shell startup. On a machine with no policy, authd's default gives Everyone that privilege. The editor preserves this default when it creates the first policy, rather than silently discarding it.

Policy warnings above the list identify records authd ignores or duplicate principal assignments. Resolve these using the shared account-policy reference. Refresh with F5 after another administrator changes an account or policy record.

Managing Accounts in Principals Manager

Peios / Using Peios / Local Accounts

Use Principals Manager for a local user's membership, credentials, claims, and permitted sign-in methods. Check the identity and the effect on future sign-ins before making a change.

Before you start #

You need the account-administration access enforced by lpsd. Preserve a working administrative sign-in route when changing administrative membership or credentials.

Inspect and change an account #

  1. Open Principals Manager, choose Users or Groups, and use Find to locate the identity.
  2. Select it and check its security identifier, local or built-in status, memberships, and sign-in configuration.
  3. Choose the intended account operation and review its confirmation. Change only the membership, claim, credential, or sign-in setting required for the task.
  4. Read lpsd's response. If it refuses a change that would leave no enabled administrator able to sign in, retain or repair another valid route before reconsidering the operation.

Check the result #

Refresh with F5 and verify the stored identity and membership. Test a new sign-in when the change concerns credentials or token policy. Existing sessions retain their own tokens.

Use Privileges for registry-based local sign-in policy. Its preview describes what a new sign-in would receive, not the rights of every already running process. For changing only your own display name, password, keys, or locale, use My Settings instead.

Choosing an account action #

Account actions have different effects:

ActionEffect
EditChanges the full name, home path, shell, or primary group. Changing the home path does not move files.
RenameChanges the name while retaining the SID and existing access grants.
Set passwordChanges the password without ending existing sessions.
Sign-inSelects accepted credentials and permitted kinds of sign-in.
DisableRefuses new sign-ins while preserving the account and its SID.
DeleteRemoves the account permanently; its old SID is not reassigned.

Adding an SSH key does not itself enable SSH-key authentication. Check Sign-in as well. Credential-free sign-in does not permit SSH access. Explicit permission to run a service is separate from ordinary sign-in methods. An empty claim and an absent claim have different meanings to access conditions; inspect the intended condition before removing one.

A group rename retains its SID. A user's primary-group membership cannot be removed until another primary group is assigned. Built-in groups with stored membership can have members added or removed, but their system identity cannot be renamed or deleted.

Disabling an account does not end its existing sessions. Use Task Manager to request sign-out when required, after accounting for unsaved work. The account store's last-administrator safeguard does not prove that a console or network sign-in route is reachable. Test fresh access before closing your working administrative session.

Creating an account #

To create a local user:

  1. Select Users, then New user, or press Ctrl+N.
  2. Enter the sign-in name and optional full name. Set and confirm a password, or explicitly select credential-free sign-in where permitted.
  3. Select administrator membership only when required. Check the proposed home path and shell before selecting Create.
  4. Read the result and verify the new user's SID and configuration. A refused creation does not leave a partially configured user.

To create a group, select Groups, then New group, and provide its name and description. Add members after verifying the new group's SID.

Changing Your Account Settings

Peios / Using Peios / Local Accounts

My Settings operates on your own account. Its backend identifies you from your token rather than accepting another account name. Use Principals Manager for administrative changes to other accounts.

Before you start #

You need a GXWI session and permission for the selected personal setting. Changing a password or SSH key requires your current password. A key-only account without a password cannot use those self-service forms.

Change a personal setting #

  1. Open My Settings and choose Account, Password, SSH Keys, or Language & Formats.
  2. For a display name, enter the new name and select Apply. For a password, enter the current password and the new password twice.
  3. For an SSH key, use Add Key with one public-key line and your password, or select Remove for the intended key and authenticate.
  4. Read the backend's outcome. Credential fields are cleared after the request, including on failure.

Check the result #

Inspect the resulting name or key list. Changed credentials and locale choices affect subsequent sign-ins; they do not replace the token of an already running session. Keep the current session available while verifying a new credential through the intended sign-in route.

System Default and Match Language remove the relevant personal locale override. Locale choices are written under CurrentUser\Locale and apply at the next sign-in. A restricted registry key makes the section read-only. Account state refreshes every five seconds. See gxwi-my-settings(1) for interfaces and file locations.

Language and formats together #

The form writes LANG and the time, number, money, measurement, and paper format categories together. Changing Language can therefore replace or remove individually configured format overrides. Use reg for a deliberate single-value edit instead.

Match Language removes personal category values; it does not remove machine category values. For one locale across these formats despite machine overrides, select it in both lists. Verify a fresh session as described in Choosing Session Locales.

Changing Your Password

Peios / Using Peios / Local Accounts

Use passwd to change the password of the account represented by your current process token. The account authority decides which credentials to request and whether the new password meets its policy.

Before you start #

  • Use a session for the account whose password you want to change.
  • Make sure authd and that account's authority are available.
  • Keep any credentials needed to verify your identity ready.

Change the password #

  1. Start the conversation:

    passwd
    
  2. Answer the prompts in the order shown. Terminal password input is not echoed. The authority can request several rounds of credentials.

  3. Wait for the result before retrying. A refused change reports that the password is unchanged; a lost connection after submission can leave the outcome unknown.

The command accepts no account name. To administer another local account, use lps password; see lps(1) for that command's requirements.

The local principal source requires an accepted current password for this self-service change. An ordinary account without one needs an administrator to set its password and choose the appropriate credential policy. A service principal does not become a personal account through this operation.

A password change does not mint a replacement token or end existing sessions. On the desktop, My Settings provides a client for the same credential-change conversation. For the API, use Self-Service Operations.

Check the result #

A completed change prints password changed. If the outcome is unknown, verify the account's state before attempting another change. The client does not automatically replay a submitted request.

Providing input through a pipe #

When standard input is not a terminal, passwd reads one line per prompt and does not print prompts for those lines. This requires knowing the account authority's conversation; a different policy can request different credentials or more rounds. Avoid putting passwords in shell history, command arguments, or ordinary temporary files. See passwd(1) for the command interface.

Inspecting and Ending Sessions

Peios / Using Peios / Local Accounts

Use logonse to inspect logon sessions and the processes associated with them. Ending a session asks authd to sign it out; destroying an empty kernel session is a different administrative operation.

Before you start #

  • Save work in any session you intend to end.
  • Use an account allowed to inspect the relevant processes. A complete kernel session listing needs access to the kernel's session list.
  • To end a session, run authd and use an account allowed by its session-end policy. You can request termination of your own eligible sessions.

Inspect a session #

  1. List sessions visible to you:

    logonse list
    
  2. Note the numeric session ID, then inspect it. Replace 1007 with the ID from your listing:

    logonse show 1007
    

The process listing contains only processes whose tokens you can inspect. It is a snapshot gathered while processes can start or exit. If the kernel session list is inaccessible, the command reports the limitation and uses visible processes to identify sessions. A session with no visible processes can still be held alive by a token.

Request a sign-out #

  1. Check permission without ending the selected session:

    logonse end 1007 --check
    
  2. After confirming the session ID and saving its work, request sign-out:

    logonse end 1007
    

The check does not reserve permission. Authd checks the actual request again. Service sessions end when their service stops; use svctl stop for that task. The kernel's own sessions cannot be ended this way.

Check the result #

Read the reported counts and any refusal. A nonzero remaining count means the session is still open. When ending the caller's own session, the reply can describe planned termination before the caller exits. If the connection is lost after submission, verify the session state before retrying.

Run logonse list from another session to inspect the resulting state. Token references can keep a session alive after its visible processes exit.

Other administrative operations #

logonse create creates a privileged kernel authentication record; it is not a way to authenticate a user. logonse destroy removes an empty session with no remaining token references. logonse psb inspects or changes process security settings, which have separate permission requirements. See logonse(1) for these interfaces and the JSON output option.

Interpret session evidence #

A process or thread's token statistics contain auth_id, the key used to join it to a kernel logon-session record. Looking at primary tokens answers which session the processes run under. Looking at effective thread tokens answers which session an impersonating request uses. These are different counts, neither of which enumerates every open token handle.

SYSTEM session 999 and Anonymous session 998 are bootstrap records, not unexpected interactive sign-ins. An authentication record can also exist before a token has been attached to a process.

The kernel's kacs.session.destroyed event records teardown after the last references are released. Its deferred emission can follow disappearance from the live list. Collection gaps mean an event stream cannot establish a complete session history by itself. Authd does not retain a complete queryable record of the grants and policy used for every past authentication.

Token expiration metadata is not a kernel timer or an AccessCheck revocation rule. A session-end request coordinates termination of its primary-token processes; it does not invalidate a token handle held elsewhere. Use the kernel lifecycle reference for those limits. For process protection, see Inspecting Process Security.

Granting Access

Peios / Using Peios / Authentication

authd reads local machine policy to decide which privileges, integrity level, owner, and default access rules a token receives. An account's principal source supplies identity and group membership, not these grants.

The policy lives under Machine\Generic\Authn\Policy. The registry manual for that path owns the value types, defaults, and combination rules. Use authd.regman when editing it.

Match policy to an identity #

Each principal-policy subkey names a well-known identity or a literal security identifier (SID). Use the SID for a local account or group. authd does not resolve a local group name while evaluating policy.

A record named Administrators refers to the built-in group. The spelling BUILTIN\Administrators cannot be one subkey name because the backslash separates registry keys.

Avoid two subkeys that resolve to the same SID. Their grants can combine, while conflicting scalar choices can depend on evaluation order. Keep one record per identity and investigate authd's duplicate-record warnings.

Start from the complete policy #

An existing policy key is the complete source of privilege grants. Its records are not merged with an invisible set of compiled grants.

If the whole key is absent, authd uses a small compiled floor granting SeChangeNotifyPrivilege to Everyone. If the key exists but cannot be read, authd grants nothing from that fallback. Deleting a policy key is therefore not a safe way to remove all access.

The shipped authd-policy.reg supplies explicit machine defaults. It is inert until image policy applies it. Installing the file does not prove that the machine has those values.

Combining grants #

Privileges combine across the user and the applicable groups. The machine-wide DeniedPrivileges mask is applied afterward, so another group cannot restore a masked privilege.

Scalar settings do not follow that union rule. A value explicitly set on the user's record takes precedence for that value. Otherwise, integrity uses the highest configured group level. Conflicting group choices for an owner or a default discretionary access control list (DACL) produce a diagnostic and fall back rather than selecting an arbitrary group.

For example, a user record setting integrity to Low can lower the result even when a group record specifies High. A user record specifying only privileges does not suppress the groups' integrity settings.

Defaults for newly created objects #

A token's DefaultDacl supplies access rules when object creation has no explicit or inherited DACL. It is not a rewrite of objects the account already owns. Without a usable default, an object with no other DACL can receive a null DACL, which does not restrict discretionary access.

Use OWNER RIGHTS (OW) when a default DACL should name the eventual owner. CREATOR OWNER is an inheritance placeholder and does not provide the same substitution in this fallback path. The shipped policy includes a parseable default; an invalid replacement is diagnosed and omitted rather than making every sign-in fail.

After editing policy, inspect a freshly issued token with token show --all, and test a disposable object through the application that will create it. Check both inherited access and the fallback case. A successful sign-in alone does not verify the intended access rules.

Separate the access checks #

A sign-in client must pass more than the account's credential check:

  1. The socket's security descriptor must allow it to connect.
  2. AuthenticationSecurity must grant the connected token the Logon right.
  3. Its own identity must be allowed to originate the requested logon type.
  4. The target account and principal source must allow that logon and its credentials.

The LogonTypes value in a principal-policy record controls what the requesting process can originate. lps logon-types controls the account being signed in. Changing one does not change the other.

Originator policy matches the peer token's user SID, not its group memberships. A service SID used as the user of a virtual service account can match; merely carrying the SID as a group is insufficient. SYSTEM has an explicit default Logon ACE and no additional caller logon-type restriction.

Authenticate uses a separate operation right and creates no OS session or token. It shares credential verification with Logon, then discloses the requested, permitted source groups and claims. It does not interpret those claims as permission to use a Wi-Fi network or another application.

For a virtual service account, configure capability names under its literal service-SID policy record in Capabilities. peinit requests its service token from authd, which adds those SIDs as enabled token groups. The default AuthenticationSecurity descriptor maps peios.auth.authenticate and peios.auth.logon to separate operations. Neither grants disclosure by itself. Changing assignments requires a new service token, normally by restart. The registry key's security descriptor controls who can edit this policy.

Apply changes at the right boundary #

Different settings have different refresh points:

SettingWhen authd uses itEffect on existing state
Token grantsWhen issuing a tokenExisting tokens retain their grants
AuthenticationSecurityOnce per Authenticate or Logon requestAn active conversation retains its descriptor snapshot
Service CapabilitiesWhen attesting a new service tokenRestart applies the assignment
SessionEndSecurityEach session-end permission checkA later request is checked again
LogonSocketDescriptorAuthority startupAn existing socket is not restamped by a registry edit
Source registration policySource registrationA connected source retains its accepted configuration

Keep a verified administrator route while changing policy. Validate a fresh request before assuming a registry edit has taken effect. For source configuration, read Registering a Principal Source.

Resolving Names

Peios / Using Peios / Authentication

authd resolves names, security identifiers (SIDs), and Unix identifiers through its registered principal sources. This gives clients one place to ask for the identity behind a name or number.

Names are not durable identifiers #

An account name can change or exist in more than one source. A SID names the identity itself. Store that SID when an application must remember which principal it authorized, and resolve a name for display.

For an unqualified name, authd uses configured source search order. The first matching source wins. A source that is unavailable can stop the lookup; authd does not silently choose a different person from a later source to hide the outage.

The name fields returned by this implementation use canonical bare names. Do not construct a realm-qualified name and assume it is accepted merely because a protocol field is named qualified_name.

Shadowed names #

Source order is explicit machine policy, not connection order. Lower SearchOrder values are consulted first; source names break ties. Changing that order can make the same bare name refer to a different SID.

After a successful logon, authd can warn that a later source also owns the entered name. The check uses identity queries without credentials and does not alter the granted token. Its deadline is shared across the later sources; a source that cannot answer makes the check inconclusive. Absence of a warning is not proof that a name is unique.

Investigate a warning by comparing the sources and SIDs. Do not remove an account merely because its name matches an account in another source.

Preserve failure meaning #

A lookup can report that an identity does not exist, that a source could not answer, or that the request was refused. These results require different responses. An unavailable source is not evidence that an account has been deleted.

For example, an application should keep an unresolved SID visible while reporting a lookup failure. Replacing it with a different local account or recording permanent absence would change its meaning.

Numeric identities and groups #

Sources report relative Unix identifiers. authd applies each source's configured range, checks its bounds, and returns the effective identifiers to clients. Clients should not repeat that arithmetic themselves.

Some well-known groups describe a session rather than a stored membership list. An empty member listing does not mean no token can carry that group. Likewise, a group without a Unix group identifier cannot be represented as an ordinary numeric supplementary group.

Recorded memberships can be enumerated when their source supports it. Groups such as Everyone and Authenticated Users are added by token derivation rather than stored as member lists. Groups such as Interactive and Network describe a logon, so the same account can carry different groups in two sessions. A static account-membership list cannot reconstruct every group on a running process's token.

Native and libc clients #

Native applications use the identity operations in libauth or its peios-auth Rust wrapper. They can inspect unavailable outcomes, withheld fields, and incomplete enumeration results.

The repository's name service switch (NSS) module translates libc account queries into requests on /run/ident.sock. It does not open the local principal store or provide an independent fallback database. Its libc result distinguishes an unavailable authority from an unknown account.

authd performs live source queries rather than keeping an identity cache. Do not assume an outage can be served from a previous successful lookup. For client handling, read Reading Identities.

POSIX Account Lookup

Peios / Using Peios / Authentication

libnss_peios.so.2 translates libc account queries into requests to authd's /run/ident.sock. An application using getpwuid or getgrnam receives a POSIX record derived from the same authority used by native identity clients. The module does not open lpsd's credential store.

A limited representation #

A struct passwd has no field for token claims. A numeric identifier does not carry a domain name. A group's empty member list cannot distinguish every reason that membership is not enumerable. Native applications needing these distinctions use the identity client API.

Groups derived from a logon, such as Interactive, have no ordinary static member list. Unnumbered groups are omitted from supplementary numeric groups rather than all being mapped to the fallback identity. Stored account memberships do not describe every group on a running token.

Preserve lookup failures #

The module distinguishes a record, a missing identity, a temporary source failure, and an unavailable authority. A temporary failure is not a cached answer that the account does not exist. If names stop resolving, inspect the authority and source state before changing accounts.

Before the authority is available, an application can have a valid numeric identity without a resolved display name. Display the number rather than requiring a name to perform early-boot work.

Enumeration can be incomplete when a source does not enumerate. A short getent passwd result does not establish that every other account is absent. Native callers can retain the response's incomplete-source information.

Requests and process lifetime #

A normal lookup asks for the fields needed by the libc call in one request. The authority resolves source ranges and group names; the module does not reconstruct them through a separate lookup for every member.

The client opens connections for individual lookups instead of sharing one across processes that can fork. Enumeration has its own cursor lifecycle. There is no independent identity cache or fallback account database in the module.

Peios' libc package fixes account lookup to this provider. Adding another identity source is an authority registration operation, not an nsswitch.conf entry that bypasses the authority's search order. The package's libc integration and the authd module are both required. Installing the module on another Linux system does not change that system's libc policy.

Authentication Services

Peios / Using Peios / Authentication

The authentication service set separates token creation from credential storage. authd issues tokens, while lpsd owns local accounts and checks their credentials. The service manager starts them from registry service definitions.

Readiness follows the protocol #

The authority opens its client and source sockets before reporting ready. The local source then connects to /run/psi.sock, registers, and waits for acknowledgment before reporting its own readiness.

The shipped dependency points from lpsd to authd. authd does not wait for every source before becoming ready, so authority readiness alone is not evidence that a local account can sign in.

The service definitions and registration seed have distinct purposes:

SeedPurposeApplied by
authd-service.regStart the authority with its required identity and privilegesImage or administrator policy
authd-policy.regSupply machine authentication-policy defaultsImage or administrator policy
lpsd-service.regStart the local source after the authorityImage or administrator policy
lpsd-authd-registration.regPermit the local source to register and define its rangeImage or administrator policy

These files are installed under /usr/share/regim/. Their presence does not apply their contents. A machine missing a registration seed can run the authority without accepting its intended principal source.

Keep each service's authority narrow #

authd runs with the authority needed to create tokens and establish their security state. Its package also requires the appropriate signing tier. A development binary that links successfully is not evidence that these runtime requirements have been met.

lpsd uses a distinct virtual service account. It needs access to its store and permission to emit audit events; it does not need token-creation or token-installation privileges. Its store descriptor grants access to the lpsd service identity and SYSTEM, not to every administrator.

RequiredPrivileges narrows the service token. It does not manufacture a privilege that machine policy did not grant in the first place.

Readiness is not a security-state handoff #

The authority does not connect to a directory to fetch credentials. Sources connect to it and verify credentials; local registry policy determines the grants on the resulting tokens. A source's asserted identity is constrained by its registration, including its domain and permitted foreign memberships. A source trusted to assert an administrator membership can affect local grants through that membership. Process separation does not make a compromised source harmless.

The client receives a token and profile and starts its own session. authd does not launch its shell or set up its terminal. Service attestation is a distinct request made by the service manager.

Restarting authd interrupts new conversations but does not replace tokens already held by processes. Kernel sessions survive while their token references remain. Authority readiness does not certify that every source has registered or that central access policies have been loaded: authd does not distribute those policies.

Inspect before restarting #

Use service status and diagnostic output to distinguish an authority startup failure from a source registration failure. Restarting either can interrupt authentication requests. Keep a separate working administrator route while investigating.

Read authd(8) and lpsd(8) for daemon behavior, then follow Diagnosing Authentication for common symptoms. Contributor build instructions live in the repository's docs/building.md.

The Local Principal Store

Peios / Using Peios / Authentication

lpsd keeps local identities in /var/state/lpsd/principals. The store contains the machine's domain identifier, account and group records, credential material, and allocation state. Losing it means losing the identities that existing access rules name.

The lpsd-service.reg seed declares /var/state/lpsd as the required lpsd-state entry under Machine\System\Init\ProvisionedPaths. peinit creates the directory before phase 2, owned by lpsd's service SID, with a protected inheritable descriptor granting full control to that SID and SYSTEM. The image or installer must supply /var/state; peinit does not create unnamed parents.

Identity survives names #

The machine domain is generated when a missing store is provisioned. Accounts and local groups receive relative identifiers from one counter, starting at 1000. Deleted identifiers are not reused.

A local security identifier (SID) combines the domain and relative identifier. Recreating the same account name in a fresh store therefore does not restore the old SID or the access granted to it.

Well-known group identities are defined separately. The store records memberships in them rather than inventing a local copy of their identity.

Do not bake a provisioned store into an image intended to create independent machines. Copying the store copies its domain and account identities; giving the machines different hostnames does not change those SIDs.

The stored Unix identifiers are relative. authd applies the source's configured numeric range when issuing tokens and answering lookups. lps displays the effective numbers. A dash in its UID column indicates that no usable source range was assigned; it is not evidence that the account lacks a SID.

Credential material stays protected #

The store holds password verifiers rather than plaintext passwords, along with enrolled public keys and credential policies. Password verifiers are still sensitive: a stolen copy can be used to guess passwords offline.

The lpsd virtual service account owns the credential file. Its protected discretionary access control list (DACL) grants full access to that service identity and SYSTEM. Administrator membership alone has no direct grant.

Do not widen the descriptor to make an account-management script work. Use the daemon's administrative interface, which checks the caller and keeps a single writer responsible for the store.

The password verifiers use Argon2id and retain their cost parameters. A change to the parameters for newly set passwords does not rewrite existing verifiers. Privileges and integrity levels are absent from the store: those come from machine policy.

Optional NT compatibility material #

Machine\Software\Lpsd StoreNtHashes controls an additional NT hash for password accounts. It defaults to REG_DWORD 1 during compatibility development. Argon2id remains present. The NT hash supports MSCHAPv2 and NTLMv2, which SMB file sharing uses; it is password-equivalent material and substantially cheaper to attack offline than Argon2id. The store has access-control protection, without an additional credential-encryption layer. Protect offline copies too.

BackfillNtHashes, under the same key, separately defaults to 1. When both settings are enabled, a successful password check can populate a missing NT hash while the verified password is transiently available. This is maintenance, without another sign-in step or sign-in failure if the save fails. Existing Argon2 records cannot be converted without the password. MSCHAPv2 or NTLMv2 success itself cannot perform this backfill.

Setting StoreNtHashes to 0 disables NT-based verification and creation, removes live NT material and attempts to save that removal. Old backups are unaffected. Inspect lpsd.credential.maintained for a failed save; memory remains disabled while durable cleanup is retried on later activity. Malformed or unreadable settings disable legacy use without requesting deletion. Changes are watched live and checked before source operations; multi-value reads are not an atomic Registry snapshot.

Password set/change updates the verifiers together under current policy. Password removal removes both. Password-policy restrictions apply to PAP, MSCHAPv2, and NTLMv2 alike. Pending proofs and backfill check credential versions to reject a password reset during the exchange. NT derivation uses exact UTF-16LE with no normalization; legacy non-UTF-8 password bytes retain Argon2 verification but cannot acquire NT material through this conversion.

lps show NAME reports whether NT material is present. No administrative, identity, or authentication API returns the stored NT hash. An authorized MSCHAPv2 authentication returns only its exchange-specific server proof, and an NTLMv2 one only its exchange-specific session key.

Administrative requests #

lps reaches /run/lpsd/admin.sock; it never edits the file. The socket's descriptor and the daemon's peer-token check admit SYSTEM and enabled Administrators membership. A deny-only administrator group does not grant access. Making the Unix mode more permissive does not repair a KACS denial.

Each connection carries one administrative request and its reply. The daemon checks the peer before reading a request and bounds reads and writes. For a refused connection, inspect the socket descriptor and the caller's token before changing either service configuration or account data.

Use the identity interface for general account lookup and the self-service interface for the caller's own account. These do not require widening the administrative socket. The public libauth client does not expose local administrative operations; lps and the repository's administrative client implement that separate protocol.

The Local Principal Administration specification defines message formats. Event names and fields belong to lpsd.evman; a successful no-op is not evidence that a change event will be emitted.

Replacement and failures #

Changes replace the whole store. lpsd creates a protected temporary file, writes and synchronizes it, renames it over the old file, and synchronizes the containing directory. Protection is established before credential bytes are written.

A successful administrative reply follows the save. A lost reply leaves the caller uncertain whether a submitted change took effect. Read back inspectable state before repeating it.

A storage error also needs investigation. In particular, failure to synchronize the directory after replacement can leave changed on-disk state even though the request reports failure. Do not assume every reported failure proves that both memory and disk retain the previous state. Stop further administrative changes and investigate the storage failure before relying on either view.

Format compatibility #

The credential-binding source reads formats 4 through 7 and writes format 7. Format 4 loads with empty group descriptions. Older password records load without NT material. Each password has an opaque reference and revision; replacement retains its reference and rotates its revision. NT-hash backfill, purging NT material, account enablement, and metadata edits do not rotate it.

Loading an older format assigns these bindings and atomically saves format 7 before exposing the store. A failed migration prevents startup. This is a specific compatibility range, not a promise that every release can read its predecessor's store. Preserve an offline copy before upgrade: older builds cannot read format 7.

Check format compatibility before replacing lpsd with an older build. Preserve the original store and its security metadata during any planned upgrade or recovery.

Missing and unreadable are different #

A missing store means an unprovisioned machine. lpsd creates a domain and an empty store, without creating an account.

An existing store that is corrupt, unreadable, or in an unsupported format causes startup to fail. lpsd does not silently replace it with an empty store. Do not delete the file to clear that error: preserve it for diagnosis and recovery.

The daemon and state paths are documented in lpsd(8).

Authentication Events

Peios / Using Peios / Authentication

Authentication events record what the authority and local source decided. They complement diagnostic logs: a source checking a credential and an authority delivering a token are separate outcomes.

Follow the decision that matters #

Use the event belonging to the stage you are investigating:

  • authd.logon.attempted: the authority's outcome for a logon conversation, including whether a granted token reached the client.
  • authd.service.attested: a request for a service identity and the authority's decision.
  • authd.session.ended: the outcome of a session-end request.
  • lpsd.credential.verified: the local source's credential check.
  • lpsd account, group, and credential events: changes to the local store and credential material.

A successful credential check alone does not prove that the authority granted a logon or that the client started a usable session. Inspect the authority result and client diagnostics as well.

Use the catalog for exact fields #

The canonical event definitions are authd.evman and lpsd.evman, shipped under /usr/share/evman/. Read them with evman for exact fields, tiers, and outcome meanings. The source copies live under docs/ in the authd repository.

For example, the authority's logon event omits the proposed account name on failure. Input supplied by a caller is not an authenticated identity. On success, the event identifies the granted principal by its security identifier (SID).

Interpret incomplete evidence #

An authority refusal, a transport failure, and a token that could not be delivered are different outcomes. Preserve the recorded reason rather than converting all of them into an incorrect-password count.

Event absence is not proof that nothing happened. Access to records, emission policy for configurable tiers, and collection failures can affect what you can see. Check service diagnostics when a required record could not be emitted.

Do not add credential values to diagnostic messages to investigate a failure. Account and session identifiers, operation names, and the documented outcome fields provide the correlation data.

Registering a Principal Source

Peios / Using Peios / Authentication

Register a principal source when authd must accept identities from that service. A source connects to authd; the authority does not discover or trust it merely because its process is running.

Before you start #

Check these prerequisites:

  • Use an authorized machine-configuration route.
  • Preserve an existing administrator session.
  • Confirm that the source implements the Principal Source Interface and runs with the service identity named by its registration.

For the shipped local source, the supplied lpsd-authd-registration.reg seed describes the expected configuration. Review that seed and authd.regman before applying image policy.

Configure and verify registration #

Follow these steps:

  1. Under Machine\Software\Authd\Sources, create or review the subkey for the source's service name. For the local source, that name is lpsd.

  2. Verify that the service's token carries the corresponding service security identifier (SID). The subkey name identifies the permitted service; a source cannot establish its identity by claiming that name in a message.

  3. Choose the source's numeric range and search order. If a fixed identity domain is required, configure its expected domain SID. Follow the types and constraints in the registry manual rather than copying another machine's generated domain.

  4. Start or deliberately reconnect the source through service management after the authority is ready. Inspect its service status and diagnostics for an accepted registration.

  5. Verify a lookup and a fresh permitted sign-in for an account from that source. A process that exists but has not registered cannot satisfy authentication requests.

For lpsd, readiness is reported after authd acknowledges registration. Its service definition therefore depends on authd, not the reverse.

Keep identity and membership authority distinct #

A source's declared domain limits which identities it can assert. Numeric range checks also prevent its relative identifiers from escaping into another source's range.

MayAssertForeignMemberships concerns group membership assertions. It does not authorize the source to authenticate identities in another domain. Grant it only where the source is trusted to provide those memberships; the local source has that role in the shipped configuration.

An absent or unusable Unix ID range does not cause authd to guess one. The unconfigured projection uses the fallback identity number. Verify the configured range before relying on numeric identity lookup.

Changing a registered source #

authd reads the allowlist during registration. A live registered source retains its accepted domain, range, search order, and membership grants. Editing or deleting its registry entry does not immediately revoke that connection.

Plan reconnection when changing those settings. Reconnecting cannot change a source domain already recorded during the running authd process's lifetime. A source interruption can make identity queries and sign-ins unavailable, so use an access route that does not depend on the source being changed.

The exact registry values belong to Machine\Software\Authd\Sources in authd.regman; shared protocol requirements belong to the Principal Source Interface specification.

Diagnosing Authentication

Peios / Using Peios / Authentication

Diagnose the stage that failed before changing account or machine policy. A denied credential, a refused socket connection, and an unavailable principal source are different failures.

Before you start #

Prepare the investigation:

  • Keep a working administrator session open.
  • Record the operation, account, client, and error text. Do not copy passwords or private keys into a log.
  • Use read-only checks before restarting a service or changing policy.

Locate the failing stage #

Follow these steps:

  1. Check whether the authority and local source are ready:

    svctl status authd
    svctl status lpsd
    
  2. From an authorized administrator session, inspect the target account with lps show <name>. Check its state, logon types, credential policy, and available credential material.

  3. Compare the failing operation with the symptom table. Inspect the relevant service diagnostics or event record before making a change.

  4. Make one justified change through the appropriate interface, then repeat a fresh request through the original client.

Match the symptom #

The symptom identifies a useful next check:

SymptomCheckDo not infer
lps cannot connectlpsd readiness and the admin socket's descriptorUnix mode bits alone determine access
lps refuses the callerThe caller's active administrator membership or SYSTEM identityExecuting an administration command grants its rights
Sign-in source unavailableRegistration, source readiness, and connection diagnosticsThe account does not exist
Credentials refusedAccount state, permitted logon type, policy, and supplied proofEvery refusal reveals whether the name exists
Key works but console failsWhether the account is key-onlyTerminal login supports SSH key proof
Sign-in succeeds but home failsRecorded path, parent directory, owner, and descriptorAnother sign-in will repair an existing directory
Registry edit appears ineffectiveThat setting's refresh boundaryEvery setting is reread on each request

Separate connection permission from operation permission #

Reaching /run/logon.sock does not authorize a client to originate every kind of logon. The authority checks the connected caller and the requested operation. Similarly, reaching the self-service socket does not authorize an operation on someone else's account.

For originator refusals, inspect Authentication Policy. For registration failures, inspect Registering a Principal Source.

Handle failed changes carefully #

If a connection is lost after an account change was submitted, inspect the state before retrying. The operation might already have succeeded. If the daemon reports a storage failure, preserve its diagnostics and investigate the filesystem before making further account changes.

Do not delete the principal store to repair a startup failure. Read The Local Principal Store for why replacing it changes the machine's identities.

Check the result #

A successful status query or account listing is only one part of the check. Verify a fresh sign-in through the intended route and confirm the resulting access before closing the administrator session used for repair.

Security Identifiers

Peios / Using Peios / Identity and Access

A security identifier (SID) is the value Peios uses to identify a principal: a user, a group, a service, the machine, or a built-in identity such as Everyone. Every permission on every object names SIDs, and every running program carries SIDs that say who it is. When you read a permission or diagnose a refusal, you are comparing SIDs.

Reading a SID #

A SID is binary, but tools show it as a string that starts with S-1:

S-1-5-21-3623811015-3361044348-30300820-1013

The parts after S-1 are numbers assigned by an authority. The 5 here is the authority, and the numbers after it narrow down to one principal. The last number is the relative identifier (RID), which tells principals apart within the same domain. Short SIDs belong to identities that every Peios system shares:

SIDIdentity
S-1-5-18Local System, the operating system's own identity
S-1-5-32-544The built-in Administrators group
S-1-1-0Everyone

These shared SIDs are called well-known SIDs. Well-Known SIDs lists the ones you meet most often.

Names are labels #

An account's name can change. Its SID doesn't. Renaming an account keeps its SID, so every permission that names the account still applies to it. A deleted account's SID is never given to another account, so old permissions can't start granting access to a stranger.

For the same reason, compare SIDs rather than names when you check who has access. Two different strings can spell the same SID, and a name only tells you what a tool chose to display.

A SID on its own doesn't tell you what a principal can do. Group membership, privileges, and the other details of a principal's authority come from the access token it runs with.

SIDs that aren't accounts #

Some SIDs identify something other than a person or a group:

  • Service SIDs identify one service, written by name as SERVICE\loregd. A service's programs carry its service SID as a group, so a permission can admit one service without admitting everything that runs as the same account.
  • Logon SIDs identify one sign-in or other logon, in the form S-1-5-5-X-Y. They let a permission admit one session without admitting every session of the same account. See Logon Sessions.
  • Integrity labels, in the form S-1-16-n, mark a level of trust. See Integrity Levels.
  • Placeholders stand in for another identity in a permission. When a new object inherits a permission that names Creator Owner, for example, the new object's owner takes its place.

Where SIDs are defined #

The Peios Common Data Structures specification defines the SID format and the complete catalog of well-known SIDs. It is the authority for every assigned value.

Access Tokens

Peios / Using Peios / Identity and Access

An access token is the identity a running program acts with. Each thread in a program carries one, and every time the thread opens a file, reads a registry key, or sends a signal, Peios checks the request against that token. The token, not the account name a program displays, decides what the program can do.

What a token holds #

A token holds the facts Peios needs to decide a request:

  • The user. The security identifier (SID) of the principal the token represents.
  • Groups. The SIDs of the groups the principal belongs to, and the logon SID of its logon session.
  • Privileges. The system operations the principal can perform. See Privileges.
  • An integrity level. A level of trust that limits what the token can change. See Integrity Levels.
  • Defaults for new objects. The owner and permissions that objects the program creates receive.

Some of these fields can be adjusted while the token is in use. A program can turn one of its privileges on or off, or turn a group off. The identity fields, such as the user, the set of groups, and the integrity level, can't be changed after the token is created.

To see the token a program is using, run token show. See Inspecting Effective Identity.

How a program gets a token #

A program can copy its token or make a weaker version of it, but creating a token for an identity is reserved for the kernel and two trusted programs, authd and peinit. Tokens come from three places:

  • At boot, the kernel creates the token for the operating system's own identity, Local System. The service manager, peinit, starts with it.
  • At sign-in, authd, the authentication service, checks your credentials against policy and creates a token for you. The program you signed in through, such as the console or the desktop, starts your session with it.
  • For a service, peinit gives the service's first program the token for the service's account.

After that, a new program inherits a copy of its parent's token. Running another program file keeps the same token, unless the file is marked to run at a lower integrity level. So everything started from your desktop or your shell runs with the identity you signed in with.

Primary and impersonation tokens #

A program's own token is its primary token, and its threads share it. A thread can also take on another token for a while, which is called impersonation. A service uses impersonation to act for a client: it handles the client's request with the client's identity, so the request can do only what the client could do. When the thread stops impersonating, it returns to the primary token.

A new program never inherits impersonation. It starts with its parent's primary token.

Account changes and running programs #

A token records the account as it was when the token was created. Changing an account afterward, for example adding it to a group, disabling it, or changing its privileges, doesn't change tokens that already exist. Programs already running keep their previous access.

To pick up a change, start a new sign-in. To stop a running session, end it: Inspecting and Ending Sessions covers the command and what it reaches.

The kernel's token model describes every field and operation.

Privileges

Peios / Using Peios / Identity and Access

A privilege lets a program perform a system operation that has no object to put a permission on: shutting down the machine, setting the clock, or loading a kernel module. Permissions live on objects, and privileges live on the program asking. Some privileges also let a program reach objects in ways their permissions alone wouldn't allow, such as reading a file for a backup.

Policy assigns privileges #

Privileges come from machine policy, not from who you are. Belonging to the Administrators group gives an account no privilege by itself. When you sign in, authd reads the policy under Machine\Generic\Authn\Policy, combines the privileges granted to your account and to each of your groups, and puts the result in your access token.

The policy that Peios ships gives every account a small set of privileges and gives Administrators many more, such as SeShutdownPrivilege and SeBackupPrivilege. It deliberately gives no one the privileges that create or install tokens. Granting Access explains the policy and how to change it.

A token keeps the privileges it was created with. A change to policy reaches only tokens created after it, so sign in again to pick it up.

Privilege states #

A privilege on a token is in one of these states:

  • Present. The token has the privilege. A privilege can't be added to a token after it is created.
  • Enabled. The privilege is in effect. A program can use a privilege only while it is both present and enabled. authd creates tokens with every granted privilege enabled.
  • Removed. The privilege is gone from the token for good. Removing a privilege can't be undone, unlike turning it off.

A program that needs a privilege only for a moment can turn it off when it is done, or remove it, so a later mistake can't use it.

Common privileges #

These are the privileges you are most likely to see in a token or a policy:

PrivilegeAllows
SeChangeNotifyPrivilegePassing through directories without permission to each one. Every account has it.
SeShutdownPrivilegeShutting down or rebooting the machine
SeRemoteShutdownPrivilegeShutting down or rebooting from a remote session, in addition to SeShutdownPrivilege
SeBackupPrivilegeReading any object for a backup, whatever its permissions
SeRestorePrivilegeWriting any object to restore a backup, whatever its permissions
SeTakeOwnershipPrivilegeTaking ownership of any object
SeSecurityPrivilegeReading and changing an object's audit settings
SeSystemtimePrivilegeChanging the system clock
SeImpersonatePrivilegeActing for a client with the client's identity
SeManageVolumePrivilegeMounting and managing volumes
SeLoadDriverPrivilegeLoading and unloading kernel modules
SeDebugPrivilegeInspecting and attaching to any process, whatever its permissions
SeTcbPrivilegeOperations reserved for the system's most trusted components

Privilege names are case-sensitive: write them exactly as shown.

A privilege doesn't override every protection. SeBackupPrivilege and SeRestorePrivilege apply only when a program asks for backup or restore access explicitly. Neither they nor SeDebugPrivilege bypass Process Integrity Protection, which guards trusted processes and the objects labeled for them.

The kernel's privilege catalog is the complete list, with each privilege's exact effect.

Logon Sessions

Peios / Using Peios / Identity and Access

A logon session records one occasion on which Peios established an identity: you signing in at the console, an SSH connection, or a service starting. Every access token belongs to exactly one logon session, and every token copied from it shares the same session. Knowing which session a program belongs to tells you how its identity was established, and lets you end everything that came from one sign-in together.

A logon session is separate from a terminal's session and from a desktop session: the word "session" names different things in each.

What a session records #

authd creates the logon session before it creates the first token for it. The session records:

  • the user's security identifier (SID);
  • the logon type, which says how the session began;
  • the time it was created;
  • an identifier that is unique while the machine is running.

The session's logon SID, in the form S-1-5-5-X-Y, comes from that identifier and is placed in the groups of every token in the session. A permission can name the logon SID to admit one session without admitting the account's other sessions. The identifier can recur after the machine restarts, so don't use it as a lasting record of an account.

A session lasts as long as any token that belongs to it.

Logon types #

The logon type describes the situation, not the account: one account can have sessions of several types at once.

Logon typeSession begins when
InteractiveSomeone signs in at the machine's console
RemoteInteractiveSomeone signs in from another computer, over SSH or to a desktop in a browser
NetworkA program on another computer authenticates to use a service here
NetworkCleartextAs Network, marked as using a credential that was sent unencrypted
NewCredentialsA program keeps its identity on this machine, marked as using other credentials for connections to other computers
BatchA scheduled job starts
ServiceA service starts

Every SSH connection is RemoteInteractive, including a single command run without a terminal. The names of the two variants describe their purpose, not what happened: NetworkCleartext doesn't prove that credentials crossed the network unencrypted, and NewCredentials doesn't make Peios forward credentials anywhere.

Sign-in policy can permit or refuse each logon type for an account; see Granting Access.

Ending a session #

Ending a logon session stops the programs whose primary token belongs to it. authd asks them to stop, then forces them. A program elsewhere that holds a copy of one of the session's tokens keeps the session alive, so ending it doesn't revoke every use of its identity. The Local System and service sessions can't be ended this way.

Inspecting and Ending Sessions describes the logonse command.

Integrity Levels

Peios / Using Peios / Identity and Access

An integrity level ranks how far Peios trusts a program or an object. Every access token has one, and objects can carry one. Before Peios reads an object's permissions, it compares the two levels. A program at a lower level can't change an object at a higher level, even if the object's permissions would otherwise allow it. A program handling untrusted input can therefore run at a low level, so that a fault in it can't change the system's own files and settings.

The levels #

Five levels are standard:

LevelValueUsed for
Untrusted0Code in a sandbox
Low4096Services handling untrusted input
Medium8192Ordinary sign-ins and most services
High12288Administrators
System16384The kernel, peinit, and the system's most trusted services

A level is written as a security identifier (SID) in the form S-1-16-n, where n is the value. Peios compares the numbers, so a value between two standard levels is valid too.

Your sign-in gets its level from machine policy. A token is Medium by default, and the policy that Peios ships gives Administrators High. A token's level can't be changed after it is created. A program file can be marked to run at a lower level than its parent, but nothing raises a running program's level.

The integrity check #

Each object can carry a label with its level. An object without a label is treated as Medium.

By default, a program can read an object at a higher level but can't write to it. A label can also stop a lower-level program from reading the object or running it. The integrity check comes before the object's permissions, and it can only take access away: a permission can't grant what the integrity check refuses. Rights that come from a privilege aren't removed by it.

Integrity and process trust #

Integrity levels are a property of the token, so they follow the identity a program acts with. Process Integrity Protection is a separate mechanism that follows the program itself, based on the signature of its program file. See Process Trust.

The kernel documents mandatory integrity control in full.

Identity and Authority

Peios / Using Peios / Identity and Access

An account record describes a principal. Authentication establishes which principal is requesting a sign-in. A token carries the runtime identity and authority used by a thread. An access decision combines that token with the object, requested operation, and applicable policy. None of these steps is interchangeable with the others.

A name is not a grant #

A security identifier (SID) identifies a principal. Resolved names are labels; compare parsed binary identities rather than names or a domain prefix. A SID alone does not reveal group membership, privileges, integrity, or whether an account is signed in. Different accepted text spellings can represent the same parsed SID; formatting differences alone do not establish inequality.

Use PCDS's SID reference for encoding and the well-known catalog for assigned identities. Avoid maintaining another numeric catalog in application documentation.

For policy, distinguish the intended audience: Authenticated Users is not Everyone, a service identity is not every process of its hosting account, and a logon SID identifies one authentication context rather than the account across sign-ins. Creator Owner is an inheritance placeholder; Owner Rights controls the owner's special grants on the object being checked. Integrity and process-trust labels belong to their mandatory-policy mechanisms, not ordinary group membership.

Accounts become runtime tokens #

Local account records, source resolution, and authentication policy participate in sign-in. Token creation is privileged; the kernel does not independently prove the truth of every claim a trusted creator supplies. Changing an account record does not rewrite tokens already running.

A token carries a user SID, groups and their attributes, privileges, integrity, claims, restrictions, and session context. A privilege is a grant for specific operations, not a substitute for identity. Integrity constrains categories of access. Process Integrity Protection belongs to the executing program's PSB, so impersonating another identity does not change program trust.

Claims are typed attributes. Token user/device claims, caller-supplied local claims, and object resource attributes have different provenance. A missing claim can evaluate to UNKNOWN: it does not satisfy a conditional allow and can preserve a conditional denial. Do not substitute an empty value for absence or treat a display label as a trusted claim. The condition specification defines the logic.

Follow the effective thread #

A process's primary token is the default identity for its threads. A thread handling a client can temporarily impersonate another token. Diagnose the thread that performed the operation, not only the account displayed for the process. Reverting returns to the primary token; it does not change the process's program protection.

Token fields and operations are defined in the kernel's token model. Identity fields cannot be arbitrarily relabeled by adjustment. Duplication, restriction, privilege adjustment, and primary-token installation have different gates and effects. A privilege can be disabled or removed; removal is not the same as a reversible disable.

Fork gives the child an independent copy of the parent's primary token, without inheriting an active impersonation. Threads share the primary token but have independent impersonation state. Exec reverts impersonation and normally retains the primary token, subject to the documented integrity lowering rule. See Token Lifecycle for installation convergence and exact transitions.

Authentication sessions and elevation #

A logon session records an authentication context shared by its tokens. It is separate from a terminal's job-control session and from an interactive environment scope. Do not use a boot-local session identifier as a durable account identity or assume its value cannot recur on another boot.

A session's type records how it was created. Local console authentication, remote SSH/GXWI sign-in, and service launch have different provenance. The type is not a blanket access grant; token groups and specific kernel operations give it effects. A NetworkCleartext name alone does not prove a password traversed an unencrypted network, and NewCredentials metadata does not implement an outbound credential broker by itself.

A linked Full/Limited pair is a kernel mechanism available to a trusted broker. It does not establish that every interactive sign-in uses a pair, that a consent interface exists, or that the caller can install its partner. The role can remain after the active link disappears. Use the linked-token reference and the actual broker's documented workflow.

Ending a session coordinates its processes; it does not revoke every token handle held elsewhere. Token expiration metadata is not a kernel access-check timer. Follow Inspecting and Ending Sessions for the supported command and its completeness limits.

Privilege state and operation authority #

A token can have a privilege present but disabled. Enabling a present privilege is different from adding one; permanently removed privileges cannot be re-enabled on that token. Enabled-by-default state is a creation property, and the used bit records exercise rather than a timestamped use history. Consult the privilege model and adjustment rules before interpreting or changing those states.

Some privileges gate kernel operations directly, some contribute rights in AccessCheck, some are interpreted by services, and some names are reserved. A name in a catalog does not prove enforcement by every component. Backup and restore contributions require the relevant intent as well as enabled privileges; the object manager's actual open/update path supplies its own context. PIP, confinement, and central policy can still constrain grants. Removing privileges and adding restricting SIDs are separate reductions.

Diagnosing an Access Refusal

Peios / Using Peios / Identity and Access

A refusal can be the intended policy working. Start with evidence from the failed operation; a token dump or an isolated allow ACE cannot explain every possible access decision.

Gather the actual request #

  1. Record the operation, time, message, and exact error or exit status. Identify the process, failing thread, and managing service where known.
  2. Identify the object and requested rights. Keep a registry key separate from its value name. Distinguish a link from its target and an open from an operation using an already-open handle.
  3. Inspect the relevant effective token with existing authority. Preserve target selectors and the observation time: impersonation can have ended before inspection. Without a target, a tool usually observes itself.
  4. Read the descriptor components available to that caller. Mark unreadable or undisplayed components as unknown, not empty.
  5. Correlate recorded evidence and its collection limits. After a reviewed correction, repeat the original operation in its intended context.

An application can request more rights than its visible action suggests. Capture the exact mask when diagnostics provide it. Rights on an existing handle reflect the earlier open; today's descriptor does not reconstruct that earlier decision.

Choose a supported view #

QuestionRead-only starting pointLimit
Process identitytoken show --pid PID --allPrimary token, not necessarily the failing thread's effective token.
Impersonating threadtoken show --pid PID --tid TID --allConsecutive live queries cannot reconstruct an earlier token.
Present/enabled privilegestoken privs --pid PIDPresence does not prove enablement, intent, or successful use.
Program protectionlogonse psb --pid PIDPSB summary, not the process's security descriptor.
Session contextlogonse list and logonse show IDCan fall back to an incomplete visible-process view.
File descriptor policysd show PATH --allOwner, group, DACL, and label subset; not a complete SACL export.
Registry descriptorreg sd KEY, with --sacl when authorizedDefault output omits SACL policy.
Recorded attemptEvent Viewer or evctlReader rights, collection, query scope, retention, and transport can limit evidence.

For files, sd follows a named symlink unless its documented no-follow option is selected. Inspect the same object the application meant to use. Token pseudo-files provide handles, not text to print with cat. Token inspection and process-security inspection explain their separate access gates.

Rehearse within the tool's limits #

For an identified file and process, a read rehearsal is:

sd check ./report.txt read --pid PID --explain

Adapt the file, rights, and PID to the failed request. This does not perform the file operation. A tool failure is different from a completed denied check. The process selector does not reproduce every thread impersonation, local claim, backup/restore intent, object mapping, or PIP context. It also does not test an existing handle's rights.

An allowed rehearsal is therefore not proof that the application must succeed. If the results differ, compare inputs and timing before changing policy. A developer can use the SDK request reference for inputs the operator tool cannot supply, and its checking guide for the advisory result's limits.

Review the relevant policy #

EvidenceReview
Identification-level impersonation tokenWhether the client conveyed authority and the server was admitted to use it.
Mandatory-integrity refusalToken integrity/mandatory policy, the applicable object label, and requested mapped rights.
Process-trust refusalCalling PSB, target trust label, and intended signed interface; impersonation does not raise PIP.
Missing privilege contributionPresent versus enabled state and required operation intent.
DACL refusalOrdered ACEs, enabled/deny-only SIDs, conditions, inheritance-only flags, and owner-rights suppression.
Restricted-token narrowingThe independent restricting SID view and any retained privilege grants.
Confinement narrowingThe intended confinement identity/capabilities and resource policy.
Central-policy narrowingEffective policy, applicability, resource attributes, and recovery behavior; staged mismatches are separate evidence.

MIC, PIP, privilege contributions, and narrowing occur in a defined pipeline. Do not assume one label mismatch or one matching ACE explains the whole mask. The kernel access-check reference is authoritative for ordering. Object-manager and service checks can also reject an operation outside that pipeline.

Interpret recorded evidence #

kacs.audit.access.checked can record the subject, object, requested and granted masks, and reasons. Auditing depends on policy; userspace checks also have audit-authority requirements. One check can produce several records. A successful MAXIMUM_ALLOWED result does not prove a particular bit was granted. Inspect the returned mask.

Use Finding Missing Records before interpreting an empty search. Raw KMES inspection is a transport probe, not historical proof. Preserve refused inspections, missing inputs, and changed-state uncertainty in the report to the application or policy owner. A narrower intended grant or corrected caller behavior should follow that review; broad permission changes are not a diagnostic substitute.

Interpreting Audit Evidence

Peios / Using Peios / Identity and Access

Use audit evidence to reconstruct a particular operation. Start with its process instance, effective subject, object, requested rights, result, and observation interval. Preserve the original record before translating SIDs or event fields into display names.

Identify the trigger #

TriggerWhat the record establishes
Access audit ACEA matching SACL rule observed an access check and outcome.
Continuous alarm ACEAn operation overlapped the audit mask retained on its handle.
Token object-access policyThe checked token required a success or failure record, even without a matching SACL ACE.
Privilege-use policyA privilege contributed rights, with success or failure determined after the narrowing passes.
Central policy diagnosticA SACL could not be evaluated or staged and effective policy differed.

Audit rules do not grant or deny access. Their success and failure flags select observations. Conditional audit expressions that are UNKNOWN use the conservative audit behavior; ordinary conditional allow rules differ. An inherit-only ACE is a template for children, not an immediate observation rule on the parent.

Continuous records identify the operation-time subject, which can differ from the opener after impersonation or descriptor transfer. Their stored audit mask comes from the open. Changing the object's SACL does not turn every existing handle into a fresh open with the replacement mask.

Preserve the limits of attribution #

The token ID, authentication ID, process GUID, and PID identify different things. Resolve names as annotations; do not replace original SIDs. A process can act with an impersonation token, and a single logon session can contain many tokens. Cross-boot correlation needs boot context.

A userspace AccessCheck record is an advisory check of caller-supplied data, not proof that the kernel opened that object. Its userspace-attestation marker matters. On that syscall path, SACL-generated records require the emitter's enabled audit privilege; token-policy and other event families have separate rules. The kernel audit reference defines these distinctions and the event schemas define the fields. Absent object information must remain unknown.

Do not treat a privilege-use record as proof that removing that privilege would have denied the operation. Backup and restore accounting can record a contribution even where the DACL independently permits access. Maximum-access queries also differ from concrete operation requests.

Check delivery before drawing conclusions #

A required event-construction or delivery failure can fail an audited call; auditing is not universally best-effort. Transport buffering, loss, persistence, retention, and query permissions are separate stages. Neither a successful call nor an empty event query establishes a complete history.

Collect both the event and any loss or ingestion diagnostics for the same interval. Check query scope and retention, and distinguish an inaccessible field from an absent field. Follow the event evidence workflow for collection and the raw event catalog for schema interpretation. A sequence gap alone in a filtered view is not proof of loss.

Inspecting Effective Identity

Peios / Using Peios / Identity and Access

token exposes the identity and authority carried by running processes and threads. It is a diagnostic tool for questions that a user name or numeric group list cannot answer.

Choose the identity being observed #

A process has a primary token. A thread can have an impersonation token that supplies its effective identity. A peer-token query observes identity captured on a connected socket, which is another distinct target.

Reading another process's token requires the appropriate access. Knowing a process number or a socket descriptor does not bypass that check.

Use an explicit selector when diagnosing another program:

token show --pid PID --all
token groups --pid PID
token privs --pid PID
token stats --pid PID
token show --pid PID --tid TID --all

Replace the process and thread IDs with identified targets. The process view selects its primary token; the thread view matters for impersonation. --self is the default, --real selects the caller's primary token, and --peer SOCK_FD selects captured identity on a connected socket. A peer query is not a lookup of whatever identity its process happens to use afterward.

Preserve the selector, time, token ID, and modification ID with observations. Use --json for structured output and the documented raw-SID/label display choices when comparing identities. These queries do not authorize mutation.

Read more than the user name #

Token state includes security identifiers (SIDs), group attributes, privileges, integrity, and logon information. A deny-only group can deny access without granting it, even when its friendly name matches an ordinary membership elsewhere.

The logon-session identifier and the interactive-environment scope are separate fields. Changing a scope is not the same operation as moving a token into a different authenticated logon session.

Field commands also expose integrity, logon context, claims, capabilities, origin/source, and creation defaults. Apply the same target selector to each. A default DACL concerns new objects, not the descriptor of every existing object. show --all means all supported query classes, not every internal field. Absence of an internal field from the output does not establish its value; the kernel's query reference owns that boundary.

Full or Limited elevation type can outlive the active link. token linked queries a counterpart where one exists and is accessible; a role alone is not evidence that elevation is available. The privilege used bit is not a timestamped record of each exercise.

Compare observations carefully #

Token comparison reports selected identity, group, and privilege state. Equal and different comparisons can both succeed: the status indicates whether the queries worked, not whether the tokens matched.

Thread enumeration can race with thread exits or access changes. A failed row makes the result incomplete and is reported rather than silently removed. Multiple queries are consecutive observations, not one atomic snapshot of all token state.

Derived tokens remain controlled objects #

Restriction, duplication, adjustment, and impersonation have different purposes. A restriction limits an existing authority; it does not grant a new one. Creating or installing identity requires the corresponding privilege and is not a normal way to switch users.

token(1) defines target selection, comparison output, thread failures, and the mutation interfaces. Use the normal authentication workflow when your goal is signing in rather than testing a token mechanism.

Refused and partial views #

A cross-process token query needs process-query rights, PIP dominance, and query access to the token. Own-process /proc query-only token paths have a special rule; direct self-open APIs still check the token descriptor. Do not generalize one surface's self-access exception to every operation.

Process walks cannot enumerate all tokens held only by file descriptors. A missing target, denied query, and invalid request are different failures; none is a successfully read empty token. Token pseudo-files are handles, not text files. SDK users should follow the opening reference and query protocol.

Inspecting Process Security

Peios / Using Peios / Identity and Access

Use logonse psb --pid PID to inspect a process's protection, mitigation mask, and Process GUID. Replace PID with the current process number. Omitting mutation options leaves those settings unchanged.

Inspect and correlate #

  1. Identify the current process and its workload. Record its Process GUID when correlating historical events; a PID can be reused.
  2. Read its PSB with logonse psb --pid PID or Task Manager. Limited query access can expose the protection level even when detailed inspection or process control is refused.
  3. Inspect the primary token to identify the process's account and session. Inspect the particular thread's effective token if impersonation matters.
  4. Read the process descriptor using the supported SDK surface when the question is who can act on it. The DACL and SACL have different access requirements; a limited PSB read is not permission to read both.
  5. Correlate current state with stored events. Separate reads can observe different moments and do not constitute an atomic security snapshot.

The kernel's process ABI defines rights and mitigation bits. The PSB reference explains their meaning. Do not infer an exact grant from a token or protection label alone; the target object and requested operation also matter.

Read a refusal accurately #

PSB inspection needs limited query rights and does not require PIP dominance. Detailed inspection and process-control operations have stronger checks. Impersonation changes identity without changing the caller's PIP, and SeDebugPrivilege does not bypass that protection.

A self-targeted PSB read is supported, but that does not mean every operation on one's own process succeeds. Reading the SACL still has its own authority requirement. Missing fields and access errors are not empty permissions.

Changes over time #

PIP follows the executable at exec, so it can change while PID and Process GUID stay the same. Mitigations only become stricter and persist across exec. A thread can install or revert impersonation, and token adjustments or process-descriptor edits can change other inspection results.

Adding --mitigations MASK requests a permanent hardening change. It is not an inspection option or a way to gain control rights. Read logonse(1) and the mitigation reference before using it; failure to activate a requested protection must not be reported as success.

Well-Known SIDs

Peios / Using Peios / Identity and Access

Well-known security identifiers (SIDs) name identities that every Peios system shares, such as Everyone or the Administrators group. They appear in tokens and in permissions on every machine with the same value. This page lists the ones you meet most often. The well-known SID catalog in the Peios Common Data Structures specification is the complete list.

Accounts and groups #

These SIDs identify built-in accounts and groups:

SIDNameIdentifies
S-1-5-18Local System (SYSTEM)The operating system itself, with the highest level of trust
S-1-5-19Local ServiceA built-in account for services that need little authority
S-1-5-20Network ServiceA built-in account for services that authenticate to other machines
S-1-5-32-544AdministratorsThe built-in administrators group
S-1-5-32-545UsersThe built-in group of ordinary accounts
S-1-5-32-546GuestsThe built-in guests group
S-1-5-32-551Backup OperatorsThe built-in group for backup and restore
S-1-5-7AnonymousA caller whose identity isn't known

Broad groups #

These SIDs match many principals at once:

SIDNameMatches
S-1-1-0EveryoneEvery principal, including Anonymous
S-1-5-11Authenticated UsersEvery principal that has authenticated, which excludes Anonymous
S-1-5-4InteractivePrincipals that signed in interactively
S-1-5-14Remote InteractivePrincipals that signed in from another computer; they also carry Interactive
S-1-5-2NetworkPrincipals that authenticated over the network
S-1-5-3BatchPrincipals running a scheduled job
S-1-5-6ServicePrincipals running as a service

Placeholders and patterns #

These SIDs stand in for another identity or follow a pattern:

SIDNameMeaning
S-1-3-0Creator OwnerIn an inherited permission, replaced by the new object's owner
S-1-3-4Owner RightsReplaces the rights an object's owner has automatically
S-1-5-5-X-YLogon SIDOne logon session; see Logon Sessions
S-1-5-80-...Service SIDOne service, written by name as SERVICE\<service-name>
S-1-16-nIntegrity labelAn integrity level; see Integrity Levels
S-1-0-0NobodyNo principal

Object Security Policy

Peios / Using Peios / Permissions

A security descriptor carries an owner, primary group, DACL, and SACL. The object manager supplies the object type and rights mapping; the caller supplies the subject token and request. The descriptor contains neither the object's data nor a live pointer to its parent's permissions.

Read the whole applicable decision #

The DACL's ordered ACEs contribute discretionary grants and denials. The walk decides each right at its first applicable entry; a later deny does not retroactively reverse an earlier allow. Builders should use canonical explicit-before-inherited and deny-before-allow ordering rather than relying on a later sort to repair intent.

An absent DACL has no discretionary restriction; a present, zero-entry DACL contributes no grants. Neither result bypasses the rest of the pipeline. An empty DACL can still coexist with owner or privilege contributions. Do not describe either state as an unconditional whole-system verdict.

The owner normally receives descriptor-read and DACL-edit rights, not automatic file-data access. An applicable Owner Rights ACE suppresses that implicit grant through a pre-scan, even when its conditional expression would not later grant access. Mandatory policy and later narrowing still matter. Ownership change alone neither removes stale ACEs nor establishes a safe recovery route.

PCDS owns the structure; the kernel DACL reference owns evaluation, matching, and maximum-access behavior. A successful MAXIMUM_ALLOWED check still requires inspecting the returned rights mask.

Inherit at creation #

A creator can supply explicit policy, and a parent can contribute inheritable entries. The token's default DACL is a fallback when explicit and inherited sources supply none; it is not always combined with inherited entries. A protected ACL prevents accepting parent entries into that ACL.

Creator Owner and Creator Group placeholders resolve for each created child. A container can receive an effective resolved entry plus an inherit-only unresolved entry for later descendants. Generic rights can require the same two-part treatment. This keeps one creator's concrete SID from becoming the owner policy for every future descendant.

Inheritance does not recompute during access, retroactively update children, or automatically reapply after moving an existing object. An explicit propagation operation is different from changing a parent's descriptor. Copying creates a new object and has its own preservation options. See PCDS inheritance and the SDK inheritance interface.

Conditions and resource attributes #

User, device, resource, and local claims come from different authorities. A resource claim resides in the object's SACL, not in its contents or the caller's token. Attribute names can contain dots without becoming nested objects: @Resource.Project.Code names the attribute Project.Code. Coordinate names and types with the policy owner.

Conditions use three-valued logic. For a deny condition equivalent to Classification == "TopSecret" && not-cleared, a missing classification makes the comparison UNKNOWN. UNKNOWN AND TRUE remains UNKNOWN, so the deny applies to an uncleared subject. UNKNOWN AND FALSE is FALSE, so the same condition does not deny a cleared subject. Missing data does not make every expression UNKNOWN; evaluate the complete expression.

An UNKNOWN allow does not grant. An UNKNOWN deny applies according to the conditional-ACE rule. Review missing and mistyped attributes explicitly, rather than assuming that any absent claim denies everyone or grants nobody through other entries. The conditional-ACE specification defines the operators and truth tables.

The SACL has several jobs #

Audit and continuous-audit ACEs, integrity labels, process-trust labels, central-policy references, and resource attributes share the SACL. Its name does not mean every entry produces an audit record. Access rights for reading or replacing the SACL differ from WRITE_DAC; owner status alone is not sufficient.

The label-only security-information interface affects the mandatory label subset. It does not read or replace audit and central-policy entries. Full SACL replacement and label-only update are different operations with their own checks; do not infer their authority from a partial sd show display. Mandatory resource attributes have additional TCB protection against changes or removal. Use the descriptor-management reference for exact gates.

Preserve an authorized repair route #

Before changing policy, establish who can restore the intended descriptor and what backup actually preserves. A text dump from a partial query cannot reconstruct omitted SACL state. Neither ownership-taking nor a saved string guarantees rollback. Verify actual application access with fresh handles after a change and use access diagnosis when the result differs from intent.

The Permissions Editor

Peios / Using Peios / Permissions

The permissions editor is a shared dialog for security descriptors. A caller identifies the object, supplies the readable descriptor parts and named rights, and applies changes returned by the dialog. The dialog does not gain authority over the object or write its descriptor directly.

Views of one descriptor #

Access & Auditing presents identities, grants, denies, conditions, specific rights, and audit rules. Other views cover resource claims, central access policies, and effective access. Owner, group, integrity, and process trust are available through the owner controls.

Advanced Mode shows the ordered access-list entries, control flags, and text representation. Entries the simpler views cannot edit remain preserved. An unchanged entry is returned with its original bytes. Unsupported text-form entries are represented by retention comments; removing such a comment removes that entry.

The caller's declared capabilities restrict what can be changed. An otherwise valid owner also has to satisfy the kernel's ownership rules. A read-only dialog reports why it cannot apply changes.

Inheritance and existing objects #

Changing a container's inheritable rules governs new children. When the caller supports propagation, the dialog asks whether to update existing children too. The caller performs that operation, reports progress, and handles a stop request. Read the final report of failures; partial propagation is not a completed update of every child.

Claim suggestions #

The dialog suggests claims declared in the machine's Security Descriptor Builder catalog, then claims and values recorded by permitted callers when rules were applied. Suggestions help spelling; they do not create a claim on the caller's token or make a condition true.

See gxwi-sd-editor(1) and the registry manual for Machine\Common\SecurityDescriptorBuilder. Shared descriptor semantics and the dialog protocol remain owned by the Peios specifications.

Inspecting and Editing File Security

Peios / Using Peios / Permissions

sd reads and edits security descriptors on files. A descriptor identifies an owner and holds access, audit, and integrity information. Inspect the relevant components before deciding which change addresses an access problem.

A displayed descriptor is a selected view #

sd show requests the owner, group, discretionary access control list (DACL), and mandatory integrity-label view. It does not request the full system access control list (SACL), which also contains audit rules.

Formatting switches do not widen that selection. The --all spelling does not turn the query into a full export. Human and ordinary JSON summaries also omit some access-control entry payload details.

Do not use sd show --sddl as a complete descriptor backup. It formats the queried subset in security-descriptor definition language (SDDL). Matching two summaries does not establish complete descriptor equality.

Changes depend on the component #

An allow or deny operation appends or replaces selected rules. Removing a principal's rules removes both grants and denials for that principal, so it can broaden access as well as narrow it. Rule order matters when rights are decided.

An access-check simulation helps explain a possible decision without performing the requested operation. It cannot reserve the object's state or guarantee the outcome of a later open.

Ownership, audit rules, and integrity are distinct components with their own access requirements. A change to one does not automatically supply the authority needed to change another.

Inheritance is stored state #

Permitting inheritance lets a descriptor receive inheritable parent rules. It does not create a live link that automatically updates existing children whenever the parent changes. Propagation explicitly refreshes descendants.

Protected descendants retain their own rules. A propagation walk can report individual failures and continue, so inspect the summary rather than assuming the whole tree changed.

Recursive operations treat symbolic links as objects rather than descending through them. A nonrecursive path normally follows the final link unless the physical-link option is selected.

sd(1) owns principal syntax, permission names, component-selection rules, and the exact subcommand interfaces.

Make and verify a bounded change #

Resolve the intended path and decide whether the final symlink or its target is the object to change. Inspect the selected descriptor components and the parent's inheritance before editing. State whether the goal concerns ownership, ordinary access, audit policy, or integrity; avoid replacing unrelated parts.

Choose the smallest supported operation, then read back the affected components and retry the original operation through a fresh handle. A recursive update can partially succeed. Preserve individual failures, and do not treat a matching summary as full descriptor equality or as proof of application-level success.

Use the descriptor API instead of manipulating the sealed xattr directly. Linux mode bits and chmod do not express the complete Peios policy. Missing and corrupt descriptors need the kernel's documented repair contract; granting a broad synthesis template is not a generic repair.

Executable Marks and Access

Peios / Using Peios / Permissions

mkexec marks a regular file as executable. The mark identifies intended executable content; it is separate from the security descriptor that authorizes a process to execute that content.

Two different questions #

A file can have an executable mark while its descriptor denies execution to a particular token. Conversely, an access rule does not identify random data as an intended program. Keep the content decision and the access decision separate.

The mark does not grant privileges, change the user's identity, or create a trusted signature. Inspect a downloaded program and its provenance before making it eligible to execute.

Select the actual file #

mkexec accepts regular files and operates on their executable metadata. It is not a recursive permission editor. Use sd when the intended change is who can access the file, and use the packaging workflow when executable metadata should be reproducible across installations.

mkexec(1) describes accepted operands and errors.

Editing Object Permissions

Peios / Using Peios / Permissions

Open the permissions dialog from the application responsible for the object. That application names its rights and applies the resulting descriptor using the access it already holds.

Before you start #

You need access to read the relevant descriptor parts and to change the parts you intend to edit. Record the existing owner and rules when you need a recovery path. Application-specific rights are meaningful only in that object's context.

Review and apply #

  1. Open Permissions for the intended file, registry key, service, or policy object. Check the object name and type in the dialog.
  2. Inspect the owner and existing rules. Use Advanced Mode when order, conditions, or entries outside the simple view matter.
  3. Make the intended change and select Apply or OK.
  4. If asked about existing children, choose propagation only for the intended scope and review its progress and failures.

Check the result #

Read the caller's apply response. Reopen or refresh the descriptor to inspect what was stored, then test the intended operation with the relevant account. Existing open handles can retain rights granted before the descriptor changed.

An effective-access view explains a calculation from the information it has; it is not a substitute for the consuming component's full operation and runtime policy. Do not remove an unfamiliar advanced entry merely because another view cannot display it.

Changing Default Security Descriptors

Peios / Using Peios / Permissions

A component can accept a security descriptor to apply when creating or preparing an object. Such a setting is policy for that component; it is not a registry feature that rewrites objects automatically.

Before you start #

Find a documented override for the object in the component's registry manual. The proposed Machine\Software\<Software>\SdDefaults convention is not implemented universally. Creating a plausible key does nothing unless the component reads it. In particular, Peinit's static device-node policy uses compiled descriptors; a planned override name in its source is not an active setting.

Read when the component applies the descriptor and how it handles absent or invalid input. Do not assume every descriptor setting has the same fallback: rejection, retaining a prior value, and using a compiled default are distinct policies.

Change and verify the default #

  1. Record the existing override, including whether it is absent, and the actual descriptor on the affected object.
  2. Prepare the component's documented recovery path. Preserve the previous descriptor separately if permission changes need to be undone.
  3. Change only the supported setting, with its documented type and layer.
  4. Use the component's normal creation or preparation workflow. Do not delete a live state file merely to force it to be recreated.
  5. Inspect the resulting object's descriptor and component diagnostics. Test the intended reader and writer identities, not only an administrator.

Valid descriptor syntax does not establish that its grants are appropriate. A fallback after invalid input can also differ from the intended policy.

What does not follow from an override #

Changing the stored default does not automatically update existing objects or descendants that already inherited permissions. Removing the registry layer cannot undo descriptors stamped while that layer's value was effective.

The registry key's own permissions govern who can edit the configuration. A descriptor stored as a value governs the different object whose creator reads it. Review both boundaries; changing Permissions… on the key is not the same operation as editing the stored descriptor.

Bootstrap descriptors, kernel mount-policy templates, and package payload permissions have their own owners and application points. A token's DefaultDacl is another mechanism, supplied by authentication policy. Do not substitute one mechanism for another without the consumer's explicit support.

Capability Policy

Peios / Using Peios / Application Boundaries

A capability SID names an audience for access policy. Its effect depends on where the token carries it, not on its name. A capability called internetClient does not itself intercept network traffic or grant a socket. An enforcing object manager and matching resource policy must exist.

Grants and confinement #

Token fieldEffect of a capability SID
Ordinary groupsParticipates in the normal DACL walk, subject to group attributes.
Confinement capabilitiesParticipates in the additional confinement intersection when that pass is active. Presence matters; disabling a capability does not remove it from that identity.
BothCan satisfy both walks, but does not bypass any other access restriction.

Using capability SIDs in ordinary groups is sometimes called positive confinement. It is an administrative convention for grants, not a sandbox. It does not remove unrelated rights, privileges, or existing handles.

For example, a media library can grant read access to a media-library-read SID. An administrator can arrange for approved service tokens to carry that SID as an enabled group, without listing every service account in every file's DACL. A service given that SID only in its confinement capabilities still needs its ordinary identity to obtain the read grant. An intersection cannot create rights missing from the first walk.

Keep the account, token-creation policy, and object grants distinct. Changing a policy document does not update an already-created token. Verify the launcher's actual token construction rather than assuming an application manifest is automatically interpreted by authd.

Confinement as a second check #

An active confinement pass intersects the existing grant with the rights justified by the confinement SID and capability list. Backup and restore privilege grants do not escape that intersection. Owner implicit rights are not added by the confinement walk. A null DACL still means no discretionary restriction, so confinement is not an unconditional deny-by-default wrapper around every object.

A library file can therefore grant ordinary read access to the service's account and confinement read access to its package SID. The service can read it but cannot change its DACL merely because the account owns it. Granting a capability alone cannot overcome MIC, PIP, central policy, or a denial in the ordinary walk.

Normal confinement includes ALL_APPLICATION_PACKAGES; strict confinement omits it and consequently does not match broad grants to that SID. These are supplied SID sets, not a separate mode flag. Supply every intended capability explicitly. The kernel confinement reference defines virtual groups, conditional expressions, null DACLs, and ordering.

Confinement constrains AccessCheck-mediated operations. It does not remove standalone kernel privileges, isolate namespaces, make inaccessible objects invisible, or retroactively revoke transferred file handles. Treat the reserved isolation-boundary field as unavailable functionality.

Naming and deploying capabilities #

The capability namespace is S-1-15-3-*. Well-known names include network, enterprise authentication, certificate-store, and removable-storage capabilities. Custom names use the defined SHA-256 derivation: eight little-endian 32-bit subauthorities after S-1-15-3. Use the same exact name and derivation on the token and resource sides. The package specification owns the encoding; a recognizable name is not evidence of enforcement.

Before deploying a capability-based service:

  1. Identify each resource and required operation, including startup, maintenance, and recovery paths.
  2. Inspect ordinary groups, privileges, confinement identity, and inherited descriptors independently. A confinement exemption skips that pass.
  3. Arrange explicit grants on the resources and explicit token creation by the launcher. Keep a separate authorized management path.
  4. Test both permitted and refused operations with fresh handles. Test failures without granting broad fallback access.
  5. Recheck a replacement process after policy changes. Record the policy and deployed identities so the result can be reproduced.

Restricted tokens offer a different way to narrow authority inside a program. They can coexist with confinement, but their privilege-restoration rules are different. See restricted tokens.

Process Trust

Peios / Using Peios / Application Boundaries

A process has an identity token, a security descriptor, and a Process Security Block (PSB). They answer different questions:

  • The token identifies the caller and its authority.
  • The target process descriptor controls which operations that caller can request.
  • PIP fields in the PSB describe executable trust. Mitigation fields describe committed process protections.

Impersonation changes the effective token, not the process's PIP tier. An administrator identity does not turn an unsigned debugger into a trusted process, and a trusted service does not acquire every client's authority merely by receiving a request.

Interpreting a refused process operation #

For protected process boundaries, the caller needs the required descriptor right and sufficient PIP dominance. Dominance compares both type and trust; it does not replace the operation-specific descriptor check. SeDebugPrivilege can rescue the descriptor check, but cannot rescue failed dominance. Kernel-mediated service control through Peinit is distinct from directly signaling the service from a shell.

Inspect the target's PSB separately from its token and descriptor. PSB queries have a documented limited-query exception to dominance; that does not imply permission to trace, signal, or open the target's token. A visible PID also does not imply access to its metadata. The kernel reference owns operation mappings, self-operation exceptions, partial multi-target signal success, and the limits of PIP.

PIP is enforced by a trusted kernel. It does not defend against a compromised kernel, unrestricted DMA, or a hostile hypervisor. Protected-process core dumps are disabled in the maintained implementation; do not assume a high-trust crash collector is installed.

Signing and running a binary #

A valid executable signature establishes a tier only if the running kernel trusts its public key. The maintained validator accepts Protected/PeiosTcb entries; adding entries for hypothetical tiers requires an implementation change. A listed key does not prove the complete table passes validation.

Ordinary unsigned binaries can run without a PIP tier. That is different from failure of the verification machinery, which can refuse execution, and from kernel-initiated helpers, which require TCB trust. Executing under a tracer or supervisor can cap a would-be trust increase. Read back the running process's state instead of inferring its tier from a package or filename.

For a script, the final interpreter determines the execution tier. A symlink resolves to the target file. Verified content can be pinned against in-place mutation; pinning is not released merely because the process exits. A failed exec can leave content pinned. Use the deployment's replacement-file workflow for updates rather than assuming signed files remain editable in place.

The verification reference and exec lifecycle define these rules. The signature specification owns the wire format and hashing rules. Detached package signatures are a transport convention, not another kernel runtime lookup path.

Build and release trust #

Keep private signing keys in controlled signing infrastructure. Runtime verification needs public keys and signatures, not private keys. Record the kernel's trusted public-key fingerprints and the signing provenance of the artifacts deployed with it. A development or KUnit key is not release trust.

Package authenticity, executable PIP signatures, module signatures, and firmware verification serve different purposes. Successfully producing a Bazel package does not establish that every required signing step or image composition step occurred. The retired Pekit image recipe is not a supported replacement for the deferred Peios package (PPK) image composer.

The kernel has no runtime signing-key replacement or per-binary revocation service. Key compromise requires a coordinated kernel/key and artifact replacement plan; removing a file alone does not revoke copies elsewhere. Do not promise additional signing tiers or a third-party signing service until their verification and operational support exists.

Boot Authority

Peios / Using Peios / Application Boundaries

The kernel must establish an initial identity before an identity service can run. It constructs SYSTEM and Anonymous bootstrap tokens directly. SYSTEM provides the initial authority; Anonymous represents a minimal identity for anonymous impersonation. They are not accounts loaded from a user database. Their exact fields and lifetime belong to the kernel bootstrap reference.

Prelude runs as PID 1 in the initramfs. It prepares kernel filesystems and runs image-supplied hooks that make the real root available. When it hands off, the same process number executes the real-root init, normally Peinit. The programs perform different jobs; a successful handoff does not establish that every later service or security policy is ready.

Peinit prepares the system's foundational state, starts the registry, then loads and supervises the service graph. SYSTEM platform tokens and authd-issued service identities use separate launch paths. The child receives its intended token before its service executable runs. User sign-in is an authd conversation followed by the requesting session launcher's work, not a universal Peinit sign-in procedure.

Distinct trust decisions #

An initramfs archive is a build artifact, not intrinsically authenticated or immutable runtime memory. Its contents become privileged boot code. Record which image, kernel, hooks, drivers, and signatures are deployed; a successful archive build does not prove firmware Secure Boot enforcement.

The token inherited through early boot gives authority. Executable signing establishes PIP at exec. A SYSTEM identity alone does not prove TCB signing, and signing alone does not give SYSTEM identity. Service management requires both the relevant authority and sufficient process trust.

Policy caches, mount policies, descriptors, and process mitigations are separate responsibilities. Neither authd readiness nor reaching the service graph proves that a CAAP or TLP loader populated kernel policy. The maintained Peinit path does not install those global policies or add a per-service mitigation mask.

Follow a boot failure to its owner #

  • Before real-root handoff, use Prelude's boot diagnosis.
  • For service dependencies, readiness, and recovery, use Peinit boot modes.
  • For identity-source readiness and sign-in failures, use the accounts and sign-in guides. Transport availability does not prove every source loaded.
  • For executable trust, check the kernel verifier and the running process's PSB. Inspect replacement processes separately after a restart.

A privileged recovery shell belongs to the failed stage and its deployment policy. Do not assume every critical service failure opens a sign-in shell or that exiting a failure shell resumes the failed operation.

The Trust Store

Peios / Using Peios / Certificate Trust

trustd supplies the machine's trusted certificate authorities. It combines shipped roots with registry decisions, then publishes the effective set through a local service and compatibility files.

A program with its own private trust store uses separate policy. Changing the machine store does not establish that every application changed its trust decisions.

Seeing what is in force #

trust status reports health, generation, root counts, and compatibility output. trust list reports the effective roots served by trustd.

The generation identifies the published set. Programs holding a snapshot can use it to detect a change. Health is degraded when reading, composition, or compatibility output fails. It is not safe to infer successful publication from the registry alone.

trust list --distrusted reads durable registry decisions. It does not prove that the daemon has applied them. See Adding and Distrusting Certificates for changes and verification.

Who can change it {#who-may-change-it} #

The security descriptors on Machine\System\Trust\Certificates and its subkeys control registry writes. SYSTEM and Administrators have write access under the default policy; everyone can read. The trust command and library use the caller's authority. They do not grant permission to change trust.

Reloading trustd has a separate control permission. A caller can have permission to record a decision without permission to request a reload. The daemon also watches for registry changes.

Where trust policy comes from #

InputLocationUpdated by
Shipped roots/usr/share/ca-certificates/mozilla.crtRoot-store package updates
Additions and distrustsMachine\System\Trust\CertificatesRegistry policy

The package supplies certificates; the registry records decisions about them. A distrust can exclude a shipped root without modifying the package. An addition supplies a certificate that the shipped set does not contain.

A root's fingerprint identifies the certificate. Subject names alone do not distinguish certificates reliably. Purpose metadata records the uses for which an addition is trusted.

What programs actually read #

Native clients use libtrust.so to query or subscribe to /run/trustd/trust.sock. A subscription publishes complete generations. Applications must replace their own cached trust state when appropriate; a notification does not itself invalidate an application's existing sessions.

Compatibility consumers read generated bundles or a hashed directory under /etc/ssl. Those outputs contain roots permitted for ServerAuth. They are derived from policy, so editing them does not make a lasting change. See The Compatibility Trust Files.

Installing a root bundle alone does not compose or render the machine store. Likewise, stopping trustd does not remove an existing rendered bundle or invalidate a program's cached copy.

Failure and recovery #

If a complete configuration read or composition fails, trustd retains its previous effective set and reports degraded health. Missing optional values retain their documented defaults. An incomplete addition without a Certificate value is skipped while it is being created.

Compatibility rendering happens after the effective socket set changes. A rendering failure can leave different consumers using different sets. Inspect the failure and verify both the service and the paths used by the affected application. See When the Store Is Degraded.

Adding and Distrusting Certificates

Peios / Using Peios / Certificate Trust

Add a certificate authority when the machine needs to trust an authority outside the shipped set. Distrust a certificate to exclude it even if a package or local addition supplies it.

Before you start #

  • Install and start trustd and the trust command.
  • Obtain write access to the relevant keys under Machine\System\Trust\Certificates.
  • Verify the intended certificate's fingerprint through a trusted channel.
  • Identify the applications affected by the change and how they obtain trust.

trust(1) owns command syntax. The regman entry for Machine\System\Trust\Certificates owns the registry schema.

In Security Policy #

Use Security Policy's certificate views to inspect effective roots, additions, and distrust decisions. Graphical changes use the same registry permissions as trust. Verify the resulting store and affected applications after using either interface.

Trusting a certificate authority #

  1. Inspect trust status and trust list before making a change.

  2. Obtain the intended certificate as a single PEM or DER file. The following example assumes it is saved as corp-root.pem in the current directory:

    trust add corp-ca corp-root.pem
    
  3. Follow Verify the Change.

The name identifies the local addition. The command rejects an invalid, expired, or non-authority certificate before writing it. trustd validates certificates again when composing the store.

To withdraw this named addition:

trust remove corp-ca

Removing an addition does not create a distrust decision. Another source can still supply the same certificate.

Purposes #

An addition defaults to ServerAuth, used to validate TLS servers. Choose other purposes only when intended. For example:

trust add corp-ca corp-root.pem --purposes ServerAuth,CodeSigning

Socket queries can filter by purpose. Compatibility bundles and hashed files include only roots carrying ServerAuth. Applications using other purposes must request and enforce the appropriate policy themselves.

Distrusting a certificate authority #

  1. Find the intended certificate with trust list and inspect it with trust show. Compare the full SHA-256 fingerprint, not only its subject.
  2. Run trust distrust with that fingerprint or its unambiguous prefix. Use --reason to record why it is being excluded; see trust(1).
  3. Check the durable decision with trust list --distrusted, then verify the effective result below.

A complete fingerprint can record a distrust before the machine has that certificate. A later bundle or addition cannot make it trusted while the distrust remains.

To remove a distrust, use trust restore with its fingerprint. Removing the decision does not supply a certificate that is absent from both the shipped bundle and local additions.

Verify the change #

  1. Run trust status. Resolve degraded health using the procedure below.
  2. Run trust list. For an addition, inspect its complete fingerprint, source, and purposes with trust show.
  3. For a distrust, confirm that the root is absent from the effective set and that trust list --distrusted contains the decision.
  4. Retest the affected application. If it caches trust, refresh that state using the application's documented procedure.

A registry write records intent. A socket query confirms the daemon's set. Neither proves that a running application has discarded a cached root or that compatibility rendering succeeded.

Doing it from the registry #

The trust command uses ordinary registry operations. A domain policy can write the same keys; it does not need a separate trust mechanism.

When creating an addition manually, write Certificate last. trustd skips an entry without that value so that the other metadata can be prepared first. Use the regman schema rather than inferring value types from examples.

Package-provided trust {#packages-may-offer-trust-never-take-it} #

Package-provided trust decisions belong in inert registry seeds. Installing files must not silently widen machine trust. Applying a seed is an explicit image or administrative policy action.

A private application store is separate from the machine store. Its contents and refresh behavior belong to that application's documentation.

When the store is degraded #

  1. Read the error from trust status and preserve the failing operation or path for diagnosis.

  2. Correct the cause. Repair a missing or invalid root bundle through its package. Correct an unreadable registry configuration or unintended distrust decision without restoring an intentionally excluded root.

  3. If rendering failed, inspect the paths the affected application uses. Reported rendered paths can describe an earlier successful render; they are not a fresh inventory after failure. Do not edit generated files.

  4. With trustd's control permission, run:

    trust reload
    trust status
    
  5. Confirm healthy status, verify the intended change, and retest the application.

An authorized reload returns an error if refresh leaves degraded health. The registry decision remains recorded. Service-manager reload uses SIGHUP; its completion does not report the result of recomposition, so inspect trust status afterward.

Skipped invalid certificates are reported separately from degraded health. Read the warnings and correct the named entries before relying on them.

Managing Certificate Trust in Security Policy

Peios / Using Peios / Certificate Trust

Security Policy manages the certificate authorities the machine accepts and its explicit distrust entries. A trust change affects programs that consume that machine policy, so inspect the certificate and its source before accepting it.

Before you start #

You need permission to change Machine\System\Trust. Reloading trustd uses its separate control permission. Obtain the certificate or fingerprint through the verification process appropriate to the authority you trust.

Inspect and change trust #

  1. Open Security Policy and select Trusted or Distrusted.
  2. Inspect the issuer, validity, fingerprint, and trust purpose. To add a certificate, use Add Certificate and select its PEM or DER file.
  3. Review the parsed certificate. The application rejects a non-authority certificate, an expired certificate, and conflicting existing trust or distrust entries.
  4. Confirm only the intended trust, distrust, or removal operation. Read the result.

Check the result #

Verify the certificate in the effective list read from trustd. The window follows changes made through other tools too. A stored entry alone does not establish that every consuming program has refreshed its state.

Settings shows trustd's status, its reload operation, certificate-file export settings, and permissions. Signing Keys displays code-signing keys compiled into the kernel; this window cannot add or remove those keys. See gxwi-security-policy(1) and trust(1).

Understanding Trust Status

Peios / Using Peios / Certificate Trust

trust reads the effective store from trustd and records policy changes in the registry. These are different views: a stored decision can exist before the daemon or an application has applied it. trust(1) owns the command reference, including arguments and exit statuses.

Listing #

trust list shows the effective roots. trust list --distrusted reads durable registry decisions. Compare both when checking a withdrawal.

trust list --purpose ServerAuth filters the service response by purpose. It does not inspect rendered files. Healthy compatibility output uses the same purpose filter, but a failed render can leave older files in place.

Showing one root #

trust show accepts a full fingerprint or unambiguous prefix from the listing. An ambiguous prefix is refused. Inspect the full fingerprint, source, and purposes before making a trust decision.

The --pem option emits only the certificate, suitable for export. Exporting it does not change policy.

Exit statuses #

A command finding no matching root differs from a failed attempt to query trustd. Scripts should check the exit status described in trust(1) rather than treating every empty result as absence.

A successful registry write means the decision was recorded. Verify healthy status and the effective store before treating it as applied. trust reload returns failure when the refresh leaves degraded health.

When a write is refused #

trust has no additional authority to grant. Registry descriptors govern changes, and trustd's control descriptor separately governs reload requests. Have an authorized administrator perform the intended operation.

Editing generated certificate files is not a substitute for changing policy. The next render replaces them, and other consumers can use the service instead of those files.

Reloading through the service manager #

svctl --wait reload trustd sends SIGHUP. trustd processes it in its event loop without replacing the main process. Repeated pending signals can be combined into one refresh.

Inspect trust status afterward. Delivery of a service reload does not prove that reading configuration, composing roots, or rendering files succeeded.

The Compatibility Trust Files

Peios / Using Peios / Certificate Trust

trustd renders certificate files for programs that obtain machine trust from a path. The files are derived output, not configuration. Change trust through the registry or trust; manual edits are replaced on the next render.

Three artifacts, because the ecosystem does not agree #

PathPurpose
/etc/ssl/certs/ca-certificates.crtCertificate bundle
/etc/ssl/cert.pemAlternate bundle path
/etc/ssl/certs/<subject-hash>.0Hashed certificate lookup

Roots with the same subject hash use successive numeric suffixes. Updating only a bundle would leave hashed lookups using stale roots, so trustd rebuilds the certificate directory as well.

Only roots with ServerAuth are rendered. Purpose metadata is not embedded as a substitute for application validation; each consumer still applies its certificate rules.

Publication and failure #

The renderer prepares a replacement certificate directory and attempts an atomic exchange. Where exchange is unavailable, it uses renames with rollback. The fallback can temporarily leave the directory absent. A rollback failure can require repair.

The directory and alternate bundle are separate operations, and the service publishes its effective set before rendering. No single atomic switch covers the socket and every file. A failure can therefore leave consumers observing different generations.

Follow degraded-store recovery and check the actual paths used by the application. A previously reported rendered path is not proof of its contents after a failed refresh.

Turning them off #

Machine\System\Trust GenerateLinuxTrustFiles selects whether trustd supplies compatibility files. Its regman entry owns the value reference.

Turning file output off removes trust inputs from programs that require those paths. Use that mode only when the installed applications use the service or deliberately managed private stores. The socket continues serving.

Removal itself uses several filesystem operations and can fail partway. A stored setting does not prove that all files were removed. Check service health, the relevant paths, and application behavior after changing the mode.

To restore ordinary file output:

reg set Machine/System/Trust GenerateLinuxTrustFiles dword:1
trust reload
trust status

These operations require registry write access and trustd's control right. Confirm healthy status and retest the application.

Why a copy, when name resolution gets a pointer #

A resolver configuration can name a service that answers later requests. A certificate bundle has to contain the authorities itself. It cannot direct a consumer to ask trustd instead, which is why file consumers need a rendered copy and their own refresh behavior.

The effective roots are public, so generated files are readable by ordinary programs. Changing the policy remains protected by registry permissions.

The Certificate Authority

Peios / Using Peios / Certificate Authority

A Peios machine can run its own certificate authority: pkid, a service that issues X.509 certificates for the machines, services, and people on your network, such as a server's TLS certificate or the certificate a phone signs in to Wi-Fi with. If you have run an enterprise certificate authority, the pieces will be familiar: CAs, templates that describe each kind of certificate, and requests that are issued at once or held for an officer.

You manage pkid with the pki command, or with the Certificate Authority window: open Certificate Authority from the launcher, or run pki --window. pkid decides every request by the access token of whoever sent it, so pki and the window can do exactly what you can, and nothing more. The window asks pkid and the Registry what you may change, offers only that, and shows the rest read-only with the reason. Someone who may only request certificates sees the authorities they can request from and their own requests and certificates.

How a certificate is issued #

A certificate starts as a request: a public key and the names it is for, signed with the matching private key to prove the requester holds it. The request names a CA and a template, and pkid checks it in this order:

  1. The CA. The requester needs the Request right in the CA's security descriptor.
  2. The template. The requester needs the Enroll right in the template's descriptor, and the request has to fit the template: the kinds of key and name it allows.
  3. Each name. The requester needs the right to request every name in the certificate, from the name trees.

A request that passes is issued at once, or held for an officer of the CA to approve, when the template or a name asks for approval. A request that fails any check is refused, with the reasons. pkid records every request and decision in its database, with who made it.

The template decides everything else about the certificate: its purposes, key usages, and lifetime. A requester can't change any of it, so the template, not the request, is what an administrator reviews.

CAs #

A CA is a key and a certificate that signs other certificates. Most networks have two tiers:

  • A root signs its own certificate. Every device that is to trust your certificates adds the root's certificate to its trust store once.
  • An issuing CA below the root signs the certificates people and machines use. Its certificate is signed by the root.

Two tiers let you keep the root's key away from the network. pkid keeps a CA's key in one of two places:

  • pkid's store, readable by pkid's service account alone. A CA whose key is here issues unattended, as an issuing CA does.
  • A sealed file, protected by a passphrase, such as on removable media. pkid never keeps such a key open: every operation that signs with it asks for the passphrase. A root's key belongs here, and the media can stay in a drawer until the root next signs something.

A CA can also be signed by a CA elsewhere, or sign a subordinate CA that runs elsewhere, so pkid can fit below or above an existing hierarchy.

Templates #

A template describes one kind of certificate: what it is for, how long it lasts, which keys and names a request can contain, and whether every request waits for approval. A CA issues only from the templates it is given.

pki setup adds two templates:

  • Server, for TLS servers named by host name. Its certificates last 90 days.
  • Device, for client authentication, such as EAP-TLS on Wi-Fi, for devices and people named by user principal name or email address. Its certificates last a year.

Both let any authenticated principal enroll. Enrolling grants nothing by itself: the names decide.

Names #

The name trees decide who can request certificates for which names. There are two trees, one of host names, such as radius.lab.home, and one of principal names, such as alice@home. Each name can have its own security descriptor and its own owner, and names below it inherit its descriptor's inheritable entries, so a grant on lab.home covers every name under it.

Three rights apply to a name:

  • Request issues certificates for the name without approval.
  • Request with approval holds them for an officer.
  • Wildcard also permits the name's wildcard form, such as *.lab.home.

A name's owner is the principal it belongs to, such as the RADIUS server's account for radius.lab.home. The roots of both trees grant Request to PRINCIPAL SELF, which matches a name's owner, so every owner can request its own names, and Administrators can request any. Nobody else can request anything until you grant it. A certificate whose names all belong to one owner carries the owner's SID, so services that accept it for sign-in can match it to the account rather than to a name that only looks the same.

Rights on a CA #

Each CA's descriptor grants four rights:

  • Read shows every request and certificate. Without it, a caller sees only its own.
  • Request lets a caller submit requests.
  • Officer approves and denies held requests and revokes certificates. An officer can never approve a request it submitted itself.
  • Manage changes the CA, signs subordinate CAs, and exports its key.

By default, Authenticated Users can request, and Administrators and SYSTEM hold every right. pkid(8) describes each right and descriptor.

Who can create and import CAs is a descriptor of its own, which grants Manage to Administrators and SYSTEM by default. pki ca creators shows and sets it, as does Who Can Add Authorities on the Certificate Authority window's overview.

Revocation #

A certificate can be revoked before it expires, such as when its key is exposed. Each CA publishes a certificate revocation list (CRL) of what it has revoked, which pki-httpd serves over HTTP at an address written into every certificate the CA issues, so that software checking a certificate can find out. pkid renews the list of a CA whose key it keeps; an offline root's list is renewed by hand, with its passphrase. Publishing Revocation Lists explains how.

Where it is kept #

The configuration, the templates, names, and CAs, is in the Registry under Machine\Software\Pki, which regman documents value by value. pkid takes a change up as soon as it is written, but only as a whole: while any part of the configuration is invalid, pkid issues nothing and says why in its pkid.configuration.loaded event. pki checks each change by the same rules before it writes it.

Requests, certificates, and revocations are in pkid's database. pki(8) documents every command, and pkid(8) the service.

Setting Up a Certificate Authority

Peios / Using Peios / Certificate Authority

Set up a certificate authority when the machines and people on your network need certificates you issue yourself. When you finish, you have a root CA whose key is kept off the machine and an issuing CA that issues server and device certificates unattended.

Before you start #

  • Sign in as a member of Administrators.
  • Make sure the pki package is installed. It doesn't start pkid or pki-httpd: they start once you set the machine up.
  • Have removable media mounted for the root's key, such as /media/usb.
  • Choose a passphrase of at least 15 characters for the root's key, and somewhere safe to keep it. Without the passphrase, the root can never sign again.

Prepare the machine #

Run pki setup once:

pki setup

It creates pkid's state directories under /var/state/pki and adds the default configuration under Machine\Software\Pki: the Server and Device templates and the roots of the name trees. Then it has pkid, and pki-httpd, which publishes revocation lists, start at boot, and starts them. It only adds what is missing, so running it again changes nothing you have set.

In the Certificate Authority window, the overview offers Set Up to an administrator until the machine is prepared.

Create the root #

  1. Create the root, with its key sealed in a file on the removable media:

    pki ca create "Home Root" --root --key-file /media/usb/home-root.key \
      --crl http://pki.home/crl/home-root.crl
    

    pki asks for the key's passphrase twice. pkid makes the key and the root's certificate, an RSA-4096 one that lasts 10 years. --crl is the address where the root's revocation list will be published, and goes into the certificates the root signs; see Publishing Revocation Lists.

  2. Publish the root's first revocation list while its key is to hand:

    pki ca publish-crl "Home Root"
    
  3. Write the root's certificate to a file, to give to the devices that are to trust it:

    pki ca show "Home Root" --out home-root.pem
    

Create the issuing CA #

  1. Create the issuing CA, signed by the root, issuing from both templates:

    pki ca create "Home Issuing" --issuer "Home Root" \
      --template Server --template Device \
      --crl http://pki.home/crl/home-issuing.crl
    

    pki asks for the root key's passphrase, since the root signs the new CA's certificate. The issuing CA's key goes in pkid's store, so it issues without a passphrase, and its certificate lasts 5 years. pkid publishes its revocation lists itself.

  2. Unmount the removable media and store it safely. The root is needed again to sign another CA, and to renew its revocation list, which lasts 180 days.

Check the result #

List the CAs:

pki ca list

Both CAs are listed, each with the state issuing. pki ca show "Home Issuing" shows the issuing CA in full, including the templates it issues from and its certificate's SHA-256 fingerprint.

Distribute the root #

Every device that is to trust your certificates needs home-root.pem in its trust store. Check its SHA-256 fingerprint against pki ca show "Home Root" when you install it. On a Peios machine, add it as described in Adding and Distrusting Certificates.

Keep a copy of the issuing CA's key #

A key in pkid's store can't leave it unless the CA was created with --exportable. To be able to restore the issuing CA on another machine, add --exportable when you create it, then export its key, sealed under a new passphrase:

pki ca export-key "Home Issuing" home-issuing.key

pki ca import restores it from the file and the CA's certificate.

Have a CA elsewhere sign your CA #

If your network already has a CA, make pkid's CA its subordinate instead of a root. --offline writes a request for that CA to sign:

pki ca create "Home Issuing" --offline home-issuing.csr

Once the other CA has signed it, install the certificate it returns:

pki ca install "Home Issuing" home-issuing.pem

The CA issues nothing until its certificate is installed.

Use the Certificate Authority window #

Add an Authority in the window's sidebar makes each kind of CA these steps make: a Root Authority, one Under an Authority Here, one Signed by an Authority Elsewhere, or one imported from a backup with Import From a Backup. Its Key Storage is the Certificate Service's store, or a Sealed File with a passphrase. A CA's page has Export Key, Sign a Subordinate Request, and, while it waits for its certificate, Save Request… and Install Certificate…. Only someone with the right to create CAs sees Add an Authority.

Controlling Who Can Request Certificates

Peios / Using Peios / Certificate Authority

Change who can request certificates when the defaults don't fit: a server that is to request its own certificate, a group that is to request names under a domain, or a kind of certificate that needs an officer's approval.

By default, a name's owner can request certificates for it, Administrators can request any name, and nobody else can request anything.

Before you start #

  • Sign in as a member of Administrators. The name and template commands write the Registry under Machine\Software\Pki, which only Administrators can change.
  • Run pki setup first, as described in Setting Up a Certificate Authority.

Let a principal request its own name #

Make the principal the name's owner, by its SID:

pki name set-owner radius.lab.home S-1-5-21-1-2-3-1105

The roots of the name trees grant Request to PRINCIPAL SELF, which matches a name's owner, so the owner can now request certificates for radius.lab.home without approval. Ownership covers exactly that name, not the names below it, and certificates for the name carry the owner's SID.

Never make a broad group, such as Users, an owner: every member could then request certificates for the name. pki warns if you do.

Let every account request its own principal name #

Rather than set an owner for each person's principal name, let the accounts on this machine own theirs. List the domains this machine speaks for:

pki name domains --set home

Now alice@home, with no owner of its own, belongs to the account alice: Alice can request certificates for it, such as for signing in to Wi-Fi, and they carry her account's SID. Nobody else can request it, as PRINCIPAL SELF matches only its owner. Only the account's name is used, which only an administrator can change, and a domain not listed is never looked up, so list only your own. An owner you set with set-owner still wins.

Let a group request names under a domain #

Give lab.home a descriptor that grants the group Request with approval (0x2), marked to inherit (CI) so it covers every name below:

pki name set-security lab.home "D:(A;CI;0x2;;;AU)"

Here AU is Authenticated Users. Their requests for names under lab.home now wait for an officer of the CA. pki adds the entries lab.home inherits from above, so Administrators and owners keep the rights the root gave them.

A tree's root, . or @, inherits nothing, so its descriptor replaces the shipped one whole. pki warns if a new root descriptor leaves Administrators unable to request the names in the tree, or owners unable to request their own.

Prefer Request with approval for groups. Request (0x1) issues without anyone looking, so granting it to a broad group lets every member obtain certificates for those names; pki warns when you grant it. Wildcard (0x4) also permits names such as *.lab.home.

To undo the change and let lab.home inherit again:

pki name set-security lab.home --inherit

Hold every certificate of a kind for approval #

Set a template's issuance to approval, and every request under it waits for an officer, whatever the names allow:

pki template set Server --issuance approval

Add a kind of certificate #

Create a template from a copy of another and change what differs, such as a server template whose certificates last 30 days:

pki template create "Short Server" --from Server --lifetime 30 \
  --renewal-window 10

pki refuses a template pkid wouldn't load, such as one whose renewal window isn't shorter than its lifetime. Then let a CA issue from it. --template replaces the CA's list, so give every template it is to keep:

pki ca set "Home Issuing" --template Server --template Device \
  --template "Short Server"

A template's enrollment descriptor decides who can use it at all; --enroll-security changes it.

Use the Certificate Authority window #

The window's Templates and Names pages make the same changes. Who Can Request opens the permissions editor on a template's or a name's descriptor; for a name, it shows the entries it inherits from the name above it. A name's page sets its Owner, by account name, and Inherit Again… drops its own permissions. Principal Domains is at the top of Names. Each control appears only where your permissions in the Registry let you change it.

Check the result #

Show a name to see its owner, its descriptor, and where the descriptor comes from:

pki name show www.lab.home

www.lab.home has no settings of its own, so its descriptor is inherited from lab.home. pki name list lists the names with settings of their own, and pki template show Server shows a template and the CAs that issue from it.

Requesting a Certificate

Peios / Using Peios / Certificate Authority

Request a certificate when a server, a service, or a device needs one from your CA. You can send a request that other software made, or have pki make the key and package the result for a device to import.

Before you start #

  • Find the CA's name and the template to use. pki ca list lists the CAs you have rights at, and pki ca show lists the templates a CA issues from.
  • Make sure you can request the names the certificate is to carry, as described in Controlling Who Can Request Certificates.

Certify a request you made #

Software that keeps its own key, such as a web server, makes the request itself, in PEM or DER. Submit it under a template the CA offers:

pki request submit "Home Issuing" Server www.csr --out www.pem

If the CA issues the certificate, pki writes it to www.pem. If the request is held for approval, pki prints its number instead. Once an officer approves it, collect the certificate:

pki cert get "Home Issuing" 42 --out www.pem

Make a key and certificate for a device #

Phones, laptops, and other devices import a key and its certificates as one PKCS #12 file. pki enroll makes the key on this machine, asks the CA to certify it, and writes the file:

pki enroll "Home Issuing" Device --upn alice@home --out alice.p12

pki asks for a passphrase of at least 15 characters, which protects the file and is asked for again when it is imported. pkid sees only the request, never the key. The file holds the key, the certificate, and the CA certificates above it that you can see on this pkid, so a device that imports it can present the chain.

Name the certificate with --dns for a host name, --email for an email address, or --upn for a user principal name, which EAP-TLS sign-in to Wi-Fi uses. Each can be repeated.

The file is encrypted with AES-256, as OpenSSL 3 writes by default, and OpenSSL 3 imports it. Apple systems older than iOS 18 and macOS 15 are reported to refuse it.

When the request is held #

The key exists nowhere but on this machine, so a held request can't lose it: pki seals the key under the same passphrase in a file beside the one it would have written, here alice.p12.key, and prints the command that finishes the job. Once an officer approves request 42, run:

pki enroll "Home Issuing" --request 42 --key alice.p12.key --out alice.p12

Delete alice.p12.key once the device has imported the file.

Request a certificate with the Certificate Authority window #

  1. Open Certificate Authority from the launcher, and choose Request a Certificate in the sidebar.
  2. Choose the Authority and the Template. Only those you may request from are offered.
  3. Type the names the certificate is for, separated by commas.
  4. Leave Key set to Make a Key Here to have the window make the key and save it with its certificates as a PKCS #12 file. Choose Save To and a Password of at least 15 characters. To certify a request other software made, set Key to Use My Own Request and choose the request file instead.
  5. Choose Request Certificate.

If the request is held for approval, the window keeps the key sealed beside the file and remembers the request. Once an officer approves it, the overview says the certificate is ready: open the request, choose Save…, and type the file's password.

Check the result #

List the CA's certificates:

pki cert list "Home Issuing"

The new certificate is listed with the state valid, its serial number, and when it expires. pki cert show with the serial number shows it in full.

Approving and Revoking Certificates

Peios / Using Peios / Certificate Authority

Approve and revoke certificates when a CA holds requests for an officer, or when a certificate's key is lost or its holder leaves. These are an officer's tasks: they need the Officer right in the CA's descriptor, which Administrators hold by default.

Before you start #

  • Sign in as an officer of the CA.

pki ca show "Home Issuing" lists your rights at the CA under Your access.

Make someone an officer #

Officers are named in the CA's descriptor. Someone with Manage CA at the CA can change it. To let the group Lab Officers approve and revoke, while everyone signed in can still request and Administrators keep every right:

pki ca set-security "Home Issuing" "D:(A;;0x2;;;AU)(A;;0x5;;;S-1-5-21-1-2-3-1105)(A;;0xf;;;BA)(A;;0xf;;;SY)"

In the Certificate Authority window, open the CA's page and choose Edit… under Permissions, which opens the permissions editor with these rights by name.

The descriptor replaces the one the CA had, so include every grant it should keep. Grant 0x4 (Issue and Manage Certificates) and 0x8 (Manage CA) only to people you trust to issue any certificate. pki warns you if the descriptor lets a broad group approve or manage, or leaves you without Manage CA. pki(8) lists the rights.

Approve or deny held requests #

  1. List the requests waiting for an officer:

    pki request list "Home Issuing" --status pending
    

    Each is listed with its number, template, when it was submitted, and the names it asks for.

  2. Look at a request in full, including who submitted it and why it was held:

    pki request show "Home Issuing" 42
    
  3. Approve it, which issues the certificate:

    pki request approve "Home Issuing" 42
    

    Or deny it, recording why:

    pki request deny "Home Issuing" 42 --reason "not a lab machine"
    

You can't approve a request you submitted yourself; another officer has to. pkid checks an approved request again as its requester, so approving it issues only what the requester was allowed to ask for, whatever the officer's own rights.

The requester then collects the certificate, as described in Requesting a Certificate.

With the Certificate Authority window #

Open Requests. Requests waiting for an officer are listed first, each with Approve and Details. Deny… on a request's page asks for an optional reason. The window shows your own requests without these, with why: another officer has to decide them.

Revoke a certificate #

  1. Find the certificate's serial number:

    pki cert list "Home Issuing"
    
  2. Revoke it, with the reason, such as key-compromise for a key that was exposed or superseded for one that was replaced:

    pki cert revoke "Home Issuing" 4f1a09 --reason key-compromise
    

A revocation can't be undone. pkid records it with its reason, the time, and the officer who made it. pki(8) lists every reason.

In the Certificate Authority window, open the certificate from Certificates and choose Revoke…, then the reason.

Software learns of the revocation from the CA's revocation list. pkid publishes a new list at once for a CA whose key it keeps. For a CA whose key is in a sealed file, pki reminds you to publish one with pki ca publish-crl, as described in Publishing Revocation Lists.

Check the result #

Show the certificate:

pki cert show "Home Issuing" 4f1a09

Its state is revoked, with when, why, and by whom. A request you approved or denied leaves the list that pki request list "Home Issuing" --status pending prints.

Publishing Revocation Lists

Peios / Using Peios / Certificate Authority

Publish revocation lists so that software checking a certificate can find out whether it was revoked. Each CA signs a certificate revocation list (CRL) naming the certificates it has revoked, and pki-httpd serves it over HTTP at the address the CA writes into every certificate it issues.

A revocation has no effect on software that never fetches the list, and software that does fetch it rejects every certificate below a CA whose list has expired. So a CA needs both an address that will keep working and a list that is kept current.

Before you start #

  • Sign in as a member of Administrators.
  • Choose a host name for the address that will outlive this machine, such as pki.home, and make it resolve to this machine. The address is written into each certificate when it is issued, so changing it later leaves every certificate already issued pointing at the old one.
  • Make sure the pkid and pki-httpd services are installed, and run pki setup, which reserves TCP port 80 for pki-httpd.

Give each CA an address #

  1. Give a CA its address when you create it, with --crl:

    pki ca create "Home Root" --root --key-file /media/usb/home-root.key \
      --crl http://pki.home/crl/home-root.crl
    pki ca create "Home Issuing" --issuer "Home Root" \
      --template Server --template Device \
      --crl http://pki.home/crl/home-issuing.crl
    

    The root's address goes into the certificates the root signs, so the issuing CA's certificate carries it, and the issuing CA's address goes into the certificates it issues.

  2. For a CA that exists already, set its address with ca set. Only certificates issued afterward carry it:

    pki ca set "Home Issuing" --crl http://pki.home/crl/home-issuing.crl
    

pki-httpd serves each list at the path of its address, so http://pki.home/crl/home-issuing.crl is served as /crl/home-issuing.crl. Use letters, digits, ., -, _, and ~ in each part of the path.

Keep each list current #

A CA whose key pkid keeps, such as the issuing CA, looks after its own list: pkid signs a new one after every revocation and at half each list's lifetime, which is 7 days unless you change it.

A CA whose key is in a sealed file, such as an offline root, can sign only with its passphrase, so you renew its list by hand. Its lists last 180 days.

  1. Mount the media holding the root's key.

  2. Sign and publish a new list:

    pki ca publish-crl "Home Root"
    

    pki asks for the root key's passphrase.

Do this after the root revokes anything, and well before its list expires: pki ca list flags a list that expires within 30 days, and pkid emits a pkid.crl.expiring event each day until it is renewed.

To change how long a CA's lists last:

pki ca set "Home Root" --crl-lifetime 365

In the Certificate Authority window, a CA's page shows its latest list and when it expires, and Publish Now signs a new one, asking for the key's passphrase if it is sealed. The overview lists each list that is due or has expired.

Check the result #

List the CAs and when their lists expire:

pki ca list

Then fetch a list from another machine, such as with curl, and check it names the CA:

curl -o home-issuing.crl http://pki.home/crl/home-issuing.crl
openssl crl -inform DER -in home-issuing.crl -noout -issuer -nextupdate

Serve on another port #

If another service already serves port 80, pki setup warns that the port is reserved for it. Choose another port for pki-httpd, such as 8080, and reserve it:

pki setup --http-port 8080

Restart pki-httpd, and give each CA an address with that port, such as http://pki.home:8080/crl/home-issuing.crl. In the Certificate Authority window, change Revocation List Port on the overview, which restarts pki-httpd for you. pki-httpd(8) describes the service.

How Crypto Policy Works

Peios / Using Peios / Crypto Policy

Peios applies one crypto policy to every program on the machine that uses libpcrypto or libpssl, its libraries with OpenSSL's API. The policy decides which algorithms a program can use, records the use of weak ones, and lets named programs keep using an algorithm that they need and that the policy would otherwise refuse.

The policy is configured under Machine\System\Cryptography. cryptod, the crypto policy service, publishes it as a file that the libraries read, and records what programs report of their weak cryptography.

Grades #

Each use of cryptography is graded as an entry: an algorithm and the operation it's used for, such as md5.hmac for HMAC-MD5 or md5.digest for an MD5 digest. The same algorithm can have different grades for different operations. MD5 is broken as a digest, but HMAC-MD5 has no practical attack.

Grades run from U to A:

GradeMeaning
UPractically broken, or forbidden by current standards
DNo practical break, but under 112-bit security or deprecated
C112-bit security
B128-bit security
A192-bit security or more

Separately, each entry records whether FIPS 140-3 approves it. FIPS approval isn't a grade: FIPS approves some entries below A, such as HMAC-SHA-1, and doesn't approve some A-grade ones.

/usr/share/peios-crypto/algorithms.tsv lists every entry, with its grade and whether FIPS approves it.

A few entries are on the floor: they're refused under every policy, and no exception can allow them. The floor holds ciphers and TLS suites that encrypt nothing, the 40-bit export-grade RC2 cipher, RSA keys and Diffie-Hellman parameters under 1024 bits, and ECDSA signing with a fixed nonce, which gives away the private key.

Thresholds #

The policy has two thresholds:

  • Reject: entries below this grade are refused. By default it's U, so only the floor is refused.
  • Warn: entries below this grade are allowed, but their use is recorded. By default it's C, so the use of anything graded U or D is recorded.

Each can also apply to every entry FIPS doesn't approve, whatever its grade. Turning that on for Reject doesn't make the machine operate in a FIPS-approved mode, because the libraries' module isn't validated.

A refused call fails as if the algorithm weren't supported. A few low-level functions can't report failure, such as SHA256 and MD5_Init, so a program that calls one for a refused entry ends. Before raising the Reject threshold, find out what would stop working: see Configuring Crypto Policy.

Exceptions #

An exception lets particular programs use particular entries: a RADIUS server that must use HMAC-MD5 because the protocol requires it, for example. Each exception is a key under Machine\System\Cryptography\Exceptions, named Owner.Purpose, such as Radius.PacketAuth. It names the entries it allows, and has a security descriptor, ProgramSecurity, granting the programs that can use it.

Packages add the exceptions their software needs when they install, and remove them when they uninstall.

Important

An exception applies to a program, not to whoever it's acting for. ProgramSecurity is checked against each process's primary token, the identity the program runs as. Impersonation is ignored. This is unusual on Peios, where access is normally decided by whose behalf a thread is acting on.

An exception answers "which software needs this algorithm". If it followed impersonation, a service would lose its exception while it served a client, and a client could weaken a service's cryptography.

Grant a service's own SID, S-1-5-80-..., to except one service. A user or group SID is accepted, but it excepts every program that runs as that user or group, including ones that don't need the algorithm.

An exception allows an entry the Reject threshold refuses only while Exceptions\AllowExceptionsToReject is 1, its default. When it's 0, exceptions only stop warnings. An exception never allows an entry on the floor.

When changes apply #

cryptod publishes the policy when it starts, and again a moment after Machine\System\Cryptography changes. Each process reads the policy once, at its first use of the libraries, and keeps it for as long as it runs.

So a change applies to processes started after it's published. A service that's already running keeps the policy it started with until it's restarted. Exceptions work the same way, so a service doesn't lose one partway through a request.

cryptod also keeps a copy of the policy that survives a reboot. A process that starts before cryptod reads that copy. A process uses Peios's built-in defaults only on a machine where cryptod has never run, or if it can't use either copy.

What's recorded #

The libraries report to cryptod, and cryptod records each report as an event:

  • cryptod.algorithm.warned: a process's first use of each entry below the Warn threshold.
  • cryptod.exception.used: a process's first use of each exception, whether or not the exception warns. An audit can always find the weak cryptography in use.
  • cryptod.policy.failed: a policy cryptod couldn't publish as written, or one a process couldn't use.
  • cryptod.policy.applied: each policy cryptod publishes.

Each process reports each use once, so the records show which programs use what without one for every call. A process is named by the identity and process ID the kernel recorded when it connected to cryptod.

cryptod also keeps a summary of what's been used, and by whom, since it started. See the cryptod reference.

When something is wrong #

cryptod checks the policy when it publishes it:

  • If a setting such as a threshold can't be read, cryptod keeps the policy it last published, and records cryptod.policy.failed. Falling back to defaults could loosen a policy an administrator had tightened.
  • If an exception can't apply as written, cryptod drops that exception alone, so it allows nothing, publishes the rest, and records why. A misspelled entry, such as md5.hmca, is the usual cause.

A process uses a copy of the policy only if SYSTEM or cryptod owns it and nobody else can change it. Otherwise it uses the next copy, or the defaults, and reports it.

Limits #

  • A process that starts before cryptod is listening can't report, so its first uses aren't recorded. It still applies the policy.
  • A report is attributed to the identity of the reporting thread when it connected. A thread that was impersonating a user then is recorded as that user. The process ID still identifies the process.
  • A process that replaces its primary token keeps the exceptions of the token it started with.
  • Policy is applied to programs that use libpcrypto and libpssl. A program with cryptography of its own, or a statically linked copy of another library, is outside it.

Configuring Crypto Policy

Peios / Using Peios / Crypto Policy

Tighten the crypto policy in steps: find what would stop working, give the services that need a weak algorithm an exception, then raise the threshold. Check the result after each change.

The regman entry for Machine\System\Cryptography owns the complete configuration reference. evman cryptod describes the records cryptod writes.

Before you start #

  • Check that cryptod is running: svctl status cryptod.
  • Obtain write access to Machine\System\Cryptography. SYSTEM and Administrators have it.
  • Obtain read access to cryptod's events in eventd.
  • Allow time for the machine to run its normal workload under the current policy, so that the records show everything it uses.

Find the weak cryptography in use #

  1. List the programs that used an entry below the Warn threshold:

    evctl 'EVENTS cryptod.algorithm.warned SINCE 7d ago'
    

    Each record names the entry, its grade, and the process that used it.

  2. List the uses of a grade that a new threshold would refuse. For example, before refusing everything below C:

    evctl 'EVENTS cryptod.algorithm.warned SINCE 7d ago WHERE object.crypto-algorithm.grade == "U"'
    evctl 'EVENTS cryptod.algorithm.warned SINCE 7d ago WHERE object.crypto-algorithm.grade == "D"'
    
  3. List the exceptions in use, and by which programs:

    evctl 'EVENTS cryptod.exception.used SINCE 7d ago'
    

Every program in these results would fail to use its entry under the new threshold, unless it has an exception. A program that calls a low-level digest function, such as SHA256 or MD5_Init, for a refused entry ends.

Let a service keep an algorithm #

Give an exception to a service that must keep using an entry, such as a RADIUS server that needs HMAC-MD5. Grant it to the service's own SID, so that no other program gets it.

  1. Find the service's SID. Read its main process ID from svctl status <service>, then list that process's token groups:

    token groups --pid <pid>
    

    The service SID is the group that begins S-1-5-80-.

  2. Create the exception, named for its owner and purpose. This one allows HMAC-MD5 for one service:

    reg set -p Machine/System/Cryptography/Exceptions/Example.LegacyRadius \
        Algorithms multi:md5.hmac
    reg set Machine/System/Cryptography/Exceptions/Example.LegacyRadius \
        ProgramSecurity 'sz:O:SYG:SYD:(A;;0x1;;;S-1-5-80-<service SID>)'
    

    Name each entry as an algorithm and an operation. md5.hmac doesn't allow md5.digest. The descriptor needs an owner, O:SY here, as an access check refuses one without, and a DACL granting the Use right, 0x1.

  3. Check that cryptod published it, and didn't drop it:

    evctl 'EVENTS cryptod.policy.* SINCE 10m ago'
    

    A cryptod.policy.failed record naming the exception says why it was dropped. A dropped exception allows nothing.

  4. Restart the service, so that it reads the new policy:

    svctl restart <service>
    

Raise the reject threshold #

  1. Set the lowest grade the policy allows. This refuses everything graded U or D:

    reg set Machine/System/Cryptography/Reject MinimumGrade sz:C
    
  2. Check that cryptod published the policy, as above. If a cryptod.policy.failed record says a setting is invalid, cryptod kept the previous policy: correct the value and check again.

  3. Restart the services that should take up the new policy. Processes started from now on use it; running ones keep the policy they started with.

To refuse everything FIPS 140-3 doesn't approve, whatever its grade, set Reject\FIPS to 1:

reg set Machine/System/Cryptography/Reject FIPS dword:1

Check the result #

Watch for refusals and new warnings after the change:

evctl 'EVENTS cryptod.* SINCE 1h ago'

A program refused an algorithm reports an error from its own calls, such as a failed TLS handshake with an insufficient_security alert. If a service stops working, give it an exception or lower the threshold, then restart it.

To undo a change, set the value back, or delete it to return to Peios's default, then restart the affected services:

reg del Machine/System/Cryptography/Reject MinimumGrade

cryptod Reference

Peios / Using Peios / Crypto Policy

cryptod compiles Machine\System\Cryptography into the policy file that libpcrypto reads, and records what processes report of their weak cryptography. Its configuration is documented by regman, and its records by evman.

Service #

PropertyValue
Servicecryptod
Program/usr/sbin/cryptod
IdentityService: its own SID, S-1-5-80-2691053820-547492864-353945177-641201782-1210658655
PrivilegesSeChangeNotifyPrivilege, SeAuditPrivilege
ReadinessNotify, once it has published the policy and is listening
Event rootcryptod

cryptod must run as its own service SID. Processes trust a policy copy only if SYSTEM or that SID owns it, and a file cryptod writes is owned by its token's user.

Files and sockets #

PathWhat it is
/run/cryptod/policyThe current policy
/var/state/cryptod/policyThe policy kept across reboots, for processes that start before cryptod
/run/cryptod/reportWhere processes report, a SOCK_SEQPACKET socket everyone can connect to
/run/cryptod/postureWhere the posture is served, a SOCK_STREAM socket for SYSTEM and Administrators
/usr/share/peios-crypto/algorithms.tsvEvery graded entry, which cryptod checks policies against

A process reads /run/cryptod/policy, then /var/state/cryptod/policy, then uses Peios's defaults: refuse only the floor, warn below C, FIPS ignored, exceptions allowed to override refusal. It moves to the next if a copy is absent or can't be used, and reports why.

cryptod writes each copy whole: to a new file beside it, which it gives the copy's descriptor, then renames over the copy. Each copy's descriptor is protected, grants full access to SYSTEM and cryptod, and grants reading to Everyone, S-1-15-2-1 and S-1-15-2-2, so that confined applications can read it too. Both directories grant the same readers traversal.

algorithms.tsv has one line per entry: its identifier, its grade or floor, and 1 or 0 for whether FIPS 140-3 approves it, separated by tabs. cryptod doesn't start without it.

Trusting a copy #

A process uses a copy only if its descriptor shows that nobody but SYSTEM and cryptod could have written it:

  • Its owner is SYSTEM or cryptod's SID.
  • It has a DACL. A copy with none lets everyone change it.
  • No entry of the DACL grants anyone else a right that could change the file: writing or appending data, writing extended attributes or attributes, deleting it, changing its descriptor or owner, or a generic or maximum-allowed right that includes them. Entries that deny, and entries that only pass to children, are ignored.

The check fails closed. A descriptor over 4 KiB, or an entry granting CREATOR OWNER a right to change the file, is refused as insecure, even where it would be harmless. A process that refuses a copy reports copy-insecure.

The policy file #

The file is version 1 of a binary format, at most 1 MiB less one byte. Integers are big-endian. A process reads the whole file before using any of it, and refuses a file of another version.

FieldSizeMeaning
Magic8 bytesPEIOSCPL
Version21
Reject below1A grade: 0 for U, then 1 to 4 for D to A
Warn below1A grade, as above
Flags10x01 reject non-FIPS, 0x02 warn non-FIPS, 0x04 exceptions can override refusal
Exception count2The number of exceptions that follow

Each exception follows in turn:

FieldSizeMeaning
Name1-byte length, then the nameOwner.Purpose
Flags10x01 warn about its use
ProgramSecurity2-byte length, then the descriptorA self-relative security descriptor
Entry count2The number of entries that follow
Entrieseach a 1-byte length, then the identifierSuch as md5.hmac

cryptod resolves Exceptions\Enabled, WarnByDefault and WarnAlways as it compiles, so the file holds only what applies. It leaves out exceptions it dropped. A process ignores an entry it doesn't grade, and any entry on the floor.

Reports #

A process connects to /run/cryptod/report, sends one datagram, and closes. It doesn't wait, and doesn't retry: a report that can't be sent is lost. A datagram has four fields:

FieldSizeMeaning
Kind11 warned, 2 exception used, 3 policy copy unusable
Problem1For kind 3, why; otherwise 0
Entry1-byte length, then the identifierFor kinds 1 and 2; otherwise empty
Exception1-byte length, then the nameFor kind 2; otherwise empty

The problems are 1 unreadable, 2 insecure, 3 malformed, 4 an unknown version, and 5 the process's token unreadable.

cryptod takes the sender's identity from the connection: the user of the token the kernel captured at connect, and the process ID. Nothing in the datagram names the sender. cryptod discards a datagram that libpcrypto couldn't have sent, such as one naming an entry it doesn't grade.

Rates #

cryptod relays at most 512 reports at once from each user, then 8 a second. It writes its records at up to 80 a second, below the lowest rate KMES allows a process without SeTcbPrivilege, and queues up to 4096 records when more arrive. A full queue drops its oldest standard record to make room, and turns a record away only when everything it holds is essential. The posture counts what's turned away.

Posture #

Connecting to /run/cryptod/posture returns one MessagePack map, then the connection closes. It describes the policy in force, and what's been used since cryptod started:

KeyValue
policyThe thresholds, flags, and exceptions in force; dropped, the exceptions dropped and why; defaults; and last-failure, a compile that failed since, or nil
fipsrequested; approved-mode, always false while the module isn't validated; reasons; and exceptions-admitting-non-fips
useOne map per user SID: the exceptions it used, by entry, and the entries it was warned about, each with a count of reports
turned-awayCounts of reports rate-limited, unattributed, and invalid, and overflow: what didn't fit the queue or a table

The posture is held in memory, so it starts again when cryptod restarts. Its tables are bounded, at 4096 users and 256 exceptions each.

Services and Jobs

Peios / Using Peios / Services and Jobs

Use Services Manager on the desktop or svctl in a terminal to see what is running and control it. Both talk to peinit, the service manager that runs as PID 1. Start with a status check; change the definition only when the running service needs different configuration.

svctl list
svctl status jellyfin
svctl boot

Replace jellyfin with the service name you want to inspect. list shows only services you have permission to query.

Where to start #

What you needStart here
Check, start, stop, restart, or reload a serviceControlling services
Understand Failed, Backoff, Skipped, or AbandonedRead service states and Troubleshooting
Find output from a failed run or hookService output and logging
Create a service or change its settingsDefining a service
Change automatic starts or a scheduleTriggers and timers
Diagnose a reduced boot or reboot loopBoot modes
Shut down or reboot deliberatelyShutdown

For exact field types and defaults, use the Registry key reference. For implementation and protocol details, use the peinit Technical Reference Manual.

Three kinds of object #

In status or logsMeaningWhat to inspect
ServiceA named definition and its current state.svctl status <service>
JobOne execution of a service, hook, health check, or submitted program. A restart gets a new job ID.The job ID in status and the matching logs.
OperationOne request to start, stop, restart, reload, or reset a service.svctl operation-status <id> when a command returned without waiting.

See Jobs and operations to follow a run or submit a one-off job.

peinit in one sentence #

peinit starts services from registry definitions, runs each under its configured identity, supervises it, and stops services in dependency order at shutdown. You use svctl or Services Manager to request those actions.

What peinit is not #

Service definitions live under Machine\System\Services\ in the registry. There are no systemd unit files or Windows SCM commands to edit or translate. Use Defining a service for configuration and Service types for programs that need to stay in the foreground.

Logs and durable history belong to eventd. Open Logs… for a service in Services Manager, or follow Service output and logging. The TRM compatibility notes describe the interface boundaries.

The one operational invariant #

peinit uses a cached service configuration. A saved change can wait for the next start or another relevant operation; it does not necessarily change a running process. Check when configuration changes apply. The event-loop design explains why.

Where peinit sits in the system #

The service's Identity controls what its process can access. Its ServiceSecurity permissions control who can manage it. Permission to edit its registry definition is separate again. See Service identity and Who can manage a service. The TRM system map covers the components behind these checks.

Controlling Services

Peios / Using Peios / Services and Jobs

Use svctl to inspect and control services from a terminal, or Services Manager on the GXWI desktop. Start by checking the service before issuing a command that interrupts it.

svctl list
svctl status jellyfin

Use the name from the list in place of jellyfin. The command form is svctl <command> [service] [flags]. To investigate a failure, keep the state, cause, job ID, and warnings, then open the service's logs.

Reading status #

Read state and cause together, then check health and warnings:

svctl status jellyfin
svctl list
DetailHow to use it
state, causeTell whether the service is running, waiting to retry, skipped, or failed, and why. See service states.
status_text, progressThe latest information the service reported. These clear on restart and can be absent.
current_jobIdentifies this execution. Use its GUID to separate its logs from previous runs.
current_operationIdentifies an action in progress. Poll its ID with svctl operation-status <id>.
healthhealthy, unhealthy, unknown (no check result yet), or null (no check configured).
warningsNotices such as leaked cgroups. Read these before trying another start.
definition_removedA deleted definition still has a draining instance. stop still works; start, restart, and reload do not.
grantedYour query, start, stop, and reload rights. A visible service does not imply permission to change it.
timersNext scheduled occurrence, actual firing after jitter, last firing, or a reason the timer could not be armed.

An Active service has met its configured readiness check. With Readiness=Alive, that only confirms the process exists; it does not prove the application is serving requests.

For a scheduled service:

$ svctl status logrotate
logrotate: inactive
cause: clean_exit
timers:
  *-*-* 02:00:00
    next: 2026-06-02T02:00:00Z, firing at 2026-06-02T02:07:12Z after jitter
    last fired: 2026-06-01T02:03:40Z

svctl prints timer times in UTC, to the second. Services Manager shows them in local time. svctl list has a NEXT TIMER column for each service's soonest firing. Jitter is already included in the actual firing time.

list omits services you cannot query. job list does the same for jobs. An operation ID expires after its terminal retention grace; a submitted job is retained for 60 seconds after it ends. For older results, look in eventd. The TRM client examples retain the full JSON views and field formats.

Manager #

On a GXWI desktop, Services Manager does the same from a window. It lists every service, shows what the selected one is doing (its state and why, its process, the account it runs as, how long it has been running, anything it has reported), and offers Start, Stop, Restart, Reload and Reset. The same commands are on each row's right-select menu. Type in Find a service to narrow the list by name or description.

Services Manager is another client of the same control socket, so it has exactly your authority and no more:

  • A command is offered only where it will act. A button is available only if you hold the right the command needs (see the table below) and the service is in a state where the command does something (see the command × state matrix). Otherwise the button is unavailable. The details pane says which commands you can use on the selected service.
  • Commands do not block the window. A command is sent without waiting. Services Manager follows its operation and reports the result, such as "SSH server was restarted." or the reason it failed.
  • Hidden services are listed, not silently dropped. list omits the services you cannot query. If you can read the service definitions in the registry, Services Manager still lists those services, marked Not yours to see, and says how many there are.
  • If peinit does not let you connect at all, Services Manager says so. By default the control socket admits everyone who is signed in, but it can be locked down. Any definitions you can read are still listed, and no command is offered.
  • Its definition opens in a window of its own, from Edit definition… in the details pane or on a row's menu. New service… on the bar defines one. Both are covered in Defining a service, with svctl definition, which does the same from a terminal.
  • Who can control a service, and who can change its definition, open from the details pane in the permissions editor. They are covered in Who can manage a service.
  • What it has logged opens in Event Viewer, from Logs… in the details pane or on a row's menu. The window shows the service's lines and those of its hooks and health checks, newest first and as they are written. See Event Viewer.
  • Timers show when they run. The Next run column shows when each service's soonest timer fires. The details pane lists each timer under its schedule, with its next run and its last run, in the machine's local time. A timer with jitter says that its run is put back by a random delay, and the next run shown already includes that delay. A timer peinit could not arm says why it never runs. These are peinit's own figures, read from status, not worked out from the definition.

peinit doesn't announce state changes, so Services Manager asks it for the services' state every two seconds. Press F5, or select Refresh, to ask straight away. What the registry holds is different. That covers which services are defined, who can control them, and what you can change. Services Manager watches the Services key for changes and reads it again only when something changes, so a change made elsewhere, from svctl or another window, shows at once.

Before changing a service #

  • Start begins the full start sequence and can start dependencies.
  • Stop interrupts the service. A BindsTo dependent stops with its target; a Requires dependent that is already running does not. See Dependencies.
  • Restart stops and starts as one operation, replacing the current process. Use it when a definition change needs a new process.
  • Reload asks the running program to re-read its own configuration. reload-config instead asks peinit to re-read service definitions. Neither promises to apply launch-only settings to an existing process.
  • Reset clears Failed, Abandoned, or Skipped to Inactive; it does not start the service or repair the cause.

After the action finishes, run svctl status <service> again. If it failed or only returned an advisory reload result, follow the troubleshooting guide before repeating it.

Service commands #

CommandDoesRequired right
startRun the service through its full start sequence.SERVICE_START
stopSIGTERM, then SIGKILL after StopTimeout.SERVICE_STOP
restartStop then start, as one operation.SERVICE_STOP + SERVICE_START
reloadRe-read configuration (ExecReload, or SIGHUP).SERVICE_INTERROGATE
resetClear Failed/Abandoned/Skipped → Inactive.SERVICE_STOP
statusReport state, cause, PID, uptime, health, current job and operation, warnings, and when each timer fires.SERVICE_QUERY_STATUS
listList services, their states, and their next timer firing (filtered to what you can query).(per-service SERVICE_QUERY_STATUS)
svctl start jellyfin
svctl restart jellyfin
svctl reload nginx
svctl reset failed-migration     # clear a Failed state without starting

Wait semantics #

By default, a lifecycle command blocks until its operation reaches a terminal state — start waits for Active (or Failed), stop waits for Inactive, and so on. Pass --no-wait to get the operation_id back immediately and poll with operation-status instead.

CommandDefaultWaits for
startwaitActive (Simple) / Completed or Inactive (Oneshot), or Failed
stopwaitInactive
restartwaitthe successful start target, or Failed
reloadno-wait(with --wait) the Reloading state to resolve
resetimmediate—

reload is the exception — it returns immediately by default, because a reload can have no observable completion. With --wait, the response carries a mode:

modeMeaning
confirmedThe service signaled READY=1 (and, for a command reload, the command exited 0).
advisoryThe reload was issued and the detection window elapsed without explicit confirmation.
failedThe ExecReload command exited non-zero or timed out. The service stays Active — a failed reload never takes down a running service.

The detection window is a fixed 2 seconds — it is built in and is not configurable through the registry. If the service says nothing within that window, the reload resolves as advisory and the service stays Active.

Note

A connection blocked on a --wait operation is not counted as idle, so it is not closed by ConnectionTimeout. It stays open until the operation resolves, bounded by the operation's own timeout (for example StartTimeout ).

System commands #

CommandDoesRequired right
shutdown <type>Graceful shutdown. type is poweroff, reboot, or halt.SYSTEM_SHUTDOWN
bootReport this boot's mode, reason, and confirmation status.SYSTEM_QUERY_STATUS
reload-configRe-read all definitions and rebuild the graph (atomic).SYSTEM_RELOAD_CONFIG
operation-status <id>Report the state of an operation by GUID.SERVICE_QUERY_STATUS on its target
svctl shutdown poweroff
svctl reload-config
svctl operation-status a1b2c3d4-...

Job commands #

Submitted jobs are reachable from two places, and svctl job covers both. Querying and stopping a job is administration and goes over the control socket; submitting a job, waiting on it, and signaling it belong to its submitter and go over the jobs socket at /run/services/peinit/jobs.sock (--jobs-socket overrides the path). Every job command is checked against the job's own descriptor, which by default admits the submitter, SYSTEM, and Administrators.

CommandSocketDoesRequired right
job list [filters]controlList the jobs you can query. Filters: --submitter SID, --identity SID, --logon-session N, --state created|running|completed|failed|abandoned; all given filters must match.per-job JOB_QUERY (others omitted)
job status JOB_IDcontrolThe job view.JOB_QUERY
job stop JOB_IDcontrolSIGTERM, then SIGKILL of the job's cgroup after its stop_timeout. Waits for the job to end by default; --no-wait returns the view as it then is.JOB_STOP
job submit [options] IMAGE [ARG...]jobsSubmit IMAGE as a job running as your own primary token, and print its view once it is running (or has failed to start). With --wait, wait for it to end too.connect to the jobs socket
job wait [--for ready|terminal] JOB_IDjobsBlock until the job is terminal (default) or has sent READY=1, then print the view. --for ready on a job without a readiness protocol is INVALID_STATE.JOB_QUERY
job signal JOB_ID SIGNALjobsSend one signal (a number, or a name like SIGUSR1) to the job's main process. Only the main process, only while running.JOB_SIGNAL
$ svctl job list --state running
JOB       STATE    SUBMITTER              IDENTITY               PROGRESS   DESCRIPTION
5f2a...   running  S-1-5-21-...-1001      S-1-5-21-...-1001      3/5 items  nightly backup
$ svctl job status 5f2a...
$ svctl job stop 5f2a...
$ svctl job submit --description "nightly backup" --timeout 3600 -- /usr/bin/backup --full
$ svctl --wait job submit --env MODE=full /usr/bin/backup   # exits 0 only if the job completed
$ svctl job wait --for ready 5f2a...
$ svctl job signal 5f2a... SIGHUP

job submit takes the definition fields as options: --description TEXT, --cwd DIR, --env NAME=VALUE (repeatable), --timeout SECS, --stop-timeout SECS, --readiness none|notify, --readiness-timeout SECS , --success-exit-code N (repeatable), --security-descriptor SDDL. Two hand the job something of yours: --fd NAME=FD passes a descriptor of the svctl process to the job under NAME (from descriptor 3, with LISTEN_FDS /LISTEN_FDNAMES set), and --output attaches svctl's standard output as the job's output sink, so the job's lines appear on your terminal as well as in eventd. Everything after IMAGE belongs to the job, options included; use -- before an image path that starts with a dash.

The CLI has no way to attach a token, so a svctl -submitted job always runs as the caller. Running a job as someone else is a programmatic act — a service attaching the token of the client it is impersonating — and is described in Jobs and operations.

The command × state matrix #

A command sent to a service in an unexpected state returns an error, not a silent no-op. This matrix is the authority on what each command does in each state:

CommandInactiveStartingActiveReloadingStoppingCompletedBackoffFailedAbandonedSkipped
startStartMERGEALREADYALREADYQUEUEStartDEFERStartERRORStart
stopNOOPCancel+StopStopStopMERGEClearCancelNOOPERRORNOOP
restartStartQUEUERestartRestartQUEUEStartRestartStartERRORStart
reloadERRORERRORReloadMERGEERRORERRORERRORERRORERRORERROR
resetNOOPERRORERRORERRORERRORERRORERRORClearClearClear
statusOKOKOKOKOKOKOKOKOKOK

Legend:

  • MERGE — an operation of this type is already running; your command merges into it and you get its GUID.
  • DEFER — your start is accepted and creates a Pending start operation, but it does not run yet: it waits out the service's existing backoff deadline and then starts. If a deferred start is already waiting, you merge into it and get its GUID.
  • ALREADY — already in the target state; returns the current status, not an error.
  • QUEUE — queued as Pending; runs after the current operation finishes.
  • NOOP — no effect; returns the current status.
  • Clear / Cancel — clear the state to Inactive / abort the current operation, then proceed.
  • ERROR — invalid for this state; returns an error with an explanation.

The Backoff column is the subtle one: the service is down with an automatic restart pending, so start is deferred — it creates a Pending start that honors the remaining backoff delay and only runs once that deadline expires (a second start merges into the one already waiting), stop cancels the pending restart and any deferred start (the service goes Inactive), restart cancels the automatic one and does an admin restart, and reload /reset are invalid because no process exists.

Error codes #

An error response is {"status": "error", "code": "...", "message": "..."}. The code is one of:

CodeMeaning
ACCESS_DENIEDAccessCheck denied the command against the target descriptor.
UNKNOWN_SERVICENo such service definition (also returned for start/restart/reload on a definition-removed service).
UNKNOWN_OPERATIONNo such operation GUID — never existed, or dropped after its retention grace.
UNKNOWN_JOBNo such job GUID — never existed, or dropped after its retention grace. A known job you cannot query returns ACCESS_DENIED.
MALFORMED_REQUESTThe request line is not a single valid JSON object.
REQUEST_TOO_LARGEThe request exceeds MaxRequestSize.
INVALID_COMMANDThe command field is missing or unknown.
INVALID_ARGUMENTSA required field is missing or malformed (for example shutdown with no valid type).
INVALID_STATENot valid for the service's current state (an ERROR cell above), or rejected because the system is already shutting down.
OPERATION_TIMEOUTA --wait operation did not reach a terminal state within its timeout.
INTERNAL_ERRORpeinit hit an internal failure executing the command.

The jobs socket uses the same envelope and codes, plus two of its own:

CodeMeaning
QUOTA_EXCEEDEDThe submission would exceed MaxJobsPerSubmitter live jobs for your SID. Nothing was created.
BAD_TOKENThe token attached to a submission cannot be a job identity — more than one was attached, its impersonation level is below Impersonation, or it could not be duplicated.

The message is human-readable and non-normative — read it for context, key off the code.

Exit status #

CodeMeaning
0The command succeeded. For job submit --wait, the job also completed.
1peinit refused the command — an access denial, unknown service or job, invalid state, or timeout — or a job submit --wait job ended other than completed.
64A usage error.
69peinit could not be reached — the socket is missing or refused the connection.
70A protocol error — peinit answered with something the client could not read.

How the control interface works #

Both tools use /run/services/peinit/control.sock. Connection admission and each service action are access-controlled. The default socket admits signed-in users; the target's permissions decide which commands they can run.

Lifecycle commands create an operation ID you can follow. Concurrent identical requests can merge into one operation. For JSON framing and complete response examples, see the control-client reference.

Connection limits #

peinit enforces hard limits on the control socket, all tunable under Machine\System\Init\:

KeyDefaultLimits
MaxControlConnectionsPerUser16Concurrent client connections one user can hold; SYSTEM is exempt (excess are refused at connect).
MaxControlConnections256Concurrent client connections in all (excess are refused at connect).
MaxRequestSize65536Bytes per request.
ConnectionTimeout30Seconds an idle connection can sit before it is closed.

The jobs socket has its own set, under the same key:

KeyDefaultLimits
MaxJobsConnections64Concurrent jobs-socket connections (excess are closed at connect, with no response).
MaxJobMessageSize32768Bytes per message — which bounds a submission's whole definition.
JobsConnectionTimeout30Seconds an idle jobs connection can sit before it is closed. A connection blocked on a wait or a pending submit is not idle.
MaxJobsPerSubmitter64Live jobs one submitting SID can hold. SYSTEM is exempt.

Where to start #

To understand the states the matrix refers to, read The service lifecycle.

To understand the operations every lifecycle command creates and how to poll them, read Jobs and operations.

To configure who can run each command, read Who can manage a service.

Managing Services in Services Manager

Peios / Using Peios / Services and Jobs

Services Manager distinguishes a service's running state from the persistent definition peinit reads. Starting or stopping a service changes its runtime; editing the definition changes how it is configured.

Before you start #

You need Services Manager in a GXWI session. Runtime control uses peinit's service rights. Editing a definition uses registry rights, which are a separate permission check.

Control a service #

  1. Open Services Manager and use Find a service to narrow the list.
  2. Select the service and read its state, reason, process, account, recent report, and timers. Timer times are shown in local time.
  3. Choose the available runtime action, such as Start, Stop, Restart, or Reload, after checking its effect.
  4. Read the command's outcome. Select Logs to open the service's recorded output in Event Viewer when more context is needed.

Check the result #

The state refreshes every two seconds. Refresh or F5 reads it at once. Confirm the intended state and inspect any failure reason. A button being available does not guarantee that the service will start successfully.

Edit a definition #

Open Edit definition for an existing service or New service for a new one. Review the grouped fields and save with Save or Ctrl+S. The editor validates the fields and writes changed values in one registry transaction. Check peinit's resulting state rather than assuming that a saved definition restarted an existing process.

The permissions for controlling a service and changing its definition are separate dialogs. Default permissions concerns services without their own service descriptor. A registry definition you can read can remain visible even when peinit refuses access to the service's runtime state. See gxwi-services-manager(1) and svctl(8).

Finding Service Logs

Peios / Using Peios / Services and Jobs

In Services Manager, select the service and choose Logs…. It opens Event Viewer with the service's lines and the output of its hooks and health checks, newest first and updating as they arrive.

For terminal queries, use evctl. peinit forwards output; eventd stores and queries the records it receives.

Find the failed run #

  1. Run svctl status <service> and note its state, cause, current job ID, and warnings.
  2. Open Logs… and inspect the time around the failure. Hook and health-check output can explain a start or health failure even when the main process wrote nothing.
  3. Match the job GUID to isolate one execution. A restart has a new job ID.
  4. For earlier attempts, look for peinit.job.started, peinit.job.ended, and the operation events in eventd. The live job or operation can already have expired.

Log origins identify the producer: the service name, a hook such as jellyfin/ExecStartPre[0], or jobs/<id> for a submitted job. A log's stream tells you stdout or stderr, not whether the line necessarily describes an error.

Capturing output #

peinit captures stdout and stderr, including hooks and health checks, and tags lines with the origin, stream, timestamp, and job GUID. A submitted job cannot opt out of forwarding; --output requests an additional live copy.

Warning

A service with TTYPath sends all three standard streams to its terminal. Its output is not captured for eventd. Check the terminal or change the service's output arrangement if you need a log record.

Pipe wiring and tagging are described in the output-flow reference.

Logs and events have different limits #

Service logs and structured events take separate paths:

RecordPathWhat to expect
Service stdout/stderrpeinit's output buffer and eventd's log socketBest-effort; lines can be truncated or dropped under load.
Job, operation, access-check, and failure eventsKMES, then eventdIndependent of the log socket. KMES holds a finite in-memory record; eventd supplies stored history.

Do not assume an event has survived a reboot merely because it was emitted. The kernel ring is not persistent, and it can overwrite older events if consumers fall behind. See KMES failure modes for those limits and Auditing for event storage and queries.

The pre-eventd buffer #

Before eventd is available, peinit holds output in memory, by default up to PreEventdBuffer=1048576 bytes. Overflow drops the oldest lines. The buffer is replayed when eventd is ready, but it is not persistent storage and cannot guarantee a complete boot log.

The buffer reference explains the early-boot path.

Flood protection #

A [truncated] marker means a line exceeded MaxLogLineLength (8192 bytes by default). Output delivered faster than peinit can read can block the service's writes at its pipe; downstream delivery to eventd is loss-tolerant.

If a submitted job's live output has gaps, look for peinit.job.output.dropped. That reports loss in the extra output copy, not necessarily loss in eventd; query eventd separately. Ordinary log delivery remains best-effort there too.

See the registry limits before changing buffer sizes and the TRM flood-control detail for the implementation.

The eventd handoff #

When eventd reaches Active, peinit replays buffered output and forwards new lines. If eventd exits, peinit resumes buffering and repeats the handoff when it returns. Missing log lines around that interval can reflect buffer overflow or lossy delivery; an empty query alone does not prove the service wrote nothing.

Access policy can also hide records from a query. Check who can read what if the expected origin is absent. The handoff reference describes transport behavior.

Console output #

peinit writes boot progress, shutdown progress, recovery entry, and critical failures to /dev/console. Service output is not echoed there by default. A terminal-attached service is the exception because it writes directly to its terminal.

peios.quiet can suppress peinit's console messages, and suppressed messages are dropped rather than saved for later. See console noise settings when investigating a boot problem.

Where to start #

For symptom-based next steps, use Troubleshooting. For finding older executions or actions, use Jobs and operations. For query tools, use Event Viewer or evctl.

Troubleshooting a Service

Peios / Using Peios / Services and Jobs

Collect the current state and cause before changing anything:

svctl status <service>
svctl list
svctl boot

Keep the job or operation ID and any warnings. Open Logs… for the service in Services Manager to inspect its main process, hooks, and health checks. For older attempts, query logs and events; live status is not a permanent history.

Use the symptom below to choose the next check. Avoid repeating a restart or changing permissions until you know which layer failed.

A service won't start #

status shows it Failed or Skipped. The cause says why:

CauseWhat happenedWhat to do
ValidationErrorThe definition is malformed — a bad field, an unresolvable conflict, an illegal health-check timing.Check the logs for the specific field. Fix the definition; the message names what is wrong.
DependencyFailureA Requires/BindsTo target failed or does not exist.Fix the target first — status it. The dependent recovers once the target can start.
ConditionSkipped (→ Skipped)A start-time condition was not met. Not a failure — the service decided it does not apply here.If it should run, the condition's premise is false (a missing path/file/key). This is often correct behavior.
TtyUnavailable (→ Skipped)Another service is holding the terminal this one names in TTYPath. Not a failure — it is waiting its turn.Check who has it: the holder is the other service with that TTYPath in a running state. Give this one a higher TTYPrecedence to win next boot, or a tty:released trigger so it starts when the terminal frees.
AssertionErrorA start-time assert failed — a required precondition is missing.Create the missing precondition (path, file, directory, registry key), then start again.
PreHookFailureAn ExecStartPre hook exited non-zero.Inspect the hook's captured output and its identity. Before rerunning it manually, check for side effects: setup and migration hooks can change data.
ParentSetupFailurepeinit could not even fork — fd/PID exhaustion, a cgroup error. No process was created.A system-resource problem, not the service's fault. Check for fd/PID limits and cgroup health.
PreExecFailureSetup after fork failed — token install, rlimits, environment.Usually identity: check Identity, that authd is up, and that RequiredPrivileges names real privileges.
ReadinessTimeoutThe process started but never became ready within StartTimeout.Either the service is genuinely slow (raise StartTimeout, or have it send EXTEND_TIMEOUT_USEC) or it never sends READY=1 (wrong Readiness, or a bug).

Tip

A startup failure (ReadinessTimeout, PreHookFailure, PreExecFailure, ParentSetupFailure) is restart-eligible. Whether it was retried depends on the configured policy and budget; Failed alone does not prove multiple attempts occurred. Read the restart policy and the logs for the actual attempts.

A service keeps restarting #

The service flaps — up, down, up, down. This is restart policy doing its job, but it points at an unstable service.

  • It eventually settles in Failed with RestartBudgetExhausted. It crashed RestartMaxRetries times faster than it could stay healthy for RestartWindow. The fix is the service, not the policy — read its logs for the crash. Raising the budget only delays the inevitable.
  • It flaps forever and never exhausts the budget. Check whether it stays Active for the full RestartWindow between failures. Reaching Active briefly does not reset the budget. Inspect the health-check output too; a faulty check can restart a working service.
  • It restarts on a clean exit you did not expect. RestartPolicy=Always restarts even successful exits (cause CleanExitRestart). If the service is meant to exit, use OnFailure instead.

The machine keeps rebooting #

Preserve the last console error and any service records before attributing repeated reboots to a service. If peinit reports a Critical service exhausting its restart budget, its ErrorControl=Critical policy makes peinit sync and reboot. Repeating that failure can produce a reboot loop; the symptom alone does not establish this cause.

The boot-attempt counter can break a sequence of boots that reach peinit's counter increment but never become confirmed: after N attempts (default 3), peinit enters Recovery mode. If each boot reaches the success grace before the Critical failure, its counter is reset and the reboot loop can continue without automatic Recovery. Check svctl boot while the normal control interface is available; it is unavailable in Recovery. Do not assume every reboot loop will stop after three attempts, or that peinit can deliver Recovery if it cannot start.

In Recovery, start with the failure reason on the console. Phase 2 services are skipped, so stored eventd history is not automatically queryable from that shell. Where a supported running eventd query service is available, use Find service logs and Find missing records to investigate earlier attempts. evctl queries that service; it does not open stored databases offline. Otherwise, retain the console evidence for the administrator or provider's recovery procedure.

Once the evidence identifies a Critical service failure, repair its cause or restore known-good configuration through a supported recovery path before rebooting. Disabling a required platform service can leave its dependents unable to start. If you need to intervene before the counter trips, boot with peios.recovery=1 on the kernel command line.

Abandoned #

Abandoned means peinit SIGKILLed the process but it survived — stuck in uninterruptible kernel sleep (D-state), the signature of hung I/O (a dead NFS mount, a failing disk). Nothing in userspace can kill a D-state process.

  • The underlying I/O fault is the real problem — investigate the storage or mount, not peinit.
  • The service's cgroup is leaked and shows in warnings. A later start uses a fresh generational cgroup, so the new instance is unaffected.
  • svctl reset <service> clears the Abandoned state and re-checks the cgroup: if the stuck process finally died, peinit cleans up; if not, it stays leaked and warns you. Leaked cgroups clear fully only on reboot.

I changed the config and nothing happened #

peinit works from an in-memory snapshot, and each field has a mutability class that decides when a change applies:

  • Immutable at runtime (ImagePath, Type, Identity, RequiredPrivileges, ErrorControl) → takes effect only on restart.
  • Apply on next start (dependencies, conditions, OnFailure) → next start or graph reload.
  • Reloadable at runtime → next relevant operation. Timeouts and health-check policy can affect later checks; environment, arguments, working directory and process limits apply to a new process, not one already running.
  • Hot-reloaded (ServiceSecurity) → next control request.

If a change is not landing, check its class first. For a wholesale re-read of every definition, run svctl reload-config — it rebuilds and validates the whole graph atomically and swaps it in only if validation passes (running services are untouched). And remember peinit pulls changes from registry notifications rather than having them pushed, so there can be a brief lag.

ACCESS_DENIED #

A control command returns ACCESS_DENIED. peinit ran AccessCheck on your token against the target's descriptor and the right was not granted:

  • A service command needs the matching right in the service's ServiceSecurity descriptor (start needs SERVICE_START, restart needs both stop and start, …).
  • shutdown and reload-config need SYSTEM_SHUTDOWN / SYSTEM_RELOAD_CONFIG in peinit's control descriptor.
  • The check uses your effective identity at connect time — if you are impersonating, that is what is checked.

Under the default descriptors every denial is recorded by the kernel as a kacs.audit.access.checked event naming the caller, the target (its object kind is service, job, or peinit-system) and the rights requested and granted. Walk it through Debugging a denial.

Note

If list shows fewer services than you expect, that is not a bug — list omits services you lack SERVICE_QUERY_STATUS on rather than denying them. You are seeing exactly what your token can see. job list does the same with JOB_QUERY.

A job submission is refused #

A job submit — from svctl or from a service — comes back with an error rather than a job. The code says which door it hit:

CodeWhat happenedWhat to do
connection refused, or an immediate closeYou cannot reach /run/services/peinit/jobs.sock — its file descriptor does not grant you write, or peinit is at MaxJobsConnections. peinit itself performs no check on who can submit; the socket's descriptor is the whole policy.Check the socket's descriptor (by default Authenticated Users can connect) and the connection count.
QUOTA_EXCEEDEDYour SID already holds MaxJobsPerSubmitter live jobs (default 64).job list --submitter <your SID> to find them; stop what should not be running, or raise the key. SYSTEM is exempt.
BAD_TOKENThe token you attached cannot become a job identity: more than one was attached, it is below Impersonation level, or peinit could not duplicate it.Attach exactly one token obtained by impersonating the client; an Identification-level token is never enough. If the job needs Delegation, set the jobs connection to Delegation before attaching.
INVALID_ARGUMENTSThe definition is malformed — a relative image_path, a descriptors list that does not match what you attached, a security_descriptor without an owner and DACL.The message names the field.
INVALID_STATEThe system is shutting down; submissions are refused.—

A job that was accepted but never ran is not an error response: it is an ok response whose view is failed with a cause — parent_setup_failure (peinit could not prepare the launch) or pre_exec_failure (the program could not be executed as that identity, which is where "no such file" and "permission denied" land, because peinit does not check the image before accepting a submission).

A job's output has gaps #

If a submitter attached an output sink and sees gaps, look for a peinit.job.output.dropped event for the job in eventd: the sink was not being drained fast enough, and peinit dropped lines for the sink only rather than let it slow the job. Query eventd under the job's GUID for the independently forwarded record. Sink loss does not itself drop that record, but eventd's log path is also best-effort, so completeness is not guaranteed.

UNKNOWN_JOB #

The GUID is unknown or its retention has elapsed. A submitted job is retained for 60 seconds after it ends, then dropped; check eventd for any stored record. A known job that you lack permission to query returns ACCESS_DENIED . job list instead omits jobs you cannot query.

A dependent never started #

You started (or booted) a service, but something that depends on it never came up:

  • A Requires/BindsTo dependent stays blocked until its target reaches a satisfying state (Active, Reloading, Completed, or Skipped). If the target is stuck in Starting or Failed, so is the dependent — fix the target.
  • If a dependent got connection refused on boot, check the target's readiness setting and startup logs. With Readiness=Alive, peinit waited only for the process to exist, not to be serving. Use Readiness=Notify only if the program supports sending READY=1 from its tracked main process when ready; changing the setting does not add that support and can cause ReadinessTimeout. See the notification contract. If the program cannot signal readiness, have its service or package owner resolve the startup race. peinit's boot validation warning can identify an Alive-readiness dependency; it does not prove the cause of a refused connection.
  • A Wants dependent waits for the optional target's startup attempt to resolve, but starts even if the target failed. Use Requires when successful readiness is necessary.

Safe #

Safe mode selects Critical and SafeMode=1 services within the boot-triggered set. Those flags do not give a demand-only service a boot trigger. You land here when graph validation finds a cycle or unresolvable conflict involving a Critical service, or when peios.safemode=1 is on the kernel command line. The TCB is healthy; the configuration is broken.

Fix the graph: the logs name the cycle path (A → B → C → A) or the conflicting pair. Once the cycle is broken or the conflict resolved, a normal boot returns. You can start any service by hand from Safe mode in the meantime — it is only auto-start that is restricted.

Recovery #

Recovery mode gives you a SYSTEM shell on the console and skips Phase 2 services. It starts registryd only if the boot has not already attempted that start. You reach it when the boot counter hits N, when peios.recovery=1 is set, or when registryd failed in Phase 1 (Recovery is immediate; this boot attempt has already incremented the counter).

If the registry itself is failing:

  1. Preserve peinit's console failure reason and the source's startup diagnostics. A failed registry operation does not prove the source process has exited.
  2. Identify the installed registryd provider and version, its hive declarations and actual database paths. LCS and sources explains the default loregd provider and its diagnostics.
  3. Establish whether the source is already active before any storage work. Recovery can retain a registryd started or attempted earlier in the boot. Do not launch a second source against the same hive files.
  4. Obtain the installed provider's supported recovery procedure before attempting offline inspection or repair. The source-checked loregd implementation accepts hive declarations and has no offline repair switches. It does not create an automatic startup backup; its orphan cleanup is not corruption repair or backup restoration. Those references identify the checked revision. Verify what recovery copy actually exists and what it contains before planning a replacement.

When the source is serving the required registry operations, Backup and restore describes the supported privileged subtree workflow. That workflow depends on a working source; it does not repair an unavailable source. Restore replaces the target contents and descendants, including security descriptors, so review the target and backup before using it. Role definitions can re-supply service configuration but do not restore every registry value.

Recovery offers no TCB guarantee. Treat the unrestricted SYSTEM shell accordingly, and remember it needs console access (physical, IPMI, or serial); there is no remote recovery yet.

Where to start #

To read states and causes fluently, keep The service lifecycle handy.

For restart, backoff, and Critical-reboot behavior, see Keeping services running.

For the commands and their outputs, see Controlling services.

Read Service States

Peios / Using Peios / Services and Jobs

Run svctl status <service> and read state and cause together. State tells you where the service is now; cause tells you why it got there. Failed with ValidationError calls for a definition fix, while Failed with RestartBudgetExhausted calls for the logs from repeated attempts.

Use the state table below for a quick interpretation, then the troubleshooting guide for the next action. You do not need the full state machine before running a status check.

The states #

StateProcess?Satisfies dependents?What it means when you see it
InactiveNoNoNot started, or stopped cleanly and not set to restart. The neutral resting state.
StartingMaybeNoActivation in progress — conditions, hooks, fork, or readiness wait. Dependents are blocked.
ActiveYesYesRunning and ready. The normal state of a healthy Simple service.
ReloadingYesYesRe-reading configuration. Still counts as running.
StoppingYes (briefly)NoSIGTERM sent; waiting for exit or SIGKILL escalation.
CompletedNoYesOneshot finished successfully. Stays here only with RemainAfterExit=1.
BackoffNoNoA restart is pending; the service is waiting out its backoff delay before the next attempt.
FailedNoNoExited abnormally and restart policy is exhausted or not configured.
AbandonedYes (unkillable)NoSIGKILL was sent but the process survived in uninterruptible sleep (D-state). peinit has given up supervising it; its cgroup is leaked.
SkippedNoYesA start-time condition was not met, or its terminal was unavailable. Read the cause.

Four of these — Active, Reloading, Completed, Skipped — satisfy dependents. Everything else blocks them. That single column is the rule the whole dependency system turns on: a service waiting on a Requires target does not move until that target reaches one of those four.

Choose the next check #

  • Starting: inspect the current operation, readiness configuration, and pre-hook output. The main process can not exist yet.
  • Backoff: an automatic retry is already pending. Another start honors the existing delay; stop cancels the pending restart.
  • Failed: read the cause and the failed run's logs before starting again. Definition and dependency faults are not fixed by increasing retries.
  • Skipped: inspect the condition or terminal owner. Skipped satisfies dependents and is not itself a failure.
  • Abandoned: investigate the underlying I/O fault. reset clears the state but cannot kill a process stuck in D-state.

Controlling services lists which actions are valid in each state.

Transition causes #

Every transition carries a cause. peinit keeps the cause of the most recent transition on the service, and emits all of them to eventd. The full taxonomy, grouped by what kind of thing happened:

Why a service started

CauseMeaning
ExplicitStartAn administrator or a trigger started it.
DependencyStartStarted to satisfy another service's dependency.
RestartPolicyAn automatic restart, after a backoff delay.
BindsToRecoveryA bound target returned to Active; the dependent is auto-restarted. Does not consume the restart budget.

Why a service stopped

CauseMeaning
ExplicitStopAn administrator requested stop.
ConflictEvictionA conflicting service started and won.
BindsToPropagationA bound target stopped, so this one stops too.
ShutdownWaveThe system is shutting down.

Why a service failed or restarted — the diagnostic causes

CauseMeaning
ProcessCrashThe main process exited non-zero or died on a signal.
CleanExitA Simple process exited successfully, and policy is not Always — not a crash; goes straight to Inactive.
CleanExitRestartA Simple process exited successfully but RestartPolicy=Always, so it is restarted. Logged clearly as not a crash.
ReadinessTimeoutStartTimeout expired before the service became ready.
WatchdogTimeoutA WATCHDOG=1 keepalive did not arrive in time.
HealthCheckFailureHealthCheckRetries consecutive health checks failed.
PreHookFailureAn ExecStartPre hook exited non-zero.
ParentSetupFailurepeinit could not even fork — resource exhaustion, cgroup error. No child was created.
PreExecFailureSetup after fork but before exec failed (token install, rlimits, environment).
RestartBudgetExhaustedRestartMaxRetries reached within the window; no more retries.

Why a service was rejected — definition and graph problems

CauseMeaning
ValidationErrorThe definition failed validation (bad field, unresolvable conflict, illegal health-check timing…).
CycleDetectedThe service is part of a dependency cycle.
DependencyFailureA Requires dependency entered Failed or does not exist.
AssertionErrorA start-time Assert failed.
ConditionSkippedA start-time Condition was not met → Skipped (this is not a failure).
TtyUnavailableAnother service was holding the TTYPath this one names → Skipped (also not a failure). See Triggers and timers.
ProcessUnkillableThe process survived SIGKILL (D-state) → Abandoned.
ExplicitResetAn administrator cleared Failed/Abandoned/Skipped without starting.

The grouping matters for what peinit does next: the diagnostic causes are mostly restart-eligible (peinit consults restart policy), whereas the definition/graph causes are never restarted — retrying a broken definition cannot help. The distinction is spelled out in Keeping services running.

Tip

When a service is Failed, the cause is the first thing to read. A ProcessCrash or WatchdogTimeout points at the service's own code or health; a DependencyFailure points at something it needs; a ValidationError points at its definition. Troubleshooting peinit is organized around exactly this lookup.

Abandoned #

Abandoned is the one state that reflects a kernel-level problem rather than a service-level one. peinit reaches it when it has sent SIGKILL to a service's process group but the processes are still there after a grace period — the post-kill timeout, 5 seconds by default. If the service's cgroup has not emptied within it, the processes are wedged in uninterruptible kernel sleep (D-state), typically behind a hung mount or a broken storage controller, and the service is marked Abandoned (its cgroup leaked).

peinit cannot kill a D-state process; nothing in userspace can. So it stops trying: it marks the service Abandoned, leaks the cgroup (it cannot be removed while populated), and moves on rather than hanging. The leak is never silent — it shows up in the service's warnings and, on a later start, peinit creates a fresh "generational" cgroup so the new instance is unaffected by the stuck old one.

An Abandoned service is cleared with reset, which re-checks the cgroup: if it finally emptied, peinit cleans up; if it is still populated, peinit leaves it leaked and warns you. An Abandoned service is a sign of an underlying I/O fault that needs investigating, not something to paper over with a restart.

The common path #

Most of a service's life is a small loop. The diagram below shows the states a healthy Simple service moves through, plus the two ways it leaves Active.

stateDiagram-v2
    [*] --> Inactive
    Inactive --> Starting: start / trigger / dependency
    Starting --> Active: ready (READY=1 or alive)
    Active --> Stopping: stop / shutdown / conflict
    Stopping --> Inactive: exited (clean stop / shutdown)
    Stopping --> Failed: exited (conflict / BindsTo eviction)
    Active --> Backoff: crash + restart allowed
    Backoff --> Starting: backoff delay elapsed
    Active --> Failed: crash + no restart
    Starting --> Failed: timeout / hook / setup failure
    Failed --> Starting: explicit start

A few things this picture makes concrete:

  • An automatic restart always routes through Backoff, never through Failed. Backoff → Starting is the retry; Failed is reached only when restarts are exhausted or disabled. This is why OnFailure fires once at the end, not on every retry.
  • Starting can fail before any process exists — a parent-side setup error, a failed pre-hook, a condition, or assert. The cause records which.
  • Failed → Starting is how a manual start (or a recovery path) revives a dead service; automatic restarts never originate from Failed.
  • Stopping has two exits. A clean stop or a shutdown lands in Inactive . But a service stopped because it lost a Conflicts race (ConflictEviction) or because its BindsTo target went away (BindsToPropagation) comes to rest in Failed, carrying that cause — so an evicted or bound-out service shows as Failed in status and needs a reset (or, for a bound service, its target returning) before it starts again. It was not shut down on purpose, so peinit does not treat it as cleanly Inactive.

Oneshot services follow a parallel path through Completed instead of Active: Starting → Completed, and then either staying there (RemainAfterExit=1) or passing through to Inactive. See Simple and Oneshot services.

Note

A crash while Reloading is still a crash. If a service's main process dies while it is re-reading its configuration, peinit treats that as an ordinary ProcessCrash and routes it through the restart policy — Reloading → Backoff if a restart is warranted, or Reloading → Failed if it is not. This is why you can see a service jump straight from Reloading into Backoff or Failed. It is distinct from an ExecReload command failing: a failed reload command leaves the running process untouched and the service stays Active, reporting the failure without changing state.

Readiness gating during boot #

The dependent-satisfaction rule is what makes boot orderly. A service's dependents do not start until it satisfies them:

  • A Simple service satisfies dependents when it signals READY=1 (Notify) or when its process exists (Alive).
  • A Oneshot service satisfies dependents when it exits successfully and reaches Completed.
  • A Skipped service satisfies dependents immediately — it succeeded by not needing to run.

If a service does not reach readiness within its StartTimeout, its dependents diverge by relationship: Requires dependents transition to Failed (DependencyFailure); Wants dependents start anyway. That difference is the whole point of the two relationship types — see Dependencies and ordering.

Invariants #

A handful of rules hold without exception:

  1. A service is in exactly one state at any moment.
  2. Only the transitions peinit defines are valid — there are no others.
  3. Only peinit changes a service's runtime state. No external process can reach in and set it.
  4. A service's securable identity (its ServiceSecurity descriptor — who can manage it) is independent of its process identity (its token — what it can access).
  5. Readiness is per start generation — a READY=1 from a previous incarnation is never honored for the current start.

Where to start #

To understand what happens after a service crashes — restart policy, backoff, health checks, watchdogs — read Keeping services running.

To understand how dependents block on and are released by these states, read Dependencies and ordering.

To see which commands are valid in which state, read the command × state matrix in Controlling services.

Jobs and Operations

Peios / Using Peios / Services and Jobs

A job is one execution; an operation is one action requested on a service. Use the IDs from svctl status to follow what is happening. A service restart creates a new job, so its job ID also distinguishes its output from the previous run.

svctl status jellyfin
svctl operation-status <operation-id>
svctl job list --state running
svctl job status <job-id>

job list and job status here are for submitted jobs. For service-run history, follow the job ID into logs and events. Live status is short-lived; eventd is where to look after an ID expires.

Run a one-off job #

Use job submit when you want one supervised execution under your own identity. For example, if /usr/bin/backup is installed:

svctl job submit --description "nightly backup" --timeout 3600 -- /usr/bin/backup --full

Keep the returned ID, then query or wait for it:

svctl job status <job-id>
svctl job wait <job-id>

To end the whole job, use svctl job stop <job-id>. job signal sends a signal only to its main process and is not a substitute for stopping its cgroup. Check the final state and cause: a job that handles a requested stop and exits successfully is Completed with cause explicit_stop.

A submitted job remains queryable for 60 seconds after it ends. After that, use its GUID in eventd. See job command options and permissions before passing descriptors, changing the job descriptor, or attaching live output.

How they surface #

You meet jobs and operations in four places:

  • status — current_job and current_operation give the GUIDs of the service's active execution and active action (or null).
  • operation-status <id> — polls one operation to a terminal state; a --wait lifecycle command does this for you under the hood.
  • **job list / job status <id> ** — the submitted jobs you can query, and one job's view.
  • eventd — the durable history. Every job and operation lifecycle transition lands there as a structured event, which is how you reconstruct what happened after the objects themselves are gone from peinit's memory.

Jobs: what actually ran #

Every time peinit forks a process — a service's main binary, a pre- or post-hook, a health check, or a submitted job — that single execution is a job, with its own GUID and exit result. If a service is the what, a job is what actually ran. A restart does not reuse a job; it creates a new one. The service always tracks its current job GUID, and a status query reports it.

Jobs come in five types:

TypeCreated for
ServiceMainA service's main process.
PreExecHookOne ExecStartPre command.
PostExecHookOne ExecStartPost command.
HealthCheckOne health-check run.
SubmittedA program submitted over the jobs socket.

Their lifecycle is simpler than a service's, because a job only tracks a process — not policy:

StateMeaning
CreatedThe job object exists but the process is not forked yet (pre-hooks can be running).
RunningThe process is alive.
CompletedThe process exited successfully.
FailedThe process failed — or peinit classified the job failed before fork (a parent-side setup error).
AbandonedThe process survived SIGKILL (D-state).

A job record carries the things you would want for forensics: the resolved identity and a token summary, the image path and arguments, created/started/ended timestamps, the exit code or signal, the cgroup, the failure cause, and the operation_id that created it (null for submitted jobs). The clean division of ownership is: the service owns policy (restart, dependencies, health schedule, current state); the job owns the execution facts (PID, exit, timestamps, identity, cgroup, log correlation).

Retention and log correlation #

For service executions, peinit keeps only active job records in memory. When a job reaches a terminal state it emits a structured event (through KMES) carrying the full record, then drops the job. Submitted jobs retain a terminal view for 60 seconds, as described below; peinit keeps no durable job history — eventd is the historian, consuming those events from the kernel ring buffer. The lifecycle events are peinit.job.created, peinit.job.started, and peinit.job.ended; a submitted job also emits peinit.job.status.reported as its progress changes. peinit.job.created and peinit.job.status.reported are verbose events, off unless the event emission policy (Machine\Generic\Events, PGSS §6.9) turns them on.

Separately, captured job stdout /stderr is forwarded to eventd tagged with the job's GUID. A service with TTYPath writes to its terminal instead; see the terminal-attached service exception. The GUID lets a query like "show me the logs for job X" distinguish that execution's records from the run before or after it.

Operations: what was requested #

An operation is a first-class object representing a requested state-machine action on a service. Rather than letting control commands mutate state directly, peinit turns each one into an operation that is validated, queued, and executed by its event loop. This is what gives concurrent callers — admin tools, automated triggers, dependency propagation — explicit, observable conflict resolution instead of races.

There are five operation types — Start, Stop, Restart, Reload, Reset — and each carries a source recording why peinit created it:

SourceCreated by
AdminA control client.
BootThe Phase 2 boot lifecycle.
ShutdownThe shutdown lifecycle.
DependencyPropagationA start pulling in a dependency.
RestartPolicyAn automatic restart.
TimerA timer firing.
BindsToRecoveryA bound target returning to Active.
BindsToPropagationA bound target stopping.
ConflictResolutionA Conflicts eviction.
OnFailureA failed service's fallback handler.

The source is why a status showing current_operation.source: "restart_policy" tells you the service is being auto-restarted, while "admin" tells you a person asked.

Operation lifecycle #

flowchart LR
    P["Pending"] --> R["Running"]
    R --> C["Completed"]
    R --> F["Failed"]
    R --> A["Aborted"]
    P --> M["Merged"]
    P --> X["Cancelled"]
    P --> F
StateMeaning
PendingValidated and queued, waiting on a precondition (for example a prior stop to finish).
RunningExecuting — the service is transitioning.
CompletedAchieved its goal (start reached Active/Completed; stop reached Inactive/Failed).
FailedDid not achieve its goal — including timing out while still Pending.
MergedFolded into an identical operation already in flight (records the survivor's GUID).
CancelledTerminated while still Pending — never ran.
AbortedTerminated while Running — interrupted in progress.

Cancelled and Aborted are the same idea at two points: canceled never ran, aborted was running. The reason (admin action, supersession) is a property of the event, not the state.

Conflict resolution and merging #

When a command arrives for a service that already has an operation in flight, peinit resolves the collision deterministically — the same logic the command × state matrix summarizes:

  • Same type (start over start, stop over stop, reload over reload) → merge. The new caller transparently receives the existing operation's GUID; from their side, their request is in progress.
  • Stop wins over start. An explicit stop cancels a pending start or aborts a running one. The admin said stop.
  • Later supersedes earlier, and a start while a stop is in flight is queued to run after the stop.

Timeout and retention #

An operation inherits its target's timeout as its maximum lifetime — StartTimeout for start/reload/reset, StopTimeout for stop, and the sum of both legs for restart. Crucially, the clock starts at operation creation, including queue time — from the caller's perspective they have been waiting since they sent the command, so a long queue can time an operation out before it even runs.

Operations are emitted as events (peinit.operation.requested, .started, .ended, and .merged; one .ended covers completed, failed, canceled and aborted, and says which) and terminal ones are dropped from memory after a short grace (default 60 s — long enough for a polling client to read the result). As with jobs, peinit keeps no operation history; eventd does.

Submitted jobs #

A submitted job is a program peinit runs once, under supervision, because a process asked it to — not because a definition in the registry said so. Two situations motivate it:

  • A task on a client's behalf. backupd takes a request from a user, and wants the backup to run as that user, in its own cgroup, with a timeout, reporting progress, visible in job list — but supervised by peinit rather than by backupd itself.
  • A session. A logon service (say, a web front-end) has authenticated a user and wants a long-lived per-logon process running as them, with a socket it can talk to, that it can stop when the session ends.

Both are the same mechanism: a jobs socket at /run/services/peinit/jobs.sock, separate from the control socket. A submitter connects, sends a job definition, and gets back the job's view and — while the job runs — a handle to its process.

Who can submit #

Being able to connect is the permission. peinit performs no access check of its own on a submission; the check is the one the kernel performs against the socket file's security descriptor when a process connects. The default descriptor gives SYSTEM and Administrators full control and Authenticated Users the write right that connecting requires — so out of the box, any logged-on principal can submit, and an administrator narrows or widens that by changing the socket's descriptor, not by configuring peinit.

What limits an over-eager submitter is a quota: at most MaxJobsPerSubmitter live jobs per submitting SID (default 64; SYSTEM is exempt). A submission that would exceed it is refused with QUOTA_EXCEEDED and creates nothing. A job stops counting the moment it ends.

What a job runs as #

A job submitted by svctl runs as your process's own primary token. There is no CLI identity switch. A service can submit with a token it is authorized to convey; the kernel checks that authority, and a token below Impersonation level is refused with BAD_TOKEN. A job needing Delegation must be submitted through a connection already at that level; it cannot be raised later.

The view records both the submitter and the identity the job runs as, plus its logon session. The TRM identity-conveyance reference describes attached tokens.

The definition #

Choose an absolute image path, its arguments and environment, a working directory, and any timeout or readiness settings. A submitted job has no restart policy, dependencies, health check, or trigger; use a service definition if you need those.

Submission returns once the job is running or has failed to start, not when it has finished or signaled readiness. Use --wait to wait for completion or job wait --for ready for a job configured with notify readiness. An accepted submission can still fail at exec, for example because its identity cannot execute the image.

See svctl job options for the CLI and the submission reference for complete fields and descriptor passing.

Who can manage a job #

Every job carries its own security descriptor from the moment it exists. By default it is owned by the submitter and grants JOB_ALL_ACCESS to the submitter, SYSTEM, and Administrators — and to nobody else. In particular the job identity gets nothing: a process running as U cannot see or stop a job that happens to run as U, unless the submitter's descriptor says so. A submitter can supply its own descriptor (in SDDL) and peinit uses it exactly as given — including a descriptor that locks the submitter out of its own job.

RightGrants
JOB_QUERYRead the job view; wait on it; see it in job list.
JOB_STOPStop the job.
JOB_SIGNALSend a signal to the job's main process.

These rights govern both the jobs socket's own commands (status, wait, stop, signal) and the control socket's job-status, job-list, job-stop. As with services, job list filters rather than denies: you see the jobs you hold JOB_QUERY on, while a command naming an existing job you cannot query returns ACCESS_DENIED. UNKNOWN_JOB means the ID is unknown or already discarded.

The job view #

svctl job status <id> reports the job's state and cause, submitter and execution identity, PID, readiness, exit code or signal, and timestamps. Its status text and progress are reported by the program itself; an absent value does not establish that it is stuck.

The TRM job-view reference describes the progress message forms and update limits.

Stopping, timeouts, and the end of a job #

A job ends when its process exits, when its timeout elapses, when its readiness_timeout elapses without READY=1, when someone stops it, or at shutdown. A stop — whichever of those triggers it — is a service stop in miniature: SIGTERM to the main process (skipped if the job already said STOPPING=1), then after stop_timeout a SIGKILL of everything in the job's cgroup, and if that survives, the job is Abandoned after the post-kill grace with cause process_unkillable.

cause records why peinit ended a job, and is null when the process ended of its own accord:

CauseMeaning
parent_setup_failurepeinit could not prepare the launch — no token, no cgroup, no fork. No process existed.
pre_exec_failureSetup between fork and exec failed, or execve did.
readiness_timeoutA notify job never sent READY=1 in time.
timeoutThe job ran longer than timeout.
explicit_stopA stop or job stop was issued.
shutdownThe system was shutting down.
process_unkillableThe process survived SIGKILL.

State follows the exit, not the cause: a stopped job whose process handled SIGTERM and exited 0 is **Completed with cause explicit_stop ** — peinit asked, the process agreed, and both facts are recorded. One that died to the signal is Failed with exit_signal set. A signal command is the raw mechanism, by contrast: SIGKILL sent that way produces a Failed job with a null cause, because peinit did not decide to end it.

A terminal job is retained for 60 seconds — long enough for a submitter polling once a second to read the result — then dropped; after that its GUID answers UNKNOWN_JOB, and the durable record is in eventd.

Shutdown #

At shutdown, every live submitted job is stopped at once, in no particular order — jobs have no dependencies, so there is nothing to order — and a job still queued to launch is canceled with cause shutdown. Shutdown does not complete while a live job remains, bounded by the global ShutdownTimeout like everything else. Submissions during shutdown are refused with INVALID_STATE.

Output #

A job's stdout and stderr are captured and forwarded to eventd tagged with the job's GUID, unconditionally — a submitter cannot turn that off. A submitter that wants a live copy attaches one extra descriptor and sets output: true: peinit then writes each line it reads to that output sink as well. The copy is best-effort — a sink that is not being drained never slows the job or peinit; lines that would block are dropped for the sink only while the independent forwarding to eventd continues, and the drop is reported once per job as a peinit.job.output.dropped event.

Submitted jobs bypass the operation model entirely — there is no service to "start," so the submission creates a job directly. The job is the whole lifecycle.

Where to start #

To create and poll operations from the command line, read Controlling services.

To understand the service states an operation drives a service through, read The service lifecycle.

To query the durable job and operation history, read Auditing.

Defining a Service

Peios / Using Peios / Services and Jobs

Use svctl definition or Services Manager to change a service's configuration. Both check field values before writing them. You need permission to change the service's registry key; permission to start or stop the service is separate.

Start by reading the current definition and runtime state:

svctl definition show sshd
svctl status sshd

A definition lives at Machine\System\Services\<name>. Its typed registry values describe the program, identity, dependencies, triggers, and supervision policy. The name of the key is the name you use in svctl.

Change and verify #

  1. Read the current definition. Decide which field needs to change and when it will apply.
  2. Use svctl definition edit or Edit definition… in Services Manager. Check the reported changes before restarting a running service.
  3. Validate the saved definition with svctl definition validate <service>. This checks fields; identity, privilege names, and dependency targets also need their runtime checks.
  4. If launch settings require it, restart the service during an appropriate interruption window. svctl reload-config re-reads definitions but does not replace a running process.
  5. Run svctl status <service> again. If it fails, inspect the cause and logs.

Warning

A definition controls what runs and under which identity. Keep definition-write access limited to trusted administrators. Grant runtime start/stop rights through ServiceSecurity, rather than giving an operator permission to rewrite the program or its identity.

Creating and changing a definition #

A definition is a registry key, so reg can write one. Two tools also know what each field means, and check a definition before writing it.

From a terminal: svctl definition #

svctl definition show sshd
svctl definition validate sshd
svctl definition create web --set ImagePath=/usr/bin/web --set Requires=lpsd --set Requires=netd:routed
svctl definition edit web --set StopTimeout=20 --unset Wants

def is short for definition.

  • Fields go by their registry names, in any case.
  • Values are given as text:
    • a number as digits;
    • yes or no;
    • a choice by its name (Type=Oneshot);
    • a list with one --set for each item, in order.
  • A change is checked first, as peinit checks it. It goes through peinit's own decoder, and every timer: schedule is parsed. If peinit would reject it, nothing is written and you are told why.
  • Only the values that change are written, in one registry transaction. If one of them has changed since svctl read it, nothing is written.
  • Values that are not fields are kept as they are.
  • edit names any changed fields that wait for a restart on a running service. See the mutability classes.

Some things can't be checked until later:

  • privilege names, when the token is made;
  • whether the services a definition names exist, when the graph is built;
  • the identity, by authd.

svctl status after the change is the final word.

Manager #

In Services Manager, Edit definition… opens the selected service's definition in a window of its own. It's in the details pane and on each row's right-select menu. It reads Definition… when you can only read the definition. New service… on the bar defines a new one. A service's definition opens in one window at a time: while it is open, Edit definition… is unavailable for that service.

  • Every field is shown, by group. Each has its name in words with the registry name beside it, its default, and when a change takes effect.

  • What you type is checked when you leave the field, as peinit checks it. Anything wrong is said beside the field, and Save stays unavailable until it is put right.

  • Each timer's schedule says when it next comes round, under Triggers, in local time. A schedule that never comes round, such as *-02-30, is marked as one that never starts the service. peinit takes such a definition and arms its other timers, so it does not stop you saving. These times are the schedule's, before any jitter. When the timer will really fire is in the details pane, once it is saved (see Controlling services).

  • Save writes as svctl does, from the button or with Ctrl+S. Only the changes are written, in one transaction, and it is refused if someone else changed a value meanwhile. Revert reads the definition again. If the service is running, Save says which changes wait for a restart.

  • Delete… asks first. A running service carries on until it stops.

  • What you can do is asked of the registry:

    • changing needs the right to set values on the service's key;
    • defining a service needs the right to create keys under Machine\System\Services;
    • deleting needs DELETE on the key.

    Without those rights, the definition is shown with every field fixed and the reason said.

  • Who can control the service (ServiceSecurity) is changed with Who can control it…, not here. See Who can manage a service.

Field mutability: when a change takes effect #

Every field falls into one of four mutability classes. This table is the one to keep handy.

ClassWhen a change takes effectFields
Immutable at runtimeNext restart only.ImagePath, Type, Identity, RequiredPrivileges, ErrorControl, RemainAfterExit, and, while it is running, Triggers and Disabled
Apply on next startNext start or explicit graph reload — not while running.Requires, Wants, BindsTo, Conflicts, OnFailure, Conditions, Asserts
Hot-reloadedNext relevant event, no restart.ServiceSecurity (next control request)
Reloadable at runtimeNext relevant operation (start, health-check cycle, …). Launch settings apply to the next process, not the current one.Arguments, SuccessExitCodes, all timeout/retry values, the health-check fields, RestartPolicy, Environment, WorkingDirectory, the hooks and HookIdentity, Readiness, NotifyAccess, LimitNOFILE/LimitCORE, FdStoreMax, TTYPath/TTYPrecedence, RuntimeDirectories, Provides, TimerPersistent/TimerJitter, SafeMode, DisplayName, Description

On a service that is not running, Triggers and Disabled take effect as soon as peinit has read the change: that is what arms a timer added to an inactive service.

The practical reading: changing what a process is or runs as (ImagePath, Identity, Type, privileges, ErrorControl) is fundamental enough that it only applies when a fresh process starts — you must restart. Changing policy that peinit consults each time it acts (timeouts, restart behavior, health checks) is picked up the next time peinit acts. And ServiceSecurity is special: it is re-read on every control request, so an access-control change takes effect on the very next command without touching the running service.

Environment, Arguments, WorkingDirectory, and process limits do not alter an already-running process. Even though peinit can reload those fields, the process receives them only on its next start.

For inactive services the rules are simpler, because there is no running process to protect: a new service entry becomes available once the change notification is processed; a changed timer arms on the next evaluation; a changed dependency takes effect on the next start.

Note

reload-config is the explicit, atomic way to make peinit re-read everything. It builds and validates a complete new graph snapshot and swaps it in only if validation passes; running services are not disturbed. It is covered with the rest of the command set in Controlling services.

Removing a service definition #

Use svctl definition delete web only when you intend to remove the definition of web. To stop its current work, use svctl stop web instead.

Deleting a definition from the registry does not kill a running instance. peinit learns of the removal through the same notification path and behaves according to whether the service is running:

  • Not running (Inactive, Failed, Completed, Skipped, Abandoned, Backoff): peinit discards the in-memory entry immediately. There is nothing to supervise.
  • Running (Active, Starting, Reloading, Stopping): the running process is a job, and a job outlives its definition. peinit marks the entry definition-removed, keeps the cached definition only to finish supervising the existing instance, and does not restart it when it exits. Once it exits, the entry — and any stored fds — are discarded.

A removal that leaves a dangling hard dependency does not apply: peinit refuses the configuration read with MissingHardDependency. Remove or update the dependent definitions first. A definition-removed entry therefore has no dependents.

For a definition-removed entry, stop still works so you can drain it cleanly, but start, restart, and reload are rejected with UNKNOWN_SERVICE — there is no definition to start from. A status query reports it with a definition_removed: true flag so the draining instance is never invisible.

Important

Removing a definition is not how you stop a service. It stops future management, not work in progress. To actually stop a running service, stop it. To prevent it from auto-starting, set Disabled=1 (see Triggers and timers). To prevent it from being started at all, deny SERVICE_START in its ServiceSecurity descriptor.

Service names #

A service name must be made of characters from [A-Za-z0-9._-] and be 1–128 bytes long. Anything else is a validation error. Two characters are pointedly excluded:

  • / — names map directly onto cgroup ids and registry key names, and a slash would be ambiguous in both.
  • : — reserved for peinit-internal synthetic names (for example, the way a hook job is labeled).

The name is how you refer to the service everywhere: in svctl commands, in another service's dependency list, in a ServiceSecurity descriptor, and in the per-service SID derived from it.

The definition schema #

A definition is a set of typed registry values. Rather than list all of them in one wall of rows, the tables below group the fields by what they are for, with a pointer to the page that explains each group in depth. Every field is optional unless noted; the only hard requirement is ImagePath. The full type-and-default catalog lives in the Registry key reference.

What to run — the binary and its execution context.

FieldDefaultPurpose
ImagePath (required)—Absolute path to the service binary.
Arguments—Argument list passed to the binary.
WorkingDirectory/Working directory for the process.
Environment—KEY=VALUE pairs added to the environment.
RuntimeDirectories—Private directories created under /run immediately before the process starts. See The execution environment.
LimitNOFILE, LimitCORE—RLIMIT_NOFILE / RLIMIT_CORE.

What kind of service — type and readiness. See Simple and Oneshot services.

FieldDefaultPurpose
TypeSimpleSimple (long-running) or Oneshot (run-to-completion).
ReadinessNotifyNotify (READY=1 through sd_notify) or Alive (ready when the process exists). Ignored for Oneshot.
RemainAfterExit0Oneshot only — stay in Completed after a successful exit.
SuccessExitCodes—Non-zero exit codes to treat as success.

When to start — triggers and conditions. See Triggers and timers.

FieldDefaultPurpose
Triggers—boot, boot:settled, timer:<schedule>, tty:released. Absent = demand-only.
Disabled0If 1, triggers must not activate the service (manual start still allowed).
SafeMode0Eligible within the boot-triggered set in Safe mode; does not add a boot trigger.
Conditions, Asserts—Start-time checks. A failed condition skips; a failed assert fails.

Who it runs as — identity and privileges. See Service identity and privileges.

FieldDefaultPurpose
IdentityLocalServicePrincipal name, SID, or Service for a distinct virtual service account.
RequiredPrivileges—Privilege allow-list; everything else is stripped from the token.
HookIdentityservice's IdentityIdentity for ExecStartPre/ExecStartPost hooks.

How it relates to other services — dependencies. See Dependencies and ordering.

FieldPurpose
RequiresHard dependencies — must be satisfied first; their failure fails this service.
WantsSoft dependencies — attempted first if present and enabled, but their failure does not block this service.
BindsToRuntime coupling — if the target stops, this stops too.
ConflictsMutual exclusion — starting this stops the named services.
OnFailureService to start when this one enters Failed.

How it is kept alive — supervision and health. See Keeping services running.

FieldDefaultPurpose
ErrorControlNormalNormal (stay Failed) or Critical (sync + reboot on irrecoverable failure).
RestartPolicyOnFailureNever / OnFailure / Always.
RestartMaxRetries, RestartWindow, RestartDelay5 / 120 / 1Restart budget, the window of health that resets it, and the backoff base.
HealthCheck, HealthCheckInterval, HealthCheckTimeout, HealthCheckRetries— / 30 / 5 / 3Active health-check command and its timing.
WatchdogTimeout0Expected interval between WATCHDOG=1 pings; 0 disables.

The transition phases — hooks and timeouts. See The execution environment and The service lifecycle.

FieldDefaultPurpose
ExecStartPre, ExecStartPost—Commands run before the binary / after readiness.
ExecReload(SIGHUP)Reload command or signal:<NAME>.
StartTimeout, StopTimeout30 / 10Seconds for the whole start sequence / between SIGTERM and SIGKILL.

The remaining knobs — scheduling, notify, fds, metadata.

FieldDefaultPurpose
TimerPersistent, TimerJitter1 / 0Catch up missed timer runs after reboot / random delay per firing.
NotifyAccessMainWho can send sd_notify messages (only Main is supported).
FdStoreMax0Size of the per-service fd store; 0 disables it.
ServiceSecurityinheritSecurity descriptor controlling who can manage the service.
DisplayName, Description—Human-readable labels for status output.

Forward compatibility #

The schema version lives at Machine\System\Services\SchemaVersion ( 1). peinit is deliberately forward-compatible:

  • Unknown values are ignored. A definition written for a newer peinit does not break an older one.
  • A newer schema version does not block boot. peinit logs a warning and continues.
  • The schema only grows. New capability arrives as new optional fields, never as a breaking change to an existing one.

One defensive rule cuts the other way: a known field must not appear more than once in a collected definition. A duplicated known field is a validation error, even though the registry would ordinarily give you at most one value per name.

peinit works from a snapshot, not the live registry #

Here is the idea that explains most surprises. peinit does not re-read the registry every time it touches a service. It reads definitions at well-defined moments and operates on an in-memory model in between.

Two layers of snapshotting stack on top of each other:

  • Boot generation. At the start of boot, peinit reads all definitions, builds the dependency graph, and validates it. The whole boot runs against that one snapshot. Changes made during boot — by an install script, a post-hook — do not perturb the boot in progress.
  • Activation generation. When peinit starts a specific service, it snapshots that service's definition for the entire start. Pre-exec hooks, the token request, the readiness timeout, the first health checks — all use the values captured at activation. Edit a field while the service is Starting, and the edit waits for the next start.

peinit learns about registry edits through change notifications: it subscribes to Machine\System\Services\ and Machine\System\Init\ at boot, and processes events in its event loop at a time of its choosing. If the notification queue overflows — a bulk admin operation, a flurry of scripted writes — peinit detects the overflow marker and does a full reload-config to resynchronise. You never have to think about the queue; you do have to know that a change is picked up, not pushed, and that when it takes effect depends on the field.

Where to start #

To understand the Type and Readiness fields and the Simple/Oneshot split, read Simple and Oneshot services.

To understand how a definition becomes a running, supervised process — and what each state in a status output means — read The service lifecycle.

For the complete type-and-default catalog of every registry key peinit reads, see the Registry key reference.

Simple and Oneshot Services

Peios / Using Peios / Services and Jobs

Choose Simple for a program that stays running and Oneshot for a task that should finish. Then check how it reports success: a Simple service becomes ready through Notify or Alive; a Oneshot succeeds by exiting successfully.

The default is Type=Simple with Readiness=Notify. Before starting a new definition, make sure the program can send READY=1 from its main process. A program that never sends it will time out even if its process is alive. Keep daemons in the foreground; peinit does not follow a double-forked replacement process.

Oneshot #

SimpleOneshot
Process lifetimeLong-running; is the serviceRuns once, exits
ReadinessNotify (READY=1) or AliveSuccessful exit — Readiness ignored
Satisfies dependents whenActiveCompleted (with or without RemainAfterExit)
Successful end stateActive (until stopped)Completed, then Inactive (unless RemainAfterExit=1)
ExecStartPost firesAfter readinessAfter successful exit only
StartTimeout coversStartup until readinessThe whole execution
Watchdog and health checksSupervised while ActiveNone — WatchdogTimeout/HealthCheck are inert
Restart on successn/aNever (use a timer to re-run)

Simple services #

A Simple service is a long-running daemon. peinit forks, installs the token, and execs the binary. The process is the service: while it runs, the service is running; when it exits, the service has stopped. This is the default and covers the large majority of services — registryd, authd, sshd, application daemons.

The interesting question for a Simple service is when does it count as started — the moment its dependents are allowed to begin. That is the readiness model, set by the Readiness field.

Alive #

ReadinessReady when…Use for
Notify (default)The service sends READY=1 through sd_notify.Any service that has meaningful startup work — opening a socket, loading state, connecting to a backend. The dependent genuinely should wait.
AliveThe process exists — readiness is immediate.Services with no startup handshake, where "the process is up" is as good a signal as you will get.

The distinction matters because it is a promise to dependents. With Notify, a service that declares itself a Requires target is telling peinit "do not start anything that needs me until I say READY=1." With Alive, peinit can only promise that the process was forked — not that it is functional.

Warning

Using Readiness=Alive on a service that other services Requires is a common configuration smell. peinit will let it boot, but it logs a validation warning: Alive readiness gives no guarantee the service is actually serving before its dependents start. If a dependent connects on boot and gets connection-refused, this is usually why. Prefer Notify wherever the service can signal it.

Once ready, a Simple service transitions to Active and stays there until its process exits or it is stopped. What happens on exit — clean exit, crash, restart — is the subject of The service lifecycle and Keeping services running.

Oneshot services #

A Oneshot service is a run-to-completion task. peinit forks, installs the token, execs the binary, and waits for it to exit. It is the right type for setup work: creating directories, initializing a database, running a schema migration, applying a one-time fixup at boot.

For a Oneshot, readiness is exit, not a signal. The Readiness field is ignored entirely — READY=1 is meaningless for a process whose whole job is to finish. Success and failure are decided by the exit code:

  • Exit 0 (or any code listed in SuccessExitCodes) → the service succeeded.
  • Any other exit, or death by signal → the service failed, and the failure policy applies.

SuccessExitCodes is for binaries that signal a meaningful outcome with a non-zero code — for example, a tool that exits 2 to mean "nothing to do." Each entry is a decimal 0 –255; code 0 is always success and need not be listed.

Completed, and RemainAfterExit #

A successful Oneshot transitions to Completed, and what happens next depends on RemainAfterExit:

RemainAfterExitAfter a successful exit
0 (default)The service passes through Completed — releasing its dependents — then transitions to Inactive.
1The service stays in Completed.

Both forms satisfy dependents; the only difference is what a later status query shows. Use RemainAfterExit=1 when "this task is done" is a state worth seeing — a boot-time migration you want to confirm ran, say — rather than a service that quietly returns to Inactive.

Oneshot timing and hooks #

Two details distinguish a Oneshot's start sequence from a Simple one:

  • StartTimeout covers the entire run. For a Simple service the timeout covers startup until readiness; for a Oneshot it covers everything from the first pre-hook to process exit. A long-running Oneshot must raise StartTimeout accordingly (or send EXTEND_TIMEOUT_USEC as it works — see Keeping services running).
  • ExecStartPost runs only on success. Post-hooks fire after the successful exit. If the Oneshot fails, ExecStartPost does not run.

Oneshot #

A Oneshot is not restarted on success, regardless of RestartPolicy — even Always. A successful exit is the goal, not a failure to retry. RestartPolicy governs only the response to failure (a non-zero exit). To re-run a Oneshot on a schedule, give it a timer trigger; that is the intended mechanism.

No forking daemons #

peinit does not support services that double-fork to background themselves. The whole reason a traditional daemon double-forks — to detach from the launcher — is moot when the launcher tracks the process it spawned. peinit obtains a pidfd for every process at fork time, which is a kernel handle to that exact process, immune to PID-reuse races. There is no MAINPID= mechanism for a service to redirect supervision onto a different process; peinit supervises what it forked.

If a legacy binary insists on daemonising, the fix lives at the package build — wrap it so it stays in the foreground (commonly a --no-daemon /--foreground flag) — not at the init layer.

The sd_notify contract #

A Notify-readiness service signals readiness by sending READY=1 over the sd_notify protocol — a datagram to the socket named in the NOTIFY_SOCKET environment variable, which peinit sets for every service. READY=1 is only the most visible message; the same channel carries watchdog keepalives (WATCHDOG=1), graceful-stop notice (STOPPING=1), timeout extensions (EXTEND_TIMEOUT_USEC), status strings (STATUS=), and the fd store. These are covered where they belong — readiness here, the rest in Keeping services running and Controlling services.

Readiness is always per start generation. A READY=1 left over from a previous incarnation of the process is never valid for the current start — peinit ties every notify message to the specific process it is supervising, verified by pidfd.

Who is allowed to send these messages is governed by NotifyAccess, which has a single value: Main (0, the default). Under Main, only the tracked main PID — the process peinit forked and supervises — is authorized to send sd_notify readiness and status messages; a message arriving from any other PID (a child, a helper, an unrelated process) is ignored. So if a worker your service spawns sends READY=1, peinit will not act on it — the readiness signal must come from the main process itself.

Where to start #

To control when either type of service starts, read Triggers and timers.

To follow a service from definition to running process and read its states, read The service lifecycle.

To configure restart, health checks, and watchdogs for a Simple service, read Keeping services running.

Triggers and Timers

Peios / Using Peios / Services and Jobs

To see when a scheduled service will run, use svctl status <service> or the Next run column in Services Manager. To change automatic starts, edit the definition's Triggers field. A saved schedule is not evidence that a timer is armed; check status after saving it.

A trigger decides when the service starts on its own. It is independent of service type: boot and timer triggers can start either Simple or Oneshot services. Each entry in Triggers is written type or type:argument.

TriggerFormMeaning
BootbootStart during Phase 2, in dependency order.
Settled bootboot:settledStart after the boot set settles, with a bounded wait; useful for console prompts.
Terminal handovertty:releasedStart when the terminal named in TTYPath is released.
Timertimer:<schedule>Start on a calendar schedule.

Without triggers, the service is demand-only: it starts through a control command or because another service needs it. To prevent automatic activation while keeping manual start, use Disabled.

Seeing when a timer runs #

peinit reports each timer as it has it armed, in the service's status:

  • the schedule's next occurrence;
  • when the timer will actually fire, with its jitter added;
  • when it last fired.

A schedule peinit refused, such as *-02-30, which never comes round, is reported with the reason, rather than left out.

$ svctl status logrotate
...
timers:
  *-*-* 02:00:00
    next: 2026-06-02T02:00:00Z, firing at 2026-06-02T02:07:12Z after jitter
    last fired: 2026-06-01T02:03:40Z

svctl list has a NEXT TIMER column, with each service's soonest firing. On the desktop, Services Manager shows the same things in local time: a Next run column, and each timer in the details pane. See Controlling services for the fields.

These times are peinit's own. Jitter is drawn at random each time a timer is armed, so the time a timer fires can't be worked out from its definition.

Disabled #

Disabled=1 suppresses automatic activation. A disabled service will not be started by any trigger — boot, timer, terminal handover, or anything added later — but it can still be started by hand through the control interface. It is the switch for "configured, but not running on its own right now."

Two related controls are easy to confuse with it:

To…Use
Stop a service from auto-starting, but keep manual startDisabled=1
Stop a service from being started at all, even manuallyDeny SERVICE_START in its ServiceSecurity descriptor
Stop a running serviceThe stop command

Enabling and disabling are registry writes performed by admin tooling, not peinit commands. peinit picks up a Disabled change through a registry notification or on reload-config. A disabled service's definition is still loaded into peinit's model, so it is ready for an on-demand start the instant you ask.

Calendar expressions #

Timer schedules are written in systemd's OnCalendar format. peinit's grammar is normative and self-contained — what follows is the whole language. The general shape is:

DayOfWeek Year-Month-Day Hour:Minute:Second Timezone

Every field is optional and has a default, so most real schedules are short.

FieldFormIf omitted
DayOfWeekweekday name(s)any day (*)
DateYear-Month-Day*-*-* (any date)
TimeHour:Minute:Second00:00:00
Secondthe :Second of Time:00
TimezoneIANA zone namesystem-local time

So 02:00:00 is a complete expression — date defaults to every day, and it means "every day at 02:00." Hour:Minute with no seconds defaults the seconds to 00.

Component syntax #

Each numeric component — year, month, day, hour, minute, second — and the weekday accept the same operators:

OperatorExampleMatches
Wildcard*any value
List1,15any listed value
RangeMon..Fri, 8..17the inclusive range
Repetition0/150, then every multiple of the step — 0, 15, 30, 45
Range + step8..17/28, 10, 12, … up to and including 17

Weekdays are English names, case-insensitive, abbreviated (Mon) or full (Monday), and take lists and ranges.

Last day of the month #

A ~ in place of the - between Month and Day counts the day from the end of the month: ~01 is the last day, ~02 the second-to-last, and so on. So *-*~01 is the last day of every month. Repetition combines with it — Mon *-05~07/1 is "the last Monday in May."

Named shortcuts #

These stand in for the expression shown:

ShortcutEquivalent
minutely*-*-* *:*:00
hourly*-*-* *:00:00
daily*-*-* 00:00:00
weeklyMon *-*-* 00:00:00
monthly*-*-01 00:00:00
quarterly*-01,04,07,10-01 00:00:00
semiannually*-01,07-01 00:00:00
yearly / annually*-01-01 00:00:00

Timezones and precision #

A timezone specifier follows the IANA database — Europe/London, US/Eastern, UTC. With none, the expression is interpreted in system-local time.

Precision is second-level. Unlike systemd, peinit does not accept sub-second fractions; a fractional second is a parse error. Service scheduling has no use for finer granularity.

Examples #

ExpressionMeaning
*-*-* 02:00:00Every day at 2 am (system-local)
Mon *-*-* 00:00:00Every Monday at midnight
*-*-1,15 12:00:001st and 15th of each month at noon
*-*~01 00:00:00Last day of each month at midnight
Mon..Fri *-*-* 09:00:00Weekdays at 9 am
*-*-* *:00/15:00Every 15 minutes
*-*-* 02:00:00 Europe/LondonEvery day at 2 am London time

What happens when a timer fires #

A timer firing does not blindly start the service — peinit considers the service's current state first, so a firing never collides with a run already in progress.

TypeCurrent stateAction
OneshotInactive / Completed / FailedStart it (operation source Timer).
OneshotActive / StartingSet a single pending flag — one catch-up run when the current one finishes.
SimpleInactive / FailedStart it.
SimpleActive / StartingNo-op; the firing is logged.

The Oneshot "pending" flag is deliberately not a queue: many firings that land while a Oneshot is busy collapse into one catch-up run, taken when the current run ends. A service cannot stampede itself.

That single flag is shared across all of a Oneshot's timers, not one per timer. If a Oneshot has several timer triggers and two of them fire while it is busy, at most one run is still pending when the current one finishes. The timers are otherwise fully independent — each keeps its own next-firing time and its own last-run timestamp — but they can only ever queue up a single shared catch-up between them.

Each timer firing creates a normal start operation, so a timer-started service is observable exactly like an admin-started one — same GUIDs, same events.

Persistent timers and catch-up #

TimerPersistent (default 1) controls whether runs missed while the machine was off are caught up after a reboot.

peinit records the last-run timestamp of each timer in the registry. On boot, for each persistent timer it reads that timestamp, computes the next firing after it, and — if that time is already in the past — fires once, immediately, then resumes the normal schedule.

The catch-up is always a single run, never one-per-missed-occurrence. A daily timer that was off for five days fires once on the next boot, not five times. A non-persistent timer (TimerPersistent=0) ignores history entirely and computes its next future firing from now.

One subtlety worth knowing: the last-run timestamp is keyed by the schedule string. If you change a timer's schedule, the old timestamp is orphaned and the new schedule has no history, which causes exactly one spurious catch-up run. Schedule changes are rare and the cost is one extra run, so peinit accepts it rather than tracking trigger identity.

Note

The timestamp is written when the timer fires and the start is initiated, not when the run completes. A service that crashes mid-run is not re-triggered on the next boot — the run was attempted, not missed.

Jitter #

TimerJitter (default 0) adds a random delay of 0 to TimerJitter seconds to each firing, recomputed every time. A timer scheduled for midnight with TimerJitter=900 fires at a slightly different moment between 00:00 and 00:15 each day. Jitter only ever delays — a timer never fires before its scheduled time. It is the standard remedy for a fleet of machines all hammering the same backend at exactly midnight.

When the clock jumps #

Calendar timers are wall-clock schedules: *-*-* 02:00:00 means "02:00 on the wall," not "every 86,400 seconds." peinit arms them as absolute real-time timers that are canceled and recomputed whenever the system clock is stepped, so the schedule stays anchored to the wall clock across corrections.

EventBehavior
NTP step or manual clock setArmed calendar timers are canceled and recomputed against the new wall clock. A backward step pushes the next firing later; a forward step that crosses a missed time fires it once.
Suspend / resumeA scheduled time that elapsed while suspended fires once on resume — once, not once per missed occurrence.
A missed occurrence within one uptimeFire once, then resume the normal schedule. peinit never replays every occurrence in the gap.
Daylight-saving transition (timezone-aware timer only)A scheduled time in the skipped hour never fires; a scheduled time in the repeated hour fires once. See below.

Daylight-saving is the case most likely to surprise you, and it only affects timers that name an IANA zone that observes DST (a bare 02:30:00 in system-local time follows whatever the system does). For a scheduled local time inside the affected hour:

  • Spring forward — that time does not exist on the transition day. The timer does not fire for that occurrence; it resumes at the next valid occurrence.
  • Fall back — that time occurs twice. The timer fires exactly once, on the first occurrence.

This is distinct from peinit's interval timers — the watchdog, health-check intervals, restart backoff, and the start/stop/reload phase timeouts. Those are genuine durations measured on the monotonic clock, so "wait 30 seconds" means 30 elapsed seconds and never lurches when the wall clock is set.

There is one boot-time case worth calling out on its own. When peinit reads a timer's stored last-run timestamp at boot and finds it is in the future relative to the current wall clock — meaning the clock has gone backwards since that run — it can't trust the timestamp, so it treats the timer as having an unknown last run and fires the persistent catch-up immediately. This only applies to the boot-time check; the runtime handling above is unaffected.

Caution

If a machine boots with a wildly wrong clock (a dead RTC battery) and NTP corrects it only later, the boot-time persistent catch-up decision is made against the wrong time and can fire spuriously or not at all. The runtime half self-heals once NTP steps the clock, but the boot-time decision is already made by then. This is a known edge case short of NTP-aware rescheduling — worth knowing if you run timers on hardware with unreliable clocks.

Waiting for the boot to settle #

boot:settled is boot with one difference: the service starts once the Phase 2 boot set has stopped moving — every service in it reached a state it will not leave on its own — rather than during it.

It exists for services that write to a terminal. peinit reports its progress to /dev/console, and a service holding that same terminal writes there too, so a prompt started mid-boot gets written over: login emits Username: with no newline and waits, peinit appends a service line, and the result is unreadable until you press Enter and the login program redraws.

The wait is capped (Machine\System\Boot\SettleTimeout, 5 seconds by default). A service stuck in Starting therefore costs a deferred service a short delay rather than preventing it — which matters most exactly when something is broken and a console prompt is what you need.

A boot:settled service is deliberately not part of the boot plan. It does not consume the parallel-start budget, is not counted toward boot success, and cannot block another service. Waiting for quiet is a preference; it must not change what the boot means.

Note

Reach for this only to keep console output legible. If a service genuinely needs something to be running first, that is a dependency — say so with Requires . A console sign-in service uses both: boot:settled for when, and Requires on its authority for what must be true.

Queueing for a terminal #

A terminal has one owner at a time. Two services writing to the same TTYPath do not fail — they interleave, which on a console means a sign-in prompt with a progress line through the middle of it. So peinit gives the device to one of them and skips the rest, and tty:released is how the ones that were skipped get their turn.

The whole arrangement is three fields. A first-boot setup flow and a sign-in prompt, both on the console:

ServiceTTYPathTTYPrecedenceTriggers
oobe/dev/console100boot:settled
login-console/dev/console(0)boot:settled, tty:released

On a first boot both are deferred, oobe outranks the sign-in prompt on TTYPrecedence, so oobe takes the console and login-console is skipped with cause TtyUnavailable. When oobe finishes — or crashes, or is stopped; all three free the device — tty:released starts the sign-in prompt. On every later boot oobe is gone, nothing is holding the console, and the sign-in prompt starts straight away.

A few rules worth knowing:

  • Higher TTYPrecedence wins, and equal precedence breaks on service name, so the outcome is the same on every boot. The default is 0.
  • Nobody is preempted. Precedence decides between services starting at the same moment; a service already using a terminal keeps it.
  • A service that stops is not offered its own terminal back. Relaunching it is RestartPolicy's job, not this.
  • Both fields need a TTYPath. tty:released or TTYPrecedence without one is rejected when the definition is read, rather than quietly doing nothing.
  • tty:released on its own starts nothing until somebody takes the terminal and lets it go. Give a service that must come up either way a boot or boot:settled trigger as well, as login-console has above — otherwise a machine with no oobe installed never gets a sign-in prompt.

Being skipped is not a failure: a skipped service satisfies anything that depends on it, exactly as a service skipped by a Conditions entry does.

Note

This is deliberately not Conflicts, which fails both services — and the services that want a terminal are the interactive ones, so that answer is a machine you cannot sign in to. It is not a dependency either: a sign-in prompt does not need first-boot setup to have run, it needs the console to be free.

You can list more than one trigger, including more than one of the same type. ["timer:*-*-* 02:00:00", "timer:*-*-* 14:00:00"] runs at 2 am and 2 pm. The model is built to grow — future trigger types (path, device, event) will slot into the same list without a schema change.

Where to start #

To see how a timer-started run appears as a job and an operation, read Jobs and operations.

To understand the states a timer-started service moves through, read The service lifecycle.

For the exact registry keys that store last-run timestamps, see the Registry key reference.

Keeping Services Running

Peios / Using Peios / Services and Jobs

When a service keeps restarting, check its state, cause, and logs before changing the restart policy. Backoff means peinit is waiting to retry; Failed with RestartBudgetExhausted means the retry budget ran out.

Use the policy reference below to distinguish a program failure from a failing health check or watchdog. Preserve the underlying error while you investigate. Increasing a timeout or retry count can change when the failure appears without fixing it.

Warning

On an ErrorControl=Critical service, exhausting the restart budget causes an immediate sync and reboot. A bad health check can therefore reboot the machine repeatedly. Confirm console recovery access before changing supervision of a Critical service.

Restart policy #

When a service fails in a way that might be transient, peinit consults RestartPolicy:

PolicyValueBehavior
Never0Never restart. The service goes straight to Failed.
OnFailure (default)1Restart on a crash or runtime failure. An exit code in SuccessExitCodes is not a failure and is not restarted.
Always2Restart on any failure, and — for a Simple service — restart even a successful clean exit (see clean exits).

Not every failure is restart-eligible. peinit splits causes into three groups:

  • Restart-eligible — peinit consults the policy and budget: ProcessCrash , WatchdogTimeout, HealthCheckFailure, ReadinessTimeout, PreHookFailure, PreExecFailure, ParentSetupFailure. (The startup failures are eligible on purpose — a pre-hook that failed on a momentarily-missing mount deserves another try.)
  • Never restarted — retrying cannot help: an explicit stop or reset, shutdown, conflict eviction, a broken definition (ValidationError, CycleDetected, DependencyFailure, AssertionError), an already-exhausted budget, or an unkillable process.
  • Budget-exempt — BindsToRecovery, where a bound service came back and its dependents are revived. The dependent did not fail on its own, so this restart does not count against its budget.

The budget and backoff #

Restarting an instantly-crashing service in a tight loop is worse than useless, so every restart is throttled by two mechanisms working together.

Exponential backoff. Before each restart the service sits in the Backoff state for a delay that doubles on each consecutive failure, starting from RestartDelay (default 1 s) and capped at 60 s. So a crash-looping service backs off 1 s, 2 s, 4 s, 8 s, … up to a minute between attempts.

The budget. A consecutive-failure counter tracks how many times the service has failed in a row. Once it reaches RestartMaxRetries (default 5), the next failure is not restarted: the service transitions to Failed with cause RestartBudgetExhausted.

The reset. The counter resets to zero once the service stays Active for RestartWindow seconds (default 120) without failing. This is the crucial detail: the budget is not "N restarts ever" — it is "N restarts faster than the service can sustain RestartWindow of health." A service that crashes once a day and recovers cleanly each time never exhausts its budget, because every crash starts from a counter of zero. Only failures recurring faster than the service can stay healthy accumulate.

flowchart LR
    A["Active"] -->|crash| B{"budget left?"}
    B -->|yes| C["Backoff<br/>delay doubles"]
    C -->|delay elapsed| D["Starting"]
    D -->|ready, stays Active<br/>RestartWindow| A
    B -->|no| E["Failed<br/>RestartBudgetExhausted"]

Tip

If a service flaps — restarting endlessly without ever sticking — and never hits its budget, check whether it stays Active for the full RestartWindow between failures. Merely reaching Active does not reset the counter. Check the health-command output too; the health-check timing constraint prevents one common form of restart loop.

Clean exits #

For a Simple service, exiting with code 0 (or a SuccessExitCodes match) is success, not a crash — a daemon chose to quit. What peinit does next depends on the policy:

  • Under Never or OnFailure, the cause is CleanExit and the service goes straight to Inactive, with no restart-policy consultation at all.
  • Under Always, the cause is CleanExitRestart and the service is restarted — but through the same backoff and budget as a failure, so a daemon that exits cleanly in a tight loop cannot bypass throttling. Logs and status make clear it exited successfully and was restarted only because the policy is Always.

A terminal-attached Simple service is an exception: a successful exit with RestartPolicy=Always is treated as a normal logout. It resets the failure counter and restarts at the base delay, capped at 60 seconds, without using the crash budget. Failures still use the ordinary budget.

(A Oneshot clean exit is never restart-eligible regardless of policy — see service types.)

Health checks #

A live process is not always a working one — it can lose its database connection, wedge in a bad state, or return errors while still "up." An active health check closes that gap by running a command periodically and treating its exit code as a verdict: 0 is healthy, non-zero is a failure.

Health checks apply to Simple services only. peinit starts a service's health-check timer once the service becomes Active; a Oneshot has no long-running process to probe, so it never has one. HealthCheck and its companion fields are inert on a Oneshot — no timer is started — so don't set them there expecting supervision.

FieldDefaultControls
HealthCheck—The command to run (runs under the service's own token).
HealthCheckInterval30Seconds between runs.
HealthCheckTimeout5Seconds before a check is killed and counted as failed.
HealthCheckRetries3Consecutive failures before the service is declared unhealthy.

HealthCheckRetries consecutive failures mark the service unhealthy and restart it through the normal restart policy — backoff and budget included. A single success resets the failure count. If a check is still running when the next interval fires, the new one is skipped rather than stacked.

The health field in a status response reflects this: healthy, unhealthy (failing but not yet failed out), unknown (configured, no result yet), or null (no health check).

The flap guardrail. Health-check throttling only works if a failure cycle is shorter than the restart window — otherwise the counter resets between failures and the service restarts forever. peinit enforces this at validation time as a hard rule:

HealthCheckRetries × HealthCheckInterval < RestartWindow

A definition that violates it is a validation error, not a warning — the service is marked Failed with ValidationError rather than allowed to restart indefinitely.

Caution

Be extremely cautious with health checks on ErrorControl=Critical services. A false-positive health-check failure on a Critical service will, after exhausting the restart budget, reboot the machine — and a flaky check can do this repeatedly. Critical platform services are better served by a passive watchdog with a generous timeout: the service itself knows whether it is healthy and stops sending keepalives if not. peinit applies the same health-check semantics to Critical services as to any other — there is no special-casing to save you.

A health check stuck in D-state is handled like any other stuck helper: its sub-cgroup is leaked and surfaced as a warning, but — unlike a stuck main process — it does not push the service to Abandoned. A health check holds no service resources; it is only a probe.

The watchdog #

The watchdog inverts the health check: instead of peinit asking the service if it is alive, the service must periodically tell peinit. Set WatchdogTimeout (seconds; 0 disables) and the service must send WATCHDOG=1 through sd_notify at least that often. Miss the deadline and peinit treats it as a failure (cause WatchdogTimeout) and applies the restart policy.

Like health checks, the watchdog is a Simple-only supervision mechanism. peinit arms the watchdog timer only once a Simple service becomes Active; on a Oneshot WatchdogTimeout is inert — no timer is started, and setting it changes nothing.

A service can adjust its own watchdog at runtime by sending WATCHDOG_USEC=<microseconds>: a positive value re-arms the timer with the new interval immediately; 0 disables the watchdog. This is for services whose phases have different latencies — a database might run a tight 5 s watchdog normally but widen it to 60 s during a compaction pass, because it knows its own phases better than the schema author did. The runtime value does not persist: a restart reverts to the schema's WatchdogTimeout.

Timeout extension #

A service that does genuinely slow work during a transition can ask for more time by sending EXTEND_TIMEOUT_USEC=<microseconds> while it is Starting, Stopping, or Reloading. Each message replaces the current phase deadline (it is not additive); a service that keeps sending them keeps proving it is making progress, and if it stops, the last deadline fires and peinit escalates normally.

The extension is capped to prevent a buggy service from extending forever:

PhaseBase timeoutMaximum deadline
StartingStartTimeoutStartTimeout × 4
StoppingStopTimeoutStopTimeout × 4
ReloadingStartTimeoutStartTimeout × 4

During shutdown a second, global cap also applies — the deadline can never exceed the remaining time in the global shutdown timeout, and the stricter of the two caps wins. A message received outside a transition (the service is Active, Failed, …) is ignored — there is no timeout to extend.

OnFailure #

When a service enters Failed, an OnFailure field names another service to start in response — a fallback for graceful degradation (the main web UI failed; bring up a minimal emergency endpoint). It is not a monitoring or alerting hook; that is eventd's job.

OnFailure fires for runtime failures — ProcessCrash, WatchdogTimeout, HealthCheckFailure, the startup-failure causes, and non-Critical budget exhaustion. It deliberately does not fire for:

  • ShutdownWave — nothing new starts during shutdown.
  • **ValidationError, CycleDetected, DependencyFailure, AssertionError ** — these are definition or graph breakage, not a running service degrading. The fallback would likely sit in the same broken graph anyway.

Because a fallback can itself fail and carry its own OnFailure, peinit bounds the chain: it tracks which services it has already started for one originating failure, refuses to start one twice, and never follows the chain beyond a depth of 16. When the guard trips, it logs the loop and stops.

ErrorControl: when failure is not an option #

ErrorControl decides how serious an irrecoverable failure is:

LevelValueOn irrecoverable failure
Normal (default)0The service stays in Failed. The rest of the system carries on.
Critical1peinit syncs filesystems and reboots immediately.

A Critical service is one the system genuinely cannot run without — the platform daemons registryd, authd, lpsd, eventd are all Critical. "Irrecoverable" means the restart budget was exhausted: peinit tried, backed off, retried up to RestartMaxRetries, and the service still would not stay healthy. At that point the fastest path to a known-good system is a reboot.

A few consequences worth holding onto:

  • Critical failure outranks OnFailure. When a Critical service exhausts its budget, peinit reboots; it does not start the OnFailure handler.
  • ErrorControl=Critical implies SafeMode. A Critical service is always eligible to start in Safe mode.
  • Critical services are OOM-protected. peinit sets their oom_score_adj to -1000, so the kernel will not pick them as out-of-memory victims.
  • A runtime Critical crash does not enter Safe mode — it follows the reboot path. Safe mode is only for boot-time configuration errors (a cycle or conflict involving a Critical service). The escalation between reboots, the boot-attempt counter, and Recovery mode are covered in Boot and boot modes.

Warning

A Critical service that exhausts its restart budget on every boot can cause a reboot loop. The [boot-attempt

counter](~peios/boot/boot-and-boot-modes#the-boot-attempt-counter) can escalate repeated unconfirmed boots to Recovery, provided peinit reaches and persists its increment. A confirmed boot resets the counter, so repeated failures after confirmation can never reach the Recovery threshold. See Troubleshooting peinit.

Where to start #

To see exactly which states these policies move a service through, read The service lifecycle.

To understand how a failed service propagates to the ones that depend on it, read Dependencies and ordering.

When a service will not stay up, work backward from the symptom in Troubleshooting peinit.

Dependencies and Ordering

Peios / Using Peios / Services and Jobs

Check a service's dependencies before stopping a shared component or diagnosing a blocked start. Requires waits for successful startup but leaves an already-running dependent alone if the target later stops. BindsTo also stops the dependent when its target goes away.

Relationships are set on the service that needs something, naming the target it needs. Wants attempts an optional target first; Conflicts makes two services mutually exclusive and is symmetric, so one side declaring it is enough.

Before changing a dependency #

  1. Read the dependent's definition with svctl definition show <service> and inspect each target with svctl status <target>.
  2. Decide whether the requirement is successful startup (Requires), optional startup ordering (Wants), runtime coupling (BindsTo), or mutual exclusion (Conflicts).
  3. Use a readiness level when the target must have reached a specific condition, such as a routed network.
  4. After saving, validate the definition and check the next start. Dependency edits apply on a new start or graph reload; they do not rewrite a running process's history.

A DependencyFailure usually points to the target to investigate first. An on-demand start can pull in other services and evict conflicting ones, so its effects can extend beyond the service you named.

The four relationships #

Requires — a hard dependency #

If A Requires B:

  • Start. B must reach a satisfying state before A starts. If B is not running, peinit starts it first (cause DependencyStart). If B fails, A is marked Failed with DependencyFailure and never even attempts to start.
  • Stop. Stopping B does not stop A. Requires is a start-ordering constraint, not a runtime leash — A keeps running.
  • Runtime failure. If B crashes while A is already Active, A is unaffected. B's own restart policy handles B's recovery.

Requires is the workhorse: "I need this to have started, and if it can't, neither can I."

Wants — a soft dependency #

If A Wants B:

  • Start. peinit starts B before A if B exists and is not Disabled — but if B fails to start, or does not exist, A starts anyway.
  • Stop / failure. No effect either way. A and B are runtime-independent.

Wants is best-effort ordering: "start this first if you can, but I work without it."

BindsTo — a runtime coupling #

If A BindsTo B:

  • Start. Identical to Requires — B must satisfy before A starts.
  • Stop. If B stops for any reason — explicit stop, conflict, crash, shutdown — A is stopped too, transitioning to Stopping with cause BindsToPropagation. When A finishes stopping it comes to rest in Failed (carrying BindsToPropagation), not Inactive — so a status query shows the bound service as Failed, making it clear it was taken down by its target rather than shut down cleanly.
  • Recovery. When B returns to Active, peinit automatically restarts A from that Failed state (cause BindsToRecovery). This is reactive — peinit watches B's transitions — and it is budget-exempt: A did not fail on its own, so the restart does not count against its budget. If B never comes back, A stays Failed until you reset (or start) it.

BindsTo is Requires plus a runtime leash: "I need this to start, and I should not outlive it." It is the right choice for a sidecar that is meaningless without its principal. BindsTo implies Requires; listing both for the same target is harmless, and BindsTo semantics win.

Conflicts — mutual exclusion #

If A Conflicts with B:

  • Start. Starting A while B is Active creates a stop operation for B (source ConflictResolution), evicting it (cause ConflictEviction) before A starts — and vice versa. If the loser will not stop within its StopTimeout, SIGKILL escalation applies. The evicted loser does not land in Inactive: it comes to rest in Failed (carrying ConflictEviction), so it shows as Failed in status and needs a reset before it will start again. That is deliberate — an evicted service is not a clean stop, and leaving it Failed stops it from quietly restarting straight back into the conflict.
  • Symmetry. Conflicts is two-way. If A declares Conflicts=["B"], starting either stops the other; B need not declare it back.

Conflicts is for true mutual exclusion — two services binding the same port, or two implementations of one role where exactly one must run — not for ordinary resource contention.

At a glance #

Start orderTarget failure stops dependent?Target stop stops dependent?
Requirestarget first; dependent fails if target failsAt start time onlyNo
Wantstarget first if present; dependent starts regardlessNoNo
BindsTotarget first; dependent fails if target failsYes (and auto-recovers)Yes (and auto-recovers)
Conflictsstarting one evicts the othern/an/a

Waiting for a condition, not only a service #

A target can carry a readiness level after a colon. Requires = ["network:routed"] waits not merely for the network manager to be active but for it to have published the level routed — a default route in place — and holds the start until it does. Publishers report a set of true levels, and peinit checks membership. A routed network publishes link, addressed and routed, so a service can ask for the condition it actually needs. peinit clears the set the moment its publisher leaves a satisfying state.

network there is a role, not a service: the service that fills it declares Provides = ["network"], and peinit rewrites the entry to that service before anything else looks at it. Write the role, not the daemon. The levels link, addressed and routed are defined by network policy, so the definition keeps meaning the same thing whichever executor an image ships. svctl status shows the resolved dependency, netd:routed on a standard image.

On-demand starts #

When you start a service explicitly rather than at boot, peinit does the same graph work on a smaller scope — the requested service's transitive closure:

  1. Collect all transitive Requires and BindsTo dependencies (and best-effort Wants).
  2. Validate that sub-graph (cycles, missing targets).
  3. Resolve Conflicts — stop anything that conflicts.
  4. Start the sub-graph with the same parallel scheduler.

Anything already in a satisfying state (Active, Reloading, Completed, Skipped) is left alone — its dependency is already met, so there is no needless restart. Dependencies pulled in this way start with cause DependencyStart. If two on-demand starts need the same dependency at once, their start operations merge rather than racing.

Failure propagation #

When a service enters Failed during graph execution, the failure spreads along Requires and BindsTo edges — and only those:

  1. Every service that Requires the failed one transitions to Failed with DependencyFailure.
  2. Every service that merely Wants it is unaffected and starts normally.
  3. Propagation is transitive: if A requires B and B requires C, and C fails, then B fails, then A fails — each with DependencyFailure.

This is the payoff of the Requires/Wants distinction. A hard dependency failing takes its dependents down with it; a soft one failing is shrugged off. Choosing the right relationship is choosing how far a failure is allowed to travel.

Graph validation #

Before peinit starts anything, it builds the dependency graph and validates it. Validation runs once per graph build — at boot for the whole boot graph, and per request for an on-demand start's transitive closure. It is not incremental.

Cycles. peinit topologically sorts the graph; if the sort fails, there is a cycle. Every service in the cycle is marked Failed with CycleDetected, and peinit logs the full path (dependency cycle: A → B → C → A) so you can find and break it. A service can not depend on itself — a self-reference is rejected as a cycle. If any service in the cycle is ErrorControl=Critical, peinit downgrades to Safe mode rather than rebooting, because a reboot would hit the same cycle.

Missing targets. What a missing target means depends on the relationship:

RelationshipMissing or disabled target
RequiresDependent marked Failed (DependencyFailure).
BindsToTreated as a missing Requires — Failed (DependencyFailure).
WantsSilently ignored — the entry is dropped.
ConflictsSilently ignored — nothing to conflict with.

Unresolvable conflicts. If two boot-triggered services conflict with each other, there is no way to honor both, so both are marked Failed with ValidationError. As with cycles, if either is Critical, Safe mode applies.

Warnings. Some conditions are logged but do not block boot — most notably a Readiness=Alive service that others Requires (see service types). Warnings appear in the logs and do not change state.

Validation errors. Some conditions do fail the service — for example a health-check configuration that violates the flap constraint. These mark the service Failed with ValidationError.

When more than one finding applies to the same service, peinit records a single primary cause by precedence — CycleDetected > ValidationError > DependencyFailure — but it logs all findings, so the primary cause never hides the others.

Parallel start #

After validation, peinit starts services whose dependencies are all satisfied, and it does so in parallel up to a configurable limit:

Registry keyDefaultMeaning
Machine\System\Boot\MaxParallelStarts10Maximum services starting concurrently.

The scheduler is simple: every service with no unsatisfied dependencies is eligible; peinit starts up to MaxParallelStarts of them; as each one reaches a satisfying state its dependents become eligible and join the queue. The result is that independent subtrees of the graph come up at the same time, while ordering constraints are still honored exactly.

Note

Boot order is emergent, not hardcoded. The installed definitions and their identity dependencies determine the sequence. Change the dependencies and you get a different order. The platform daemons come up first because everything else, directly or transitively, requires them.

Shutdown reverses the graph #

peinit does not need a separate stop-ordering configuration. Shutdown reverses the dependency graph: services with no dependents stop first, and services that others depend on stop last. A service is never stopped until everything that Requires or BindsTo it has already stopped.

Shared platform services stop after their dependents, with registryd last. The exact order comes from the installed graph; do not rely on a fixed list of daemon names. The full shutdown sequence is in Shutdown.

Where to start #

To see the states services move through as they start and stop in order, read The service lifecycle.

To understand how a target's failure interacts with the dependent's own restart policy, read Keeping services running.

To follow how dependency-driven starts appear as operations, read Jobs and operations.

Service Identity and Privileges

Peios / Using Peios / Services and Jobs

A service's Identity decides what its process can access. Its ServiceSecurity descriptor decides who can start, stop, or query it; the registry key descriptor decides who can edit the definition. Check the right boundary before changing permissions.

Read the definition with svctl definition show <service>. Prefer the identity and privileges the service actually needs. An absent or empty Identity means LocalService; SYSTEM must be explicit. peinit gives each service a separate token and never shares its own SYSTEM token.

A distinct virtual service account #

Set Identity to Service to run under the service's own S-1-5-80-… SID as its user identity. authd derives it from the attested service name, using the same case-insensitive derivation as the existing service group. Only SYSTEM PID 1 can request the attestation. No local principal record or stored credential is created, and this does not provide an interactive logon path.

Unlike shared LocalService, two differently named virtual services have distinct file and process owners. Grant storage access and policy privileges to the individual service SID. Renaming the service changes its identity and requires coordinated updates to those grants. The default remains LocalService for existing definitions; choosing Service is explicit.

The standard timed, resolvd and trustd deployments also use distinct Service identities, retaining their existing service-SID grants. Their SYSTEM preparation hooks, where present, remain separate from their main processes.

The standard eventd deployment uses this identity with SeChangeNotifyPrivilege, SeSecurityPrivilege (KMES consumption), and SeAuditPrivilege (event emission). Its System integrity level allows reception of higher-integrity client tokens; it does not grant SYSTEM account membership or SeTcbPrivilege. A short SYSTEM pre-start hook initializes registry authorization defaults, then exits before the long-running daemon starts. Private stores name eventd's own SID.

Services that need token minting/installation, raw network administration, device management, or pre-authd bootstrap still require separate assessment. Granting SeTcbPrivilege solely to make an identity change work defeats the purpose of moving a service out of the machine-wide trust boundary.

The local principal source lpsd also runs as Service, with only SeChangeNotifyPrivilege and System integrity for handling client tokens. Its package provisions its private state scope; credential files are owned by lpsd and admit only lpsd and SYSTEM. Its administrative API still admits SYSTEM and Administrators. /run/psi.sock admits service connections, but authd registers a source only when its enabled service SID matches the configured source allowlist. Transport admission does not confer source authority.

Privilege restriction #

A token comes from its source (authd or the SYSTEM mint) with a default set of privileges. RequiredPrivileges lets a definition trim that set down to only what the service needs:

  • peinit reads the RequiredPrivileges allow-list and removes every privilege not on it from the token before exec.
  • Restriction is purely subtractive. peinit removes privileges; it never adds them. A service cannot acquire a privilege its token's source did not grant.
  • If RequiredPrivileges is absent, the token's default privilege set is used unchanged.

This is least-privilege made concrete: eudev, for instance, runs as SYSTEM (it needs device access during early boot) but with its privilege set stripped to the minimum it actually uses, so a compromise of eudev does not hand an attacker the full SYSTEM privilege set. Removal is permanent for the life of that token — it is not a disable that the service can re-enable. See Privileges for what the individual privileges grant.

Which identity runs what #

A service is not only its main process — it has hooks, health checks, and a reload command, and each runs under a defined identity:

ContextRuns as
Main processThe service's Identity.
ExecStartPre / ExecStartPostHookIdentity if set, otherwise the service's Identity.
Health checksThe service's Identity, always.
ExecReload (command form)The service's Identity, always — HookIdentity does not apply.
Submitted jobsThe submitting process's own primary token — or, if the submitter attached one, the token the kernel verified it could convey (its client's identity, when impersonating). Never an identity named in the request.

Token materialisation for hooks follows the same rules: a HookIdentity of SYSTEM is minted; any other principal is requested from authd, at the point the hook runs.

HookIdentity exists so hooks can run with different — usually higher — privileges than the service itself: creating directories in privileged locations, or running a database migration as an admin identity, before the long-running daemon drops to a lesser identity.

Warning

peinit does not validate filesystem permissions on hook binaries. If HookIdentity grants elevated privileges, it is the administrator's responsibility to ensure the hook binary and every parent directory are not writable by a lower-privileged identity — otherwise a less-trusted principal could replace the hook and run code as the elevated identity. (FACS enforces KACS descriptors on managed filesystems, but peinit itself performs no such check — protecting hook binaries still depends on correct SDs from packaging and controlled paths.)

The per-service SID #

Every service token carries a SID derived from its service name. Granting access to that SID can distinguish two services even when they share LocalService. With Identity=Service, it is also the token's user identity.

Renaming a service changes its SID. Update grants that name the old SID as part of the same planned change. The SID derivation reference gives the algorithm.

How a token is materialised #

Identity=SYSTEM uses a separate token minted by peinit. Other identities use authd; if authd cannot issue the required identity, the start fails rather than falling back to SYSTEM.

The SYSTEM path #

Use SYSTEM only when the service requires that authority, such as the services needed before authd is available. registryd and authd use this bootstrap path. Standard eventd and lpsd deployments now use their own Service identities and start through authd.

The authd path #

For a non-SYSTEM identity, check that authd is available and the account is permitted for service logon. The authd.service.attested event records the service, issued identity and privileges, or a refusal reason. peinit derives an authority dependency for a non-SYSTEM service or hook identity.

The token-materialisation reference retains the minting and authority flow. The current authd request is specified in the TRM authd path.

Security invariants #

The identity model rests on a few rules peinit never breaks:

  1. peinit never shares its SYSTEM token. Even Identity=SYSTEM services get a separately minted token.
  2. peinit never drops its own SYSTEM identity. PID 1 runs as SYSTEM for the life of the system — its identity is axiomatic, granted by the kernel at boot.
  3. Privileges are subtractive only. RequiredPrivileges removes; it can never add.
  4. Identity is deterministic. Every service runs as a known principal. SYSTEM must be declared explicitly; an empty Identity is the minimal LocalService, never SYSTEM.
  5. A submitted job never runs as an identity its submitter could not act as. peinit installs only the submitter's own primary token or a token the kernel gated on the way in; it never opens a token by a PID or descriptor a submitter names, and there is no identity field to name one.

Where to start #

Identity decides what a service can do; the ServiceSecurity descriptor decides who can manage it — two independent concerns. Read Who can manage a service for the other half.

To see how the token is installed alongside the rest of the process setup, read The execution environment.

For the identity primitives themselves — tokens, SIDs, privileges — start at Tokens.

Token installation and executable trust #

The service child receives its prepared identity before exec. PIP is then established from the executable by the kernel; it is not chosen by the service account or inherited unchanged through exec. Peinit needs sufficient PIP dominance to manage protected services, but that does not make it the only trusted process or exempt it from service-management authorization.

The launch path does not add a per-service PSB mitigation request. Inherited mitigations and application self-hardening can still apply. Inspect the running process's committed mask, including after a replacement, rather than interpreting successful launch as proof of a requested hardening profile.

Peinit also does not populate the global TLP or CAAP caches or install mount policies. Those mechanisms require their own deployment owner. A service's readiness event proves only the readiness contract that service implements.

The Execution Environment

Peios / Using Peios / Services and Jobs

If a program works in your shell but fails as a service, compare its identity, environment, working directory, and standard streams. peinit does not inherit your logon session. It launches the program with the context in its definition.

Start with svctl definition show <service>, then inspect svctl status <service> and the service's logs. Check hook output as well as the main program. Environment and working-directory changes reach the next process start; they do not change a process already running.

The environment #

peinit constructs each service's environment in layers, lowest precedence first — it does not pass through its own near-empty startup environment.

  1. Compiled-in base. A fixed floor peinit always provides — PATH: /bin.
  2. Global EnvVars. Each value under Machine\System\Init\EnvVars\ becomes a variable (value name → variable name). EnvVars\PATH overrides the base PATH; other names add. Every service gets this layer except registryd, which serves the key itself — see the warning below for why that exemption exists.
  3. Per-service Environment. The definition's own KEY=VALUE entries, which override layers 1–2.
  4. Protocol variables. NOTIFY_SOCKET (always) and LISTEN_FDS / LISTEN_FDNAMES (only when stored fds are injected). These have the highest precedence and cannot be overridden — a service that clobbered NOTIFY_SOCKET would break sd_notify.

A change to EnvVars\ takes effect on a service's next start, like the per-service Environment field — it is not pushed into running services.

peinit deliberately does not set HOME, USER, LOGNAME, SHELL, or TERM. Peios identity is a token (a SID), not a passwd entry, so there is no canonical home directory or sign-in shell to fill in. A service that needs any of these supplies it through EnvVars\ or its own Environment.

Warning

Write access to Machine\System\Init\EnvVars\ is equivalent to compromising every service peinit starts — a principal who can set it can inject LD_PRELOAD, LD_LIBRARY_PATH, and the like into all of them. peinit deliberately does not filter variable names; the key's security descriptor is the control boundary. Keep it tight — the recommended default is SYSTEM full, Administrators read-only.

This is also why registryd is the one service that never receives this layer: it is the daemon that serves the key. Letting the key inject into the process that enforces who can write it would make the control boundary self-referential. Every other service, platform daemons included, gets the ordinary layering.

Working directory and limits #

FieldEffect
WorkingDirectoryThe process's working directory. Must be a non-empty absolute path; defaults to /.
LimitNOFILERLIMIT_NOFILE — the maximum number of open file descriptors.
LimitCORERLIMIT_CORE — the maximum core-dump size, in bytes.

peinit also sets oom_score_adj: -1000 (OOM-immune) for ErrorControl=Critical services, and the default 0 for everyone else — so the kernel never picks a Critical platform daemon as an out-of-memory victim.

Runtime directories #

RuntimeDirectories gives a service private scratch space under /run without an ExecStartPre that has to mkdir it by hand. Each name you list becomes a directory created **directly under /run ** — RuntimeDirectories=myapp yields /run/myapp — set up immediately before the main process starts. Each one gets a security descriptor granting full access to SYSTEM, Administrators, and the service's own SID, so the service can write to its directory while other principals cannot. If a directory can't be created, or its descriptor can't be applied, the start fails with ParentSetupFailure.

peinit does not remove these directories when the service stops. /run is a boot-scoped tmpfs, so they disappear at the next boot rather than being torn down on each stop — a restarting service finds its runtime directory (though not necessarily its contents) already in place.

For the exact naming rules on each entry and the field's type and default, see the Registry key reference.

Standard streams #

peinit wires a service's standard streams before exec:

  • stdin is redirected to /dev/null. peinit never gives a service an interactive input channel; a service that needs input must obtain it explicitly (a socket, a stored fd).
  • stdout and stderr are redirected to pipes peinit holds, so it can capture and forward every line. This is the subject of Service output and logging.

Attaching a terminal #

A service that sets TTYPath to an absolute terminal path — /dev/console, /dev/tty1, a serial line — gets that terminal on all three standard streams instead of the wiring above, and becomes a session leader owning it as its controlling terminal. That last part is what makes job control work: Ctrl-C interrupts, fg /bg behave, and a hangup reaches the process group. It is what a boot shell or a login prompt needs.

It carries a path rather than a flag because which terminal is a per-service question: a maintenance shell on tty1 while the kernel console is a serial line is an ordinary thing to want.

Warning

Attaching a terminal suppresses log capture — the pipes eventd would read are closed, so the service's output goes to the terminal and nowhere else. Don't set TTYPath on a service whose output you expect to find in the logs.

Two services pointed at the same terminal do not fight over it. peinit gives the device to one of them and skips the rest — highest TTYPrecedence wins — and a skipped service can ask to be started when the terminal frees, with the tty:released trigger. See Queueing for a terminal.

Pre-exec and post-exec hooks #

Hooks let a service do work around its main process without baking it into the binary.

  • ExecStartPre runs before the main binary. Each command runs in sequence, in the hooks/ sub-cgroup; any hook exiting non-zero aborts the start (the whole cgroup is killed and the service Fails with PreHookFailure). Use it for prerequisites that must hold before the service starts — creating a runtime directory, waiting on a precondition.
  • ExecStartPost runs after readiness (Simple) or after a successful exit (Oneshot). A post-hook failure is logged but does not fail the service — by the time it runs, the service is already up. (A Oneshot that fails never runs its post-hooks.)

Hooks run under HookIdentity if set, otherwise the service's own identity. Their output is captured and tagged like the main process's, labeled with the hook (for example jellyfin/ExecStartPre[0]).

Command string parsing #

The command fields — ExecStartPre, ExecStartPost, ExecReload, HealthCheck — are parsed into an argument list with simple, predictable rules. peinit never invokes a shell.

  • Whitespace splits the command into arguments; double quotes group text containing spaces into one argument and are not retained (--name="hello world" → one argument --name=hello world).
  • There is no shell expansion, variable substitution, or globbing. Backslash is literal; a single quote is an ordinary character.
  • The first argument is the executable and must be an absolute path beginning with /. Relative names and PATH search are validation errors.
  • An empty or whitespace-only command, or an unclosed quote, is a validation error.

If a command genuinely needs shell features, wrap it in a script and point the field at the script.

ExecReload can also be a signal, written signal:<NAME> — for example signal:SIGHUP. The name must be an exact, canonical Linux signal name (uppercase, no aliases, no numbers); SIGKILL and SIGSTOP are rejected because they cannot be handled as a reload. With no ExecReload at all, reload sends SIGHUP. The reload lifecycle is covered in Controlling services.

Conditions and asserts #

Before peinit runs any hook or the main process, it evaluates conditions and asserts — start-time checks in the same type:argument form. The difference is what failure means:

  • A failed Condition skips the service — it transitions to Skipped, which satisfies its dependents (it succeeded by not needing to run). Conditions express "only run here if it makes sense."
  • A failed Assert fails the service — it transitions to Failed with AssertionError. Asserts express "this was expected to run, and a precondition is missing."

Conditions are checked first; only if all pass are asserts checked. All entries are AND-ed. The check types:

TypeFormPasses when
pathpath:<path>the path exists (any type)
filefile:<path>a regular file exists
directorydirectory:<path>a directory exists
registryregistry:<key>the registry key exists

Two constraints follow from peinit being single-threaded PID 1, which must never block:

  • registry: checks are cache-only. Accepted paths are exactly Machine\System\Services, Machine\System\Init, and Machine\System\Services\<name> with one nonempty service-name component. The roots resolve as present; the last form checks whether the service exists in the in-memory model. Init descendants, deeper Services paths, trailing separators, and other keys are load-time decode errors. No live registry read is made.
  • Filesystem checks run off the main loop. path: /file:/directory: checks are performed by a short-lived forked helper, not a stat() on the event loop, because stat() can wedge on a hung mount.

That timeout is the PreStartCheckTimeout field, which defaults to 5 seconds. A filesystem check that does not finish within it — say a stat() wedged on a hung mount — is treated as not satisfied, fail-safe: peinit kills the helper and treats the check as unmet, so a Condition skips the service and an Assert fails it, rather than letting the event loop hang.

The fd store #

The fd store lets a service preserve file descriptors across restarts — most usefully a listening socket, so a stateful daemon can restart without dropping connections. It is opt-in: FdStoreMax (default 0) sets the maximum number of fds peinit will hold; 0 disables it.

The mechanics ride on sd_notify:

  • A service stores an fd by sending FDSTORE=1 with the fd attached (and optionally FDNAME=<name>; the default name is stored). peinit holds it.
  • It removes one with FDSTOREREMOVE=1 and FDNAME=<name>.
  • On the next start, peinit injects the stored fds starting at fd 3, sets LISTEN_FDS to the count and LISTEN_FDNAMES to the colon-separated names, then clears the store. (This is the same LISTEN_FDS convention systemd uses, so software with existing fd-passing support works unmodified.)

The store survives an automatic restart (crash → restart policy → new start) — that is the whole point. It is cleared on an explicit stop or shutdown (the service is not coming back), and when a removed definition is finally discarded.

A clean context #

A service receives its standard streams and explicitly supplied descriptors. It does not inherit peinit's privileged connections or signal handling. The launch-isolation reference describes the descriptor and signal setup.

The cgroup tree #

peinit tracks a service's main process, hooks, and health checks in separate cgroups beneath /sys/fs/cgroup/peinit/. It uses those groups for tracking and clean termination, not resource limits.

A leaked cgroup warning means a process survived cleanup, often because I/O is stuck. A later start can use a fresh <service>.gen<N> tree; that does not repair or kill the stuck old process. Investigate the Abandoned state. The cgroup reference retains the layout and rationale.

Where to start #

For the identity half of the launch — how the token is chosen and installed — read Service identity and privileges.

For what happens to the stdout/stderr pipes peinit holds, read Service output and logging.

For how conditions, asserts, and hooks fit into the start sequence and its states, read The service lifecycle.

System-console aliases and logout #

Peinit pins TTYPath=/dev/console to the kernel-selected terminal when reading service definitions. A display's moving tty0 alias becomes tty1, so switching the foreground console does not move the session. Both arbitration and launch use this fixed endpoint. When a terminal service's main process exits, peinit kills its remaining session processes before handing the terminal on. A clean exit under RestartPolicy=Always restarts the prompt at the base delay without spending the crash budget.

Who Can Manage a Service

Peios / Using Peios / Services and Jobs

To let someone start or stop a service, change its ServiceSecurity permissions. Do not give them write access to the service definition to grant control: definition writes can change the program and the identity it runs as.

In Services Manager, select the service and inspect the commands you can use. Who can control it… edits runtime control; Who can change its definition… edits the registry key's permissions. If a command returns ACCESS_DENIED, check its required right and the caller's identity before widening either descriptor.

Two descriptors, two questions #

A service is associated with two descriptors that are easy to conflate but answer different questions and are enforced by different components:

DescriptorQuestionStoredEnforced by
Registry key SDWho can read or edit the definition?On the Machine\System\Services\<name> keyLCS, at key-open time
ServiceSecurity SDWho can manage the running service?As the ServiceSecurity binary value on that keypeinit, on every control command

The registry key SD is ordinary registry access control and not peinit's concern — peinit reads definitions as SYSTEM, which has full access. The ServiceSecurity SD is peinit's domain, and the rest of this page is about it.

They are genuinely independent. An administrator might be able to query a service's status (ServiceSecurity grants SERVICE_QUERY_STATUS) but not read its configuration (the registry key SD denies read) — or the reverse. Runtime control and configuration access are separate concerns, and both combinations are valid.

Changing them from the desktop #

On a GXWI desktop, select the service in Services Manager. Below what you can do with it, the details pane says where its ServiceSecurity comes from: set for this service, the default set for every service, or peinit's built-in default. Two buttons open the permissions editor, and both are also on each row's right-select menu.

  • Who can control it… opens the ServiceSecurity descriptor. Its boxes are the service rights in words: Full control, Start, Stop, Reload (SERVICE_INTERROGATE) and See its state (SERVICE_QUERY_STATUS). Restart needs Start and Stop together, and Reset needs Stop. When you apply, Services Manager writes the result as the service's own ServiceSecurity value. From then on, a change to the default does not reach that service. peinit applies the new descriptor on the next command, and the window's buttons change to match.
  • Use the default appears beside it once the service has its own value. After you confirm, it deletes that value, so the service takes the default again.
  • Who can change its definition… opens the descriptor of the service's registry key. Its boxes are Full control, Read, and Write on the key. Entries you add there apply to the key and to any keys under it.

Under Every service, the pane says what a service without its own value takes:

  • Default permissions… opens the ServiceSecurity on Machine\System\Services. If there isn't one, it starts from peinit's built-in default. Applying writes it to that key, and it reaches every service without its own value at the next command.
  • Use the built-in default appears once that key has a value. After you confirm, it deletes the value, so services without their own go back to peinit's built-in default.

Each of these is offered for changing only if you are allowed to change it:

  • ServiceSecurity is a value on a registry key: the service's key, or Machine\System\Services for the default. Changing it, or deleting it, needs the right to set values on that key (KEY_SET_VALUE).
  • The service key's own descriptor needs WRITE_DAC, and WRITE_OWNER for its owner.

If you are not allowed, the editor still shows who can do what and says why it can't be changed, and the two "use the default" buttons are unavailable with the reason. Services Manager finds this out by asking the registry for those rights, not from your group memberships.

The same can be done from a terminal with reg. For example, this makes sshd take the default again:

reg del 'Machine\System\Services\sshd' ServiceSecurity

Service access rights #

The ServiceSecurity descriptor grants these rights:

RightBitGrants
SERVICE_QUERY_STATUS0x0001Query state, PID, cause, health, warnings.
SERVICE_START0x0002Start the service.
SERVICE_STOP0x0004Stop the service.
SERVICE_INTERROGATE0x0008Reload the service.
SERVICE_ALL_ACCESS0x000FAll of the above — the "full access" granted to SYSTEM by default.

restart requires both SERVICE_STOP and SERVICE_START, since it is a stop followed by a start. reset requires SERVICE_STOP.

When peinit evaluates the descriptor it maps the generic rights as follows, so a descriptor written with generic rights behaves sensibly:

GenericMaps to
GENERIC_READSERVICE_QUERY_STATUS
GENERIC_WRITESERVICE_START | SERVICE_STOP | SERVICE_INTERROGATE
GENERIC_EXECUTESERVICE_START | SERVICE_STOP | SERVICE_INTERROGATE
GENERIC_ALLSERVICE_ALL_ACCESS

The default descriptor #

If a service has no ServiceSecurity value, it inherits the one on Machine\System\Services itself. If that key has none either, peinit applies a built-in default:

  • SYSTEM (S-1-5-18) — full access.
  • Administrators (S-1-5-32-544) — full access.
  • Authenticated Users (S-1-5-11) — query only.
  • Everyone (S-1-1-0) — every refusal audited, in its SACL.

So out of the box, administrators can do anything with a service, everyone who is signed in can see what it is doing, and every refused command is recorded. To let someone else start or stop a particular service, give that service a ServiceSecurity that grants it; anyone signed in can reach the control socket, so a grant to them takes effect.

Warning

A ServiceSecurity value carries the service's audit policy as well as its permissions, and it is written whole. Anyone who can write it — that is, anyone who can write the service's registry key, or Machine\System\Services — can remove its SACL and so stop its denials being recorded. Keep those keys writable only by administrators, as they are by default. To let someone manage a service, grant them rights in its ServiceSecurity; do not give them write access to its key.

ServiceSecurity is hot-reloaded: a change to the value in the registry takes effect on the next control request, with no service restart. peinit picks the change up through a registry notification. This is why ServiceSecurity is in its own mutability class — access policy should be able to change without disturbing a running service.

How a command is authorized #

Every control command runs the same gate:

  1. peinit captures the caller's token from the kernel (the KACS_SO_PEER_TOKEN socket option) — the caller's effective identity at connection time, so if the caller is impersonating, the impersonated identity is what is checked.
  2. peinit resolves the target service and its ServiceSecurity descriptor.
  3. peinit runs AccessCheck: the caller's token against the descriptor, for the right the command needs.
  4. Denied → return ACCESS_DENIED. The kernel records the attempt — caller, target service, rights requested, and granted — as a kacs.audit.access.checked event, because the descriptor's SACL asks it to.
  5. Granted → execute the command.

Note

Every denial is recorded by default: the built-in descriptor's SACL audits every refusal, for everyone, and peinit names the service in each check so the record says which one it was. Look for it in the event viewer as kacs.audit.access.checked with object kind service and the service's name. A ServiceSecurity you write yourself is used as it is, so keep a SACL on it (for example S:(AU;FA;0xF;;;WD)) if you still want its denials recorded. If you are debugging a denial, the audit record has everything you need; see Debugging a denial.

The system control descriptor #

Some operations are not about any one service — shutdown and reload-config act on the whole system, and boot reports on it. These are checked against peinit's own descriptor, stored at Machine\System\Init\ControlSecurity:

RightBitGrants
SYSTEM_SHUTDOWN0x0001Initiate poweroff, reboot, or halt.
SYSTEM_RELOAD_CONFIG0x0002Re-read all definitions and rebuild the graph.
SYSTEM_QUERY_STATUS0x0004Ask how this boot went (svctl boot).
GenericMaps to
GENERIC_READSYSTEM_QUERY_STATUS
GENERIC_WRITESYSTEM_RELOAD_CONFIG
GENERIC_EXECUTESYSTEM_SHUTDOWN
GENERIC_ALLall three

The default grants SYSTEM and Administrators all three rights, and Authenticated Users SYSTEM_QUERY_STATUS, as the default service descriptor lets everyone signed in query a service. peinit loads this descriptor at boot and hot-reloads it on registry change, exactly like ServiceSecurity. A descriptor written before SYSTEM_QUERY_STATUS existed grants it only through GENERIC_READ, GENERIC_ALL or the bit itself.

Jobs have descriptors too #

A submitted job is a securable object in the same way. It carries its own descriptor from the moment it exists — by default owned by the submitter and granting JOB_QUERY, JOB_STOP, and JOB_SIGNAL to the submitter, SYSTEM, and Administrators, and nothing to the identity the job runs as — and every job command, on either socket, is checked against it. The one thing no descriptor inside peinit governs is who can submit: that is the file descriptor on the jobs socket, checked by the kernel when a process connects.

The list command filters, it does not deny #

list is access-control-aware in a quieter way: it returns only the services the caller has SERVICE_QUERY_STATUS on, and omits the rest. A caller with no query rights gets an empty list, not a denial. What this protects is a service's state; that a service exists is not a secret. A command naming a service is answered UNKNOWN_SERVICE only if it does not exist, and the definitions under Machine\System\Services are readable.

The boundaries that hold #

A few invariants are worth stating outright, because they are what make this trustworthy:

  • peinit never bypasses AccessCheck for a control operation. No backdoor, no override flag, no "trust localhost."
  • The descriptors are the only policy inputs. peinit consults the ServiceSecurity and ControlSecurity descriptors and nothing else — not config files, not environment variables, not hardcoded lists.
  • One service's state is never exposed to another without a check. status is per-service access-controlled; list filters. The same holds for jobs: job status is checked, job list filters.

Where to start #

For the other half of the security model — what a service can reach once it is running — read Service identity and privileges.

For the commands these rights gate, read Controlling services.

For the descriptor and AccessCheck machinery itself, read Security descriptors and Access decisions.

Service Registry Keys

Peios / Using Peios / Services and Jobs

peinit reads its configuration from four places in the registry. This page says what each one holds and which guide explains it. The registry manual for each value, shown by regman, is the authority for its type, default, valid range, and when a change takes effect.

Where peinit's settings live #

peinit reads these keys:

KeyHoldsGuide
Machine\System\Services\<name>One service definition per subkey. Only ImagePath is required.Defining a Service
Machine\System\BootBoot limits and timeouts: parallel starts, the success grace period, the settle timeout, and shutdown timeouts.Boot and Boot Modes
Machine\System\InitOperational parameters: control and jobs socket limits, service output limits, default environment variables, and boot-time path provisioning.Operational parameters
Machine\System\eventdLogSocketPath, the socket that peinit forwards service output to.Finding Service Logs

Replace <name> with the service's name. peinit learns about edits to service definitions through a registry watch. Saving a value doesn't mean that a running service has adopted it; each value's manual says when a change applies.

Looking up a value #

Use regman with the key's path to read the documentation for every value under it:

regman 'Machine\System\Services'

regman reads the installed documentation, not the live registry. Use reg to read the value configured on this machine. To check a whole definition before peinit uses it, run svctl definition validate.

Operational parameters #

The values under Machine\System\Init bound peinit's own resources. They fall into four groups:

  • Control and jobs sockets. The security descriptor for system-level control operations, connection counts, request and message sizes, idle timeouts, and the number of live jobs each submitter can hold. See Controlling Services and Jobs and Operations.
  • Service output. Line length, the buffer for each service, and the output held before eventd starts. See Finding Service Logs.
  • EnvVars. Default environment variables for the services peinit starts once the registry is available. Protect this key's security descriptor: every value written here reaches those services. See The Execution Environment.
  • ProvisionedPaths. Directories and files that peinit creates and secures during boot. See Boot and Boot Modes.

Values peinit writes #

peinit records the last run of each persistent timer, in the LastTimerRun value or the TimerState subkey of the service's definition. Don't edit these values. See Triggers and Timers.

The peinit technical reference manual lists every key from the implementation's side.

Boot and Boot Modes

Peios / Using Peios / Boot and Shutdown

On a running machine, use svctl boot or System Settings › Startup & Shutdown to see the mode, why it was chosen, and whether the boot has been confirmed successful.

  • Full starts the normal boot-triggered set.
  • Safe starts a reduced boot-triggered set. Use the reported graph error or requested-mode reason to decide what to repair.
  • Recovery provides an unrestricted SYSTEM shell on the console and skips Phase 2 services. svctl boot is not available there.

Important

Recovery needs physical, IPMI, or serial console access; there is no remote recovery service. Confirm that access before a change that can leave the machine unable to boot. Recovery offers no TCB guarantee.

How this boot went #

svctl boot asks peinit, and so does System Settings, at the top of its Startup & Shutdown section:

$ svctl boot
boot: full
reason: normal
unconfirmed boots before this one: 0 (recovery at 3)
confirmed: yes
grace: 30s
  • boot is the mode, and reason why: normal, requested (peios.safemode=1), or a Safe mode peinit chose itself because a full boot couldn't be planned, with what stopped it.
  • unconfirmed boots before this one is the boot-attempt counter as this boot found it, and the threshold at which the machine starts in Recovery.
  • confirmed says whether this boot has counted as a success yet: every Critical service holding for BootSuccessGrace, and the counter put back to 0. Until then it names what it is waiting for.

Recovery mode never answers: it runs a recovery shell and no Phase 2 services or peinit control interface. Registryd can already be running, but there is no control socket to ask. Anyone signed in can ask; see who can manage a service for the descriptor.

The three boot modes #

The three modes form an escalation path from normal operation to last-resort maintenance.

flowchart TD
    F["Full boot"] -->|success| OK["operational<br/>counter reset"]
    F -->|cycle/conflict w/ Critical| S["Safe mode<br/>(no reboot)"]
    F -->|Critical failure| RB["sync + reboot"]
    S -->|success| OKS["operational (reduced)<br/>counter reset"]
    S -->|Critical failure| RB
    RB --> CNT["counter increments"]
    CNT -->|counter ≥ N| REC["Recovery mode"]
    F -.->|Phase 1 failure| REC

Full mode #

The default. All boot-triggered services start in dependency order. A boot is successful — and the boot-attempt counter resets to 0 — when every Critical service has reached and held a dependent-satisfying state (Active, Completed, or Skipped) for a grace period (BootSuccessGrace, default 30 s). The criterion is "satisfying," not "Active," so that a Critical Oneshot that reaches Completed can still mark the boot good.

Safe mode #

Safe mode starts a reduced set of boot-triggered services and rebuilds the graph from scratch using only those, dropping dependencies on excluded services. Two categories are eligible:

  • Critical services (ErrorControl=Critical) — must start; a Critical failure here still follows the normal reboot path.
  • SafeMode services (SafeMode=1) — best-effort; if they fail, Safe mode carries on without them.

Everything else is skipped. Safe mode is entered when:

  • graph validation finds a cycle involving a Critical service, or
  • an unresolvable conflict involving a Critical service, or
  • the kernel command line says peios.safemode=1.

The first two are configuration errors — rebooting would hit them again — so peinit downgrades without rebooting. Safe mode is not entered by a Critical service crashing at runtime; that follows the reboot path. And it is purely a boot-sequencing concern: once booted, you can start any service by hand exactly as in Full mode. It is the mode for "the configuration is broken but the TCB is healthy."

Note

SafeMode=1 and ErrorControl=Critical are filters within the boot-triggered set. They do not make a demand-only service auto-start in Safe mode — a service with no boot trigger stays demand-only regardless.

On a machine with the dynamic-boot feature, System Settings › Startup & Shutdown › Always Start in Safe Mode puts peios.safemode=1 on the command line the next boot image is made from. Its next-boot effect depends on a successful rebuild to the intended boot partition; verify the activation chain. Once present in the booted image it holds until changed there, and while the machine is in Safe mode because of it, System Settings says so.

Recovery mode #

Recovery mode is the last resort, and it offers no TCB guarantee — the administrator gets an unrestricted SYSTEM shell on the console and must treat it with corresponding care. It is a maintenance environment, not a degraded boot.

In Recovery, peinit completes the Phase 1 basics and starts registryd only if that boot has not already attempted it; a failed registryd start is not repeated. Registryd failure does not prevent the shell. peinit skips all Phase 2 services and execs a SYSTEM shell on /dev/console (/bin/recsh if present, else /bin/sh), respawning it if it exits. It is entered when:

  • the boot-attempt counter reaches N (default 3),
  • the kernel command line says peios.recovery=1, or
  • registryd fails during Phase 1 — entered immediately, without rebooting, because there is no Phase 2 to attempt. The counter has already been incremented for this attempt.

Preserve the console failure reason and any source startup diagnostics first. Identify the installed registryd provider, its version, hive declarations and database paths. Recovery does not establish that the registry source is stopped: a source started or attempted earlier in the boot can still be active. Do not start a second source against the same hive files.

Offline inspection or repair needs a procedure supported by that provider and version. The source-checked loregd implementation has no offline repair switches and does not create an automatic startup backup. Its orphan cleanup is not corruption repair or backup restoration; the references identify the checked revision. Verify the existence and coverage of any recovery copy before planning to replace data.

Follow Recovery troubleshooting for the evidence to collect and the point to involve the administrator or provider. If the source can serve the required operations, the supported Backup and restore workflow can recover a subtree; it depends on that working source and is not offline source repair. Restore replaces data and permissions. Role definitions can re-supply service configuration but do not restore all registry data.

Important

Recovery mode requires console access — physical, IPMI, or serial. There is no remote recovery in the current design (emergency SSH and registry historical reversion are noted as post-v1 work). Plan console access for any machine you need to be able to recover.

The boot-attempt counter #

The counter can escalate repeated unconfirmed boots to Recovery when peinit reaches the increment and can persist it. It is a plain integer in a file at /.peinit/boot-attempts — not in the registry, because the registry can be the very thing that is broken. A confirmed boot resets the count; the counter does not guarantee that every reboot loop ends in Recovery.

  • peinit reads it at startup, before choosing a mode. The Recovery threshold (counter ≥ N) is checked against this pre-increment value, so the default N of 3 admits exactly three attempts before Recovery. A missing file counts as 0; a corrupt or unreadable one → Recovery. Override N with peios.bootattempts=N on the kernel command line, or set it to 0 to disable the check when the counter is itself the fault.
  • peinit increments it once per boot after the root, mount, seed, machine-ID and clock steps, before registryd starts. A registryd startup failure therefore still consumes an attempt. An earlier failure that enters Recovery before this point does not increment it.
  • peios.recovery=1 forces Recovery but does not suppress the increment once that point is reached.
  • The counter is reset to 0 on a successful Full or Safe boot (after the grace period).
  • If the counter file cannot be written (disk full), peinit treats it as 0 and continues — a write failure must not by itself trigger Recovery.

A Critical service exhausting its restart budget — at boot or at runtime — triggers a sync and reboot. Repeated boots that never complete the success grace accumulate attempts until the counter reaches N and peinit enters Recovery. A failure after a confirmed boot still reboots the machine, but that boot already reset the counter: repeated late failures can therefore continue without reaching the Recovery threshold. Use svctl boot to distinguish these cases. The counter deliberately does not try to catch a peinit too broken to reach its own increment; that is a binary-integrity problem, not a boot-loop problem. See the TRM counter cycle for the exact increment boundary.

Boot configuration #

KeyDefaultControls
Machine\System\Boot\MaxParallelStarts10Services starting concurrently (must be > 0; invalid → Recovery).
Machine\System\Boot\BootSuccessGrace30Seconds a Critical service must hold a satisfying state before boot counts as successful.
Machine\System\Boot\ShutdownTimeout90Maximum seconds for the whole shutdown sequence.
Machine\System\Boot\PostKillTimeout5Seconds a service cgroup can take to drain after SIGKILL before it counts as stuck.
Machine\System\Boot\SettleTimeout5Seconds peinit waits for the boot service set to settle before starting boot:settled services anyway.

All but ShutdownTimeout are read at boot, so a change applies at the next one; ShutdownTimeout applies the next time peinit re-reads its configuration (svctl reload-config). System Settings shows and changes them in its Startup & Shutdown section, under Timeouts: Apply and Undo appear once one has been edited. Changing them needs write access to Machine\System\Boot — as shipped, Administrators.

The kernel command line #

peinit reads the following peios.* tokens. They are deliberately few: everything peinit can read after registryd is serving belongs in the registry instead, where it can be inspected, secured and changed without editing a boot entry. What is left is either a per-boot mode decision or a Phase 1 value — one peinit needs before there is a registry to ask.

TokenEffect
peios.safemode=1Force Safe mode.
peios.recovery=1Force Recovery mode, whatever the counter says.
peios.bootattempts=NOverride the boot-attempt threshold; 0 disables the check.
peios.notifysocket=PATHMove the sd_notify socket. Phase 1, because registryd is the first service to use it and it must be bound before registryd starts.
peios.quiet=NHow much peinit can write to the console: 0 write everything, 1 (default) stay out of a terminal a service owns, 2 also drop ordinary progress. See below.

Console noise: peios.quiet #

peinit reports its progress to /dev/console, and so does any service that claims that terminal with TTYPath. Two writers, one device: a sign-in prompt started while peinit is still narrating gets written over, and the reader cannot tell input from log. peios.quiet decides who yields.

It sets two independent rules, which is why it is a level and not a flag:

Terminal a service ownsEverywhere else
peios.quiet=0peinit writes anywayeverything
peios.quiet=1 (default)only messages that mean the machine is about to be losteverything
peios.quiet=2only messages that mean the machine is about to be losterrors only

The rules stack rather than scale: errors are never less visible at 2 than at 1. An error overrides a requested blackout — silence was a preference, and an error is news — but it does not override terminal ownership, which is not peinit's to override. Only losing the machine (dropping to Recovery, halting with no shell, a Critical service about to force a reboot) is worth one corrupted line of somebody else's session.

prelude honors peios.quiet=2 as well, since it writes to the same console. The other two levels mean nothing there — prelude exits before the first service starts, so no terminal has an owner yet.

Warning

Suppressed messages are dropped, not stored. Until peinit can forward them to eventd, peios.quiet=1 means you lose peinit's narrative from the moment a sign-in prompt appears. On a machine you are debugging, boot with peios.quiet=0.

A few lines escape all of this: whatever peinit and prelude print before they have read the command line. Neither can honor a preference it has not seen yet, and those lines are also the only evidence either started at all.

Note

peios.quiet governs what peinit writes, and nothing else. The kernel's own console output is governed separately by the standard loglevel parameter, which shipped images set to 4 — errors and worse — so that peinit's narrative is not buried under the kernel's. The two are independent: setting peios.quiet=0 to debug a boot does not bring the kernel's messages back, and loglevel=7 ignore_loglevel does not make peinit any louder. Note also that raising loglevel alone will not undo a shipped ignore_loglevel, and that the image ships no dmesg, so at the default a kernel warning is not recoverable after the fact.

Seeing and changing it #

System Settings shows the command line this boot was started with, under Kernel Command Line in the Startup & Shutdown section, and the one the next boot image will be made from, /lcl/etc/boot/cmdline, where they differ.

On an installed machine the command line is part of the boot image, so editing that file changes nothing on its own. Dynamic Boot supplies mkuki-watch, but package delivery or feature enablement alone does not mean it is running or rebuilding successfully. Check its selected input, output filesystem, and completed rebuild using the activation checklist. With the feature installed, System Settings offers peios.bootattempts and peios.quiet as choices — how many boots can fail before Recovery, and what peinit writes on the console — and writes them into the file with Apply at Next Boot, which appears once one has been changed. Nothing else on the line is offered: a mistake there can leave a machine that doesn't boot. Writing the file needs write access to it, which as shipped only Administrators have.

Unknown peios.* tokens are ignored, as is a malformed value on a valued token — this parser runs before anything exists to report a diagnostic to, and refusing to boot over a typo in a tuning knob is the worse outcome.

Note

There is no token that selects services. Which services start is decided entirely by what is defined under Machine\System\Services — see Defining a service. A console shell or a sign-in prompt is an ordinary service definition with a TTYPath, not a boot flag.

Where peinit takes over #

peinit is PID 1, but it is not the first thing that runs. The initramfs assembles and mounts the real root — decryption, RAID/LVM, the root filesystem itself — and then hands control to peinit. The contract peinit relies on is narrow:

  • The real root is already mounted read-write, and /proc, /sys, /dev are mounted and moved into it.
  • peinit is exec'd as PID 1 from a fixed path on the real root.

peinit does not assemble, decrypt, repair, or even re-mount the root — those need tools and configuration that belong to the initramfs. It also does not fsck the root or mount non-root storage (a data partition is mounted by an ordinary Oneshot service, not by peinit). For the trust and identity side of this handoff — signatures, the SYSTEM token peinit inherits — see peinit at PID 1.

Phase 1: the hardcoded bootstrap #

Phase 1 is compiled into peinit. It cannot change at runtime and touches no registry. It does the minimum to make Phase 2 possible:

  1. Confirm the root is writable with a single probe write. registryd's storage needs a writable root even for reads, so a read-only root cannot support Phase 2 → Recovery.
  2. Mount the remaining virtual filesystems — /dev/pts, /dev/shm, /run, /sys/fs/cgroup — mounting each only if absent. A failure here → Recovery.
  3. Restore the persisted random seed from /var/state/peinit/random-seed , mixing it into the kernel's entropy pool early so anything that needs randomness during boot gets it. A missing seed is normal — first boots and stateless live boots have none — so peinit carries on; a seed problem is never fatal and never sends boot to Recovery.
  4. Establish the machine-id from /lcl/etc/machine-id — a stable, opaque identifier for this install (used for log correlation, instance identity, and software compatibility). It is not a security principal: it is not a SID, an account, or a credential, and no authorization decision depends on it. If the file is missing, empty, or malformed, peinit generates a fresh 128-bit ID. If it cannot persist the ID, boot continues with a warning and an ID valid only for this boot; failure to obtain random bytes sends boot to Recovery.
  5. Set the clock from the hardware RTC, so early timestamps and the boot counter are meaningful. A failure here → Recovery.
  6. Start registryd and wait for it to signal readiness, then probe-read the schema-version key to confirm it is actually serving reads. Any failure → Recovery — there is no Phase 2 without a registry.
  7. Provision boot-time paths. With registryd up and before Phase 2 starts, peinit applies the entries under Machine\System\Init\ProvisionedPaths\ — the registry-driven equivalent of tmpfiles.d, creating directories, and files (with Peios security descriptors) that no single service owns. Best-effort entries that fail are logged and skipped, but an entry marked Required=1 that cannot be provisioned sends boot → Recovery. The individual keys are cataloged in the registry key reference.
  8. Infrastructure setup — create the control socket and the jobs socket, and bring up the loopback interface. A control-socket or jobs-socket failure → Recovery; a loopback failure is logged as a warning and boot continues.

Most Phase 1 failures are fatal to a normal boot, because none of the later machinery can run without this foundation — the only outcome is Recovery mode. The exceptions are the fail-soft steps called out above: a missing or unusable random seed, a regenerated machine-id, and best-effort provisioned paths all let boot continue.

Caution

Packaged images, VM templates, and live ISOs must not ship a populated /lcl/etc/machine-id or a /var/state/peinit/random-seed file. A shipped machine-id gives every clone the same identity, and a shipped seed is a public value that is not acceptable entropy. Clone and reset tooling should remove or truncate /lcl/etc/machine-id so peinit generates a fresh ID on the next boot, and should never bake a seed into the image — if you need strong first-boot randomness for a stateless image, provide a real kernel entropy source (hardware RNG or virtio-rng) instead.

registryd #

registryd is an interface, not a specific program. It is the path peinit execs to get a registry source daemon — the component that implements the registry's persistent storage and answers peinit's reads. The implementation behind that interface can vary; by default it is loregd.

The distinction matters when diagnosing source failures: peinit's registryd role does not define a storage-repair interface. Check which provider and version the installation uses before choosing recovery instructions. The default provider's database paths come from its startup hive declarations, not registry settings. See LCS and sources for source availability checks and the Recovery-mode limits before direct storage work.

Phase 2: the registry-driven boot #

With registryd serving reads, peinit boots the rest of the system from the registry:

  1. Read all definitions under Machine\System\Services\. (A registry read timing out here → Recovery.)
  2. Build and validate the dependency graph from the boot-triggered services and their transitive dependency closure. Validation runs before anything starts.
  3. Start services in dependency order, in parallel up to MaxParallelStarts , with readiness gating releasing each service's dependents as it becomes satisfied.

Only services with a boot trigger are start candidates; demand-only services are pulled in only if something boot-triggered depends on them, and Disabled services are excluded from the graph (but kept in the model for on-demand start). The whole boot runs against one snapshot — mid-boot registry edits do not perturb it.

The installed service graph determines the platform order. registryd and authd use the SYSTEM bootstrap path; standard eventd and lpsd deployments use Identity=Service and obtain tokens through authd. See Service identity. A non-SYSTEM service's authority dependency is derived from its identity rather than left to an administrator to remember.

Do not infer readiness or shutdown order from a fixed list of daemon names. Check the installed definitions and the service status. The boot implementation describes graph construction and validation.

Where to start #

To understand the graph validation and parallel start that drive Phase 2, read Dependencies and ordering.

To understand the Critical-failure reboot path that feeds the boot counter, read Keeping services running.

For the trust and token side of early boot, read peinit at PID 1.

Prelude

Peios / Using Peios / Boot and Shutdown

Prelude starts the userspace part of Peios boot. It runs inside the initramfs, a small filesystem unpacked into memory, until boot hooks have made the real root filesystem available. It then replaces itself with the init that manages the running system.

The two programs keep the same process number, 1, but have different jobs. Prelude prepares one handoff. The real-root init manages services after it. Storage discovery, unlocking, and root mounting belong to hooks supplied by the image's packages.

From temporary root to real root #

Prelude mounts the kernel's process, system, and device filesystems. It seeds access control on existing device nodes, then reads the sequence of hooks written by mkirf. The sequence tells it which hooks can run and which capabilities each hook needs.

A hook mounts the real root at /mnt/rootfs. Prelude checks that this is a different filesystem from the temporary root, moves the kernel filesystems into it, removes the old temporary files where possible, and changes its root directory. A successful exec transfers control to the selected init. The complete parameter and path reference is prelude(8).

Why hook outcomes matter #

A hook can finish its work, decline because it does not apply to this machine, or defer because an input is not ready. Deferral is safe only when the hook has made no changes. Prelude retries deferred work after another hook makes progress; it does not retry a failed hook that might have left partial changes.

Capabilities let a hook depend on a result instead of another hook's name. For example, several storage hooks can contribute toward preparing storage. A later hook waits for their contributions before using it. The runtime format and precise outcome rules are described in prelude-hooks(5).

Hooks can source /usr/libexec/prelude/hook-log.sh for consistent status messages. The helper prints message text literally, so a backslash in a filename keeps its meaning when color is enabled.

Access control during boot #

The initial device policy grants full access to SYSTEM and Administrators. An inherit-only CREATOR OWNER entry gives a creator control over the objects it creates. The policy does not grant Everyone access: a broad inherited grant could expose raw disks as well as ordinary device nodes.

A failure to seed device descriptors produces a warning and boot continues. A hook failure or missing real root stops the handoff. Those outcomes need different responses; a completed boot does not prove every device received its intended descriptor.

Assembling and updating the temporary root #

The conventional source tree is /boot/initramfs. It must contain Prelude, its interpreter and helper dependencies, the hook sequence, and the drivers needed to reach the target root. The mkirf build resolves hook ordering; Prelude consumes that result. An ordinary source-tree edit does not change an already-built initramfs or UKI. Rebuild the artifact, deploy it through the image's boot workflow, and verify which artifact the next boot actually loads.

The temporary root is independent of the installed root. A helper available under the installed /usr is not thereby available before handoff. Include its dynamic loader and libraries, or use an appropriate static build. Do not assume runtime /bin and /lib views exist before their topology hook runs.

Module availability, dependency closure, loading, and root readiness are separate checks. Include modules matching the booted kernel and their required providers. A package-supplied coldplug hook can scan modaliases in a bounded settling window; Prelude itself is not a hotplug manager. A module loading failure matters according to whether a later hook can still prepare the root. Hardware that appears after that window needs the real-root device manager or an explicit boot design.

For storage changes, preserve a known bootable artifact and test the intended hardware or recorded VM image. Do not infer that every firmware-dependent or network-root configuration fits a generic storage-only module set. The exact init selection, fallback paths, and root-switch behavior are in prelude(8); the supplied image decides which candidates and tools exist.

Authoring hooks #

For capability declarations, runtime outcomes, and console reporting, read Writing Boot Hooks.

Bootstrap Descriptors

Peios / Using Peios / Boot and Shutdown

A newly mounted filesystem needs access control before boot tools can use it. The seed-sd helper establishes that initial security descriptor. Its bootstrap policy gives SYSTEM and Administrators full access and adds an inherit-only rule for the creator of each new object.

A template reaches later objects #

Inheritance applies the directory's template when a child is created. Changing the directory later does not rewrite every existing child. Prelude therefore calls seed-sd recursively on /dev, covering the nodes already present as well as the directory that supplies later inheritance.

The walker writes a node's descriptor before inspecting its descendants. That order allows it to enter a directory whose missing descriptor would otherwise deny access. Symlinks receive their own descriptor; the walker does not follow their targets.

Bootstrap policy has a limited purpose #

The default is suitable for making a fresh tree administrable. It is not a complete access policy for a running system. Granting Everyone read access at the device root would also reach newly created raw disk nodes, where reading the disk can bypass file-level access control.

A caller that prepares a different tree can supply an explicit descriptor with seed-sd --sddl. That caller owns the broader policy and its scope. The command's options, required privileges, and exit statuses are recorded in seed-sd(8).

Partial failure is visible #

Recursive seeding continues after errors where traversal remains possible. It reports failures and returns an unsuccessful status, but it does not undo descriptors already written. An installer or hook must use that status when deciding whether its own work succeeded.

The helper rejects command-line arguments containing invalid UTF-8 before applying any descriptor. During a recursive walk, a descendant name that cannot be represented as UTF-8 is reported as a failure and skipped.

Debugging Initramfs Boot

Peios / Using Peios / Boot and Shutdown

Use Prelude's recovery shell to inspect a boot that fails before the real-root init starts. A breakpoint lets you inspect or repair the temporary environment and then continue the same boot.

Before you start #

  • Use a disposable test image or a machine you can recover independently.
  • Have access to its boot parameters and boot console.
  • Include /usr/bin/sh and the inspection tools you need in the image.
  • Treat the recovery shell as privileged access to the boot environment.

Stop before the hooks #

  1. Add rd.break to the image's kernel command line and boot it.
  2. Wait for Prelude's breakpoint message and shell.
  3. Inspect /system/prelude and the hook scripts named by its sequence. This breakpoint occurs before Prelude reads that sequence, so an edit made here takes effect when you resume.
  4. Exit the shell to continue boot.

To stop before one hook instead, use rd.break= followed by its filename or complete path. For example, rd.break=mount-root matches a hook whose final path component is mount-root. Use the name present in your image. The full syntax is in prelude(8).

Inspect a failure #

  1. Add rd.shell to the kernel command line and boot the image.
  2. Read the failure message before using the shell. A hook error identifies the failed hook; an unsatisfied capability identifies pending work.
  3. Inspect the files and mounts that remain at the point of failure. Before handoff, the intended real root is /mnt/rootfs. After a root switch, paths resolve inside the new root.
  4. Exit when finished. A failure shell continues to the halt path, not back to the failed boot operation.

Check the result #

A successful breakpoint recovery reaches the real-root init. A failure shell ends at the halt path after you exit. If no shell starts, look for the reported exec error and check that /usr/bin/sh exists in the filesystem visible at that stage.

Do not start the Prelude executable from an ordinary terminal to reproduce a boot problem. Its operations include mount changes and removal of files from the old root.

Writing Boot Hooks

Peios / Using Peios / Boot and Shutdown

A boot hook performs a deployment-specific part of early boot, such as unlocking storage or mounting the real root at /mnt/rootfs. Prelude runs the generated hook sequence before handing control to the real init process. Put service startup and ongoing supervision in Peinit instead.

Before you start #

  • Prepare an initramfs source tree and a disposable boot environment.
  • Include each hook's interpreter, tools, and required drivers in that tree.
  • Read mkirf(1) for image construction and hook metadata syntax.
  • Arrange the access policy required by the storage operations you perform.

Hooks run under the bootstrap SYSTEM token. That authority does not remove kernel access checks or replace the security descriptors needed during boot. See Prelude for the stage's responsibilities and handoff checks.

Choose a location and declare dependencies #

  1. Put a packaged hook under usr/libexec/prelude/hooks.d/ in the image tree. Put an operator-owned hook under lcl/libexec/prelude/hooks.d/ instead.

  2. Give it a distinct filename, an available interpreter in its shebang, and executable permissions. An operator hook with the same filename replaces the packaged hook at image construction.

  3. Declare its capabilities in a comment block:

    #!/usr/bin/sh
    # /// hook
    # contributes = ["rootfs-ready"]
    # ///
    

This example declares part of the work needed for the real root. It is not a complete hook: append the required checks and operation before including it in an image. File extensions have no special meaning, and numeric prefixes are only filename tie-breakers, not a dependency mechanism.

Express what the hook needs and supplies #

The metadata distinguishes alternatives from work that must all complete:

DeclarationMeaning
providesAny successful provider can satisfy the capability
contributesAll contributors must complete their part
requiresThe capability must be achieved before this hook runs
afterIf supplied, wait for the capability's suppliers to settle

after allows an optional milestone to be absent. It does not assert that the milestone succeeded. Use requires when running without the achieved capability would be incorrect. A capability cannot mix provides and contributes suppliers.

Three shared milestones connect independently packaged hooks:

CapabilityMeaning
initramfs-readyThe initramfs topology and console are usable
rootfs-readyThe real root is mounted at /mnt/rootfs and ready for work
rootfs-strata-readyThe StrataFS topology exists inside that root

The builder orders declaring hooks after initramfs-ready unless they supply it or already declare a dependency on it. An image without a supplier does not gain a missing requirement from this implicit ordering. An explicit requires retains its stronger meaning.

For example, an unlock hook and a root-mount hook can both contribute to rootfs-ready. The mount hook can defer until the unlocked device exists. This allows independent storage layers to compose without naming every other hook. Where a prerequisite is known, declare it explicitly.

Return the right outcome #

ExitMeaningScheduler action
0The hook completed its workRecord success
69The hook has no applicable workRecord a deliberate decline
75Inputs are not ready and nothing changedRetry after other progress
OtherAn attempted operation failedStop boot with the hook's failure

A declining contributor has completed its part. A declining provider has not achieved its capability; another provider must succeed if a dependent hook requires it. Do not report success merely because the hook does not recognize the machine.

Check for readiness before making changes. Returning 75 promises that retrying the hook does not repeat a partially completed operation. Once an operation has been attempted and failed, return a failure instead of hiding it as a deferral. Prelude stops when a full pass makes no progress while work remains.

A hook killed by a signal fails. A hook stopped by job control is killed and reported as stopped; the boot environment does not provide an interactive job-control session to resume it. Failure does not roll back earlier hooks.

Selected root strategies should diagnose missing required inputs. The retained live-boot and disk-boot package recipes select one strategy through conflicting packages; they do not use runtime decline to choose between two broken configurations. A custom image needs its own explicit selection.

Report progress and failures #

Standard output and standard error go directly to the console. Prelude does not capture and relabel each line. If the image supplies the level-three prelude-hook-abi helper, source it and use your hook's own name:

. /usr/libexec/prelude/hook-log.sh
hook_log_init example-root
log "checking root device"
log_ok "root device checked"
log_skip "optional device absent"
log_warn "optional device unavailable"
log_fail "root device check failed"

Declare a dependency on prelude-hook-abi >= 3 when using this helper. log_warn and log_fail write to standard error; the other functions write to standard output. The helper observes the console color convention, including TERM=dumb in the kernel command line.

Use a progress verb for work about to happen and a completed verb only after success. Logging failure does not itself replace returning a failure status. Do not log secrets used to unlock storage.

Build and check the result #

  1. Check shell syntax with the interpreter used by the image, then build the archive with mkirf. Resolve warnings about replaced or undeclared hooks.
  2. Inspect the generated /system/prelude/hooks.seq.<n> files in the image. Confirm the chosen paths and capabilities. Do not edit generated sequences.
  3. Boot the disposable image. Exercise success, inapplicable hardware, missing inputs, deferred work, and operation failure.
  4. Confirm that /mnt/rootfs is a separate mounted filesystem and that the expected init process starts after handoff.

Prelude reads the newest supported sequence version. An unsupported version produces a warning when a supported fallback exists, or an error when none exists. The warning remains visible at peios.quiet=2. A missing sequence is an error; an intentionally empty manifest is distinct from a missing one. Malformed selected manifests also fail rather than silently rescanning hooks.

For discovery and dependency validation during image construction, see Building an Initial RAM Filesystem. A successful archive build does not establish that its tools, policy, or storage configuration can boot.

Building an Initial RAM Filesystem

Peios / Using Peios / Boot and Shutdown

mkirf builds an initial RAM filesystem, or initramfs, from a source directory. The kernel unpacks that archive to provide files needed before the final root filesystem is ready.

Source files and generated order #

Source-tree contents map onto the archive's root. The tree needs an executable init and supported entry types. Sockets and preexisting generated hook-sequence files are rejected.

Packaged hooks and operator-provided hooks can declare dependencies. Operator hooks take precedence when filenames match. The builder resolves those declarations into a valid order and emits versioned sequence files under /system/prelude without writing them into the source tree.

A missing required capability or a cycle prevents a valid order. A hook without metadata is handled separately, with a warning and a defined late-order position. Do not mistake that compatibility path for dependency validation.

Determinism is an archive property #

The builder sorts entries and normalizes metadata that would otherwise vary between runs. Regular-file executability remains significant, while ownership, timestamps, and archive inode numbers are normalized.

Compression settings also form part of the result. The default uses zstd; gzip is available for a kernel without support for the default format. Compare builds made with the same inputs, settings, and implementation. A deterministic archive does not itself prove a bootable or trusted image.

Early segments precede compression #

The kernel reads some content before it decompresses the main archive: CPU microcode and ACPI table overrides. This content forms the early part of the initramfs. Packages place it in /usr/lib/earlyirf/, and an administrator can place it in /lcl/lib/earlyirf/. Each child directory is one segment, and its contents map onto the archive root. For example, /usr/lib/earlyirf/intel-ucode/kernel/x86/microcode/GenuineIntel.bin becomes kernel/x86/microcode/GenuineIntel.bin.

A segment in /lcl/lib/earlyirf/ replaces the segment of the same name in /usr/lib/earlyirf/, and mkirf warns about the replacement. mkirf still reads segments from the old ++ directory at the root of the tree and warns about each one.

The segments are combined into an uncompressed early archive ahead of the main archive, which does not hold them. Conflicting entries are rejected rather than silently choosing a copy.

Watch mode is a build loop #

Watch mode builds once, then waits for source changes to settle before rebuilding. A failed rebuild is reported while the watcher remains available for a later correction. Keep the output outside the watched tree to avoid triggering a rebuild with its own output.

Successful writing replaces the output through a sibling temporary file. That protects against presenting a partial assembled archive; it is not a boot test or a full power-loss durability guarantee.

mkirf(1) defines source layout, hook rules, metadata normalization, compression, exclusions, and watch behavior. Validate the resulting image in the boot environment before selecting it for deployment.

Hook discovery and validation #

The builder scans regular files directly inside usr/libexec/prelude/hooks.d and lcl/libexec/prelude/hooks.d in the source tree. It does not recurse into subdirectories or select a particular extension. A filename identifies one hook; an operator copy wins over the vendor copy, with a diagnostic naming the replacement. The legacy root-level hooks directory is accepted with migration warnings.

A hook's metadata opens with exactly # /// hook and closes with # ///. Between those lines, each line is a comment. The supported keys are provides, contributes, requires, and after, each holding a list of double-quoted capability names. Empty lists and trailing commas are accepted. This is a restricted declaration format, not arbitrary TOML.

Unknown keys, malformed lists, duplicate or unclosed blocks, missing required capabilities, dependency cycles, and mixed provider/contributor definitions are build errors. A declared empty block differs from having no metadata. Undeclared hooks are warned about and placed after declaring hooks.

Dependency edges place suppliers before consumers. Filename order breaks ties between unrelated hooks. The builder materializes implicit initramfs-ready ordering in the generated manifest, retaining an explicit requires instead of weakening it to after. Prelude then consumes that manifest; it does not rediscover or reorder the source directories at boot.

Writing Boot Hooks explains capability achievement, decline, deferral, and console reporting. Image construction checks declarations; boot testing checks whether those claims match the hook's behavior.

Assembling a Unified Kernel Image

Peios / Using Peios / Boot and Shutdown

mkuki assembles a unified kernel image (UKI). It appends a kernel, an initramfs, and a command line to a firmware executable stub so that the boot payload travels as one file.

Three payloads and a stub #

The command line, kernel, and initramfs occupy separate named sections in the executable. The stub reads those sections at boot. The default stub is bundled into the utility; its provenance can be inspected separately.

Command-line input can come from a literal value or a file. Trailing line endings are removed and a terminator is added. Embedded zero bytes are rejected rather than silently shortening the command line.

Select a kernel image #

A concrete image path selects exactly that file. Directory selection reads vmlinuz directly in the selected directory, normally /usr/lib/modules. A Peios system closure has one kernel, at /usr/lib/modules/vmlinuz, with modules in the same directory and no release subdirectory.

Directory selection reads the image again after a directory changes. A missing image makes that rebuild fail while leaving the watcher available to retry.

Publication and signing are separate #

The assembled image is written through an exclusively created sibling temporary file and then replaces the output. A failed staging write does not replace the accepted output with a partial assembly.

The command does not sign the image. A complete firmware executable is not proof that its payloads are trusted or bootable. Signing, trust policy, and boot qualification are separate steps.

Watch the inputs without watching the output #

Concrete input files are observed through their parent directories so that atomic file replacement is visible. Directory selection watches the selected directory nonrecursively. Output paths that feed back into those watched locations are rejected.

After changes settle, the watcher rebuilds. Failure is logged rather than ending the loop, so the last output can remain older than the inputs. Monitor diagnostics instead of treating the existence of an output file as proof of a successful latest build.

mkuki(1) defines section construction, kernel selection, stub inspection, watching, and output failures.

Applying a Root Skeleton

Peios / Using Peios / Boot and Shutdown

skeleton apply makes the directories and links a root needs outside /usr. Packages only install under /usr, so /var, /lcl, /tmp and the /lib64 link to the dynamic loader come from a root skeleton file instead. The dev.peios.fsbase package ships that file at /usr/share/skeleton, and whatever builds a root applies the copy in that root's own /usr.

skeleton apply /mnt/root

The live-boot hook runs this after composing the live root. An installer or an upgrade tool runs it against the root it builds. --file applies another file instead of the root's own, and --verbose prints each entry it makes.

Making what is missing #

skeleton reads and checks the whole file, including every security descriptor, before it changes anything. A file with an error changes nothing.

It then works through the entries in order. It makes each missing directory or link, and leaves each existing one alone, even if its security descriptor differs from the file's. Running it again makes nothing new.

It stops with an error when something of another kind is in an entry's place, such as a file where a directory belongs, or a link with a different target. It never follows a link to reach an entry. Entries made before the error stay, so you can run it again after removing what was in the way.

Descriptors at creation #

A directory with a descriptor in the file is created with that descriptor in the same native create call. It never exists with an inherited descriptor first. A directory without one inherits from its parent.

A descriptor doesn't need to grant whoever applies the skeleton any access. The create succeeds even if the new descriptor would deny its creator.

The file's format is specified in PSPU 11.

Shutting Down and Rebooting

Peios / Using Peios / Boot and Shutdown

Use svctl shutdown when you intend to stop the machine. Choose one action:

svctl shutdown poweroff
svctl shutdown reboot
svctl shutdown halt

These are alternatives, not a sequence. Each interrupts running services and jobs and requires SYSTEM_SHUTDOWN. Save work and account for other users before issuing one. halt stops the CPU but leaves power on.

A normal shutdown stops dependents before their dependencies, gives running services time to exit, then unmounts, syncs, and performs the selected action. Forced shutdown skips that opportunity to finish work.

How shutdown is triggered #

There are four paths into shutdown, and they are not equal — three are graceful, one is not.

A control command. An administrator with SYSTEM_SHUTDOWN runs svctl shutdown <type> (the familiar reboot, poweroff and halt commands, and shutdown -r now, are the same client under other names):

TypeResult
poweroffStop everything, unmount, power off.
rebootStop everything, unmount, reboot.
haltStop everything, unmount, halt (CPU stopped, power stays on).

Signals. As PID 1, peinit treats a handful of signals as shutdown requests:

SignalMeaning
SIGINTReboot — the kernel sends this on Ctrl-Alt-Del.
SIGTERMPoweroff.
SIGPWRPoweroff — a compatibility path for environments that surface power failure or power-button policy as a signal.

The power button. On Linux, a physical power-button press is a graceful poweroff — peinit watches the machine's input devices under /dev/input and treats a KEY_POWER press (the key going down, not its release or auto-repeat) as a shutdown request. This path is deliberately minimal and fail-soft: if /dev/input is missing, an input device cannot be opened, or a device stops responding, peinit keeps running and drops that device — the button quietly stops working, but the machine stays up and you can still shut down over the control socket or with a signal. It is not a full power-management policy engine; a separate power-management daemon can add richer policy on top by sending control-socket commands.

A Critical service failure — the ungraceful path. When an ErrorControl=Critical service exhausts its restart budget, peinit syncs and reboots immediately. There is no service-stop ordering: the system is in an undefined state and the fastest route to a known one is a reboot. This is what feeds the boot-attempt counter, and a Critical service that fails identically every boot becomes a reboot loop that the counter eventually breaks by escalating to Recovery.

The graceful sequence #

For a poweroff, reboot, or halt, peinit runs an ordered sequence:

  1. Enter the shutdown state. A flag is set, and while it holds: no new services can start, timer triggers are disarmed, and new lifecycle commands are rejected with INVALID_STATE. Status, list, operation-status, boot, and job query/stop commands remain available so you can watch progress or stop a job sooner.
  2. Suspend Critical-failure semantics. If a Critical service fails during shutdown, it is logged but does not trigger a reboot — the system is already going down, and rebooting would loop.
  3. Clear Completed services. Oneshot services sitting in Completed (with RemainAfterExit) have no process; peinit moves them to Inactive so their dependents can be stopped cleanly.
  4. Stop every live submitted job at once — SIGTERM, then SIGKILL of the job's cgroup after its own stop_timeout — and cancel any job still queued to launch, both with cause shutdown. Jobs have no dependencies, so there is no order among them and nothing waits for them to finish before the service waves begin; but shutdown does not complete while a live job remains, within the same global timeout.
  5. Stop services in reverse dependency order, in waves. Each graceful-stop-eligible service (those in Active or Reloading) gets SIGTERM and StopTimeout seconds to exit; if it does not, peinit SIGKILLs its whole cgroup. A service is never stopped until everything that Requires or BindsTo it has already stopped. Services that are Starting are not stopped gracefully — their startup is canceled and the cgroup SIGKILLed.
  6. Enforce the global timeout. The whole sequence is bounded by ShutdownTimeout (default 90 s). When it expires, all remaining services are SIGKILLed; any whose cgroups do not empty within the post-kill timeout (default 5 s) become Abandoned (leaked), and shutdown continues regardless.
  7. Save the random seed. With every service stopped and before any filesystem is touched, peinit writes a fresh seed drawn from the kernel's CSPRNG to /var/state/peinit/random-seed — this is the entropy the next boot starts from. The write is crash-conscious (written to a temporary file, flushed, then atomically swapped in), and it is best-effort: if it fails, peinit logs it and carries on. Shutdown never stalls on it, and the forced and Critical-reboot paths skip it entirely in favor of getting the machine down fast.
  8. Unmount filesystems. peinit snapshots the mount table and tries to unmount every remaining non-root mount in its namespace — not only the ones it mounted itself — working from the deepest mount points outward. That includes the Phase 1 set (/proc, /sys, /dev, /dev/pts, /dev/shm, /run, /sys/fs/cgroup) wherever those are still mounted. A mount that is already gone counts as done. If one won't unmount because it is busy, peinit falls back to remounting it read-only; anything it still can't clean up is logged and left for the final sync() and the kernel, never blocking shutdown. The root filesystem (/) is never unmounted — once the rest are handled, peinit remounts root read-only.
  9. Sync and finish. sync() to flush pending writes, then the final action — power off, reboot, or halt.

The reverse ordering falls straight out of the dependency graph; there is no separate stop-order configuration. Shared platform services stop after their dependents, with registryd last. The exact order is derived from the installed graph.

STOPPING=1 and timeout extension #

A service that begins shutting down on its own — say, in response to an internal error — can tell peinit by sending STOPPING=1 through sd_notify. peinit acknowledges it and, importantly, stops sending SIGTERM to that service: it is already on its way down, and a redundant signal could interfere.

STOPPING=1 is a courtesy, not a timeout extension. The StopTimeout keeps running; if the process has not exited when it expires, peinit escalates to SIGKILL regardless. A service that genuinely needs longer must say so with EXTEND_TIMEOUT_USEC (see Keeping services running) — and during shutdown those extensions are capped not only by the per-service StopTimeout × 4 but also by the remaining global ShutdownTimeout, whichever is smaller.

Forced shutdown #

Warning

Forced shutdown kills processes without waiting for graceful completion. Unfinished application work can be lost. Use it only when the normal shutdown cannot finish.

When the machine must be stopped despite a stuck graceful shutdown, repeated SIGINT forces it: three Ctrl-Alt-Del presses within five seconds skip the graceful sequence entirely — SIGKILL everything, sync, reboot. It is the escape hatch for a graceful shutdown that is itself stuck behind an unresponsive service.

Shutdown during boot #

A shutdown requested while peinit is still in Phase 2 boot takes effect immediately: services still Starting are SIGKILLed (they never reached Active, so there is nothing to stop gracefully), services that did reach Active are stopped per the normal sequence, and the boot is abandoned.

How peinit handles signals #

peinit handles all signals through a signalfd read from its event loop — every signal is blocked and read as data, so there are no async signal handlers and no async-safety hazards. PID 1 cannot be killed by any signal; the kernel protects it.

SignalBehavior
SIGCHLDReap children; match exits to services and submitted jobs. Also reaps orphaned processes the system reparented to PID 1.
SIGINTReboot request. Repeated within the window → forced reboot.
SIGTERMPoweroff request.
SIGPWRPoweroff request — compatibility path for power-button/power-failure policy.
SIGHUPIgnored — PID 1 has no controlling terminal.
SIGPIPEIgnored — a broken control-socket pipe must never crash PID 1.

All other signals are ignored.

Note

Reaping orphans matters: when any process anywhere on the system dies leaving children, those children are reparented to PID 1. peinit reaps them so they do not accumulate as zombies — even though they were never its services. This is part of the job of being PID 1, distinct from supervising services.

Where to start #

To understand the reverse ordering and which relationships gate it, read Dependencies and ordering.

To understand the Critical-failure path that bypasses graceful shutdown, read Keeping services running.

For the boot side of the lifecycle and the reboot/recovery escalation, read Boot and boot modes.

The Registry

Peios / Using Peios / The Registry

The registry is where Peios keeps configuration: service definitions, network profiles, sign-in policy, desktop preferences, and the settings of almost every component. It is a tree of keys holding typed values. The kernel decides who can read or change each key. It also lets an installed role, a policy, and an administrator each set the same value without overwriting one another. Understanding that model explains why a value you set might not be the one in effect.

Hives, keys, and values #

A path through the registry names a key, from the top of the tree down:

Machine\System\Services

The first part of every path is a hive, a top-level tree. A standard system has two:

  • Machine holds settings for the whole machine.
  • Users holds one subtree for each account, named by the account's security identifier (SID): Users\<SID>.

CurrentUser is a shortcut, not a third hive. At the start of a path, it stands for Users\<SID> of the account the calling program runs as. Other components can register further hives.

A key contains subkeys and values. A value is a named piece of data with a type. A key can also have one value with an empty name, its default value. The types you meet most are:

TypeHolds
REG_SZA UTF-8 string
REG_MULTI_SZAn ordered list of strings
REG_DWORDA 32-bit unsigned integer
REG_QWORDA 64-bit unsigned integer
REG_BINARYRaw bytes

Names are case-insensitive but keep the case they were created with, so Machine\System\Services and machine\system\services are the same key. The backslash is the separator. Tools also accept a forward slash, which is easier to type in a shell.

Layers #

Each value can have several entries at once, one from each layer that has set it. A layer is a named collection of registry writes that can be managed, and removed, as a unit. When a program reads a value, the kernel returns the single winning entry: the effective value.

Two numbers decide the winner:

  • Precedence. Every layer has a precedence. The highest precedence wins.
  • Sequence. Among layers with the same precedence, the most recent write wins.

The base layer is built in and is always present. It has precedence 0, and a write that names no layer goes to it. Layers that a role installs also sit at precedence 0, so the most recent write among them wins. Policy layers sit above 0 and override both. Giving a layer a precedence above 0 requires SeTcbPrivilege; being a local administrator doesn't grant it on its own.

Layers make configuration reversible. Deleting a layer removes its entries, and the next entry down becomes effective again. A layer can also mask a value, so that the value reads as absent while the layer is in effect.

When a read seems wrong, check which layer won. reg and Registry Editor both report the winning layer for each value.

Who stores the registry #

The kernel holds none of the registry's data. Programs called sources store it, and the kernel asks them for entries when it needs them. On a standard system, the source is loregd, which keeps the Machine and Users hives in database files under /var/state/loregd.

The kernel makes every decision: which layer wins, who can see a key, and who can change it. A source only stores what it is given. Programs reading and writing configuration always talk to the kernel, never to the source.

A key can be volatile, which tells its source not to keep it in permanent storage. loregd holds volatile keys in memory-backed files, so they disappear whenever loregd restarts, even if the machine doesn't.

If a source stops, its hives become unavailable and requests for them fail until it returns. Sign-in and other services depend on the registry, so a storage failure can affect much of the system. Diagnosing Registry Storage Failures covers recovery.

Who can read and change a key #

Every key has a security descriptor, which records who owns it and who can do what to it. The kernel checks the descriptor once, when a program opens the key, and the program keeps the access it was granted for as long as the key stays open. Values don't have security descriptors of their own: the key's descriptor covers all of them.

The kernel checks only the key being opened, not the keys above it. A program can open Machine\System\Services\netd without any access to Machine\System\Services.

Changing a key's security descriptor doesn't affect programs that already have it open. Security descriptors aren't layered either, so removing a layer doesn't undo a change to one.

Documentation and live state #

Each component installs a manual for the registry settings it owns. regman reads those manuals. It tells you what a value means, which values are valid, and when a change takes effect, but it doesn't read the live registry. Use reg or Registry Editor to see what is actually set.

Storing a value doesn't prove that its component accepted it. The component that reads a setting checks it and decides when to apply it, so check that component after a change.

Where to start #

These pages cover the tasks:

  • Finding a Registry Setting to find the owner and live state of a setting before you change it.
  • Changing a Registry Setting to make a change from the command line and confirm that it applied.
  • Registry Editor to browse and edit the registry on the desktop.
  • The SDK's Registry Overview to use the registry from your own code.

Registry Reads, Writes, and Layers

Peios / Using Peios / The Registry

reg reads and changes the live registry. regman explains the intended meaning of a setting; it does not read the value configured on this machine. Consult the documentation before changing a setting whose accepted values you do not know.

Keep the key and value name separate #

The key path and the value name are separate arguments. A value name can contain separators that are not allowed inside a key-path component. The special value-name token @ selects the empty-name default value.

Value literals have types. Numeric-looking input can be inferred as a number, losing a textual spelling such as leading zeros. Use an explicit string type when those characters are part of the value's meaning. Inspect the resolved type reported after a successful write.

The empty-name default value is unrelated to a consumer's documented fallback when an entry is absent. To preserve text such as 007, use an explicit literal such as sz:007. Quote backslash paths in a shell, or use forward slashes. reg(1) owns the full type-prefix and encoding reference.

Names preserve display case and compare without locale-sensitive case rules. They are not Unicode-normalized, so visually identical names can remain distinct. Ordinary value data is opaque to the registry; its consumer checks whether the bytes make sense for the type and setting. A link key's target has additional interpretation by the kernel.

A volatile key describes storage lifetime, not when a setting applies. Check reg info for volatility and the setting's manual for application timing.

Choose a layer deliberately #

An effective read resolves the visible value across layers. Deleting an entry in one layer can reveal a lower entry. Masking hides lower values instead, while hiding a key affects path visibility.

These are different operations, not interchangeable ways to remove data. Select the layer and understand the lower state before changing either. Security-descriptor changes affect the key object directly; removing a configuration layer does not undo them.

The winner has the highest precedence, then the newest write sequence within that precedence. A sequence is not a timestamp or a history of previous values. Base and role layers can share precedence zero; writing to base does not prevent a later role update from winning. reg get KEY NAME -L reports only the effective winner, not every hidden entry.

See Recovering a Registry Layer before disabling or removing configuration, and Removing Registry Entries before choosing between withdrawal and masking.

Separate exchange from exact backup #

JSON export and apply provide a reviewable representation of keys and values. A batch applies within one hive transaction. It is not a cross-hive transaction. Export does not claim to preserve every security component.

Text export is useful for review, but the text import path is not implemented. Use the supported JSON document when applying an export. Opaque backup and restore use a different kernel mechanism and require the corresponding privileges.

Use Applying a Registry Batch for related edits and Backing Up Registry Configuration for recovery.

Treat notifications as prompts to reread #

A registry watch tells you that relevant state changed. Reread the state needed by your application; do not treat the notification itself as the complete new configuration.

For an operator watch, run this in a terminal and read the current values from another:

reg watch Machine/System/KMES --subtree --filter value
reg get Machine/System/KMES BufferCapacity -L

The watch command remains running until interrupted; the second command is a separate read. Watch permission does not grant permission to read descendant values. The command reports changes without decoding every detailed record.

Watches describe effective-state changes, not every hidden layer write. After overflow, an interruption, restore, or source reconnection, read the required key or subtree again. A watch follows its opened key object; if a replacement key takes the same path, reopen the path and arm a new watch. Uncommitted transaction changes are not consumer notifications.

Operations use the caller's authority. Interactive confirmation protects against mistakes but is not an access check, and redirected input can change prompting behavior. reg(1) defines types, layers, batch syntax, confirmation, and status codes.

Inspect a link rather than its target #

Normal opens follow registry links. To inspect a suspected link itself, replace KEY with its path:

reg info KEY --no-follow
reg get KEY @ --no-follow -L

Check the link flag and the winning unnamed target value. A link flag is fixed at creation; storing REG_LINK in an ordinary key does not create a link. Conversely, a winning value of the wrong type can break resolution of a flagged link. A target is literal: CurrentUser is not expanded inside it.

Targets are layered, so withdrawing a target entry can reveal a different one. Check both the stored target and the resolved object after repair. reg(1) defines which mutating commands support operating on a link itself; do not assume every command accepts the inspection options above.

Diagnose access to a key and a layer #

A write needs the key's operation rights and access to its destination layer. Use reg sd for the key's owner, group, and DACL; reading its SACL needs ACCESS_SYSTEM_SECURITY. Values have no separate descriptors.

Inspect layer metadata permissions as well as the target key. Its Owner value is informational, not an authorization grant. Creating or promoting a layer above precedence zero needs SeTcbPrivilege. Merely being a local administrator does not establish that privilege.

Do not create Machine\System\Registry\Layers\base as an exploratory repair. Without that metadata key, a compiled descriptor allows Authenticated Users to write into base, subject to target-key access. Creating the key replaces that fallback with its real descriptor; inherited read-only grants can unexpectedly prevent personal configuration writes.

A parent's readability does not establish a child's permissions, and LCS does not apply filesystem-style traverse checks to each path component. Inheritance applies when a key is created. Editing a parent's descriptor does not rewrite existing descendants or revoke rights on existing handles. Reopen the key when testing a changed descriptor. The kernel's access flow and layer authorization references define the checks.

Finding a Registry Setting

Peios / Using Peios / The Registry

Find a setting by its purpose and consuming component. A path can contain operator configuration, a runtime observation, or personal preferences; those are different kinds of data.

Find and inspect #

  1. Search installed manuals with a term from the setting's purpose:

    regman -k buffer
    
  2. Read the matching key and value documentation. Confirm its owner, scope, type, accepted values, and application timing.

  3. Inspect live state with reg or Registry Editor. Keep the key path and value name separate. A documented default can apply even when no live entry exists; do not create one solely because it appears in the manual.

  4. Follow Changing a Registry Setting when the intended change and recovery are understood.

Common owners #

PurposeStarting locationOwning guidance
Service definitionsMachine\System\ServicesService configuration
Boot and init settingsMachine\System\InitBoot modes
Network profiles and reported stateMachine\System\NetworkProfiles and name resolution
Shared authentication grantsMachine\Generic\Authn\PolicyGranting Access
authd source registrationMachine\Software\Authd\SourcesRegistering a Principal Source
Personal preferencesUsers\<SID>The component consuming the particular key

This is an orientation map, not a complete schema. A shared format under Machine\Common, such as SecurityDescriptorBuilder, is still defined by its consumers' documentation; it is not automatically part of a specification. Use the installed manual for the specific value.

Identity and reported state #

CurrentUser is an alias resolved from the calling thread's effective token. A service or impersonating thread can therefore address a different account from an interactive shell. The kernel's hive routing reference defines the alias's limits. It is not a separate hive or a universal substitution inside every stored string.

Machine-to-user fallback is consumer-specific. Session locales combine corresponding machine and personal values; that rule does not apply to unrelated settings.

Services also publish facts. For example, netd's status and readiness describe observed network state. Change its documented profiles to request behavior; do not edit a reported address and assume that it configures an interface. Remembered DNS observations are distinct from active resolver state and configured resolver overrides.

Missing or unreadable #

A missing manual entry can mean documentation is absent. A missing live value can select a documented fallback. Access denied means the caller lacks the right for that operation; listing a parent does not establish access to a child's contents.

Check the actual descriptor. There is no universal rule that every registry key is readable by everyone, and knowing a path grants no access to it.

Finding a Setting's Meaning

Peios / Using Peios / The Registry

regman reads the documentation shipped for registry settings. It explains what a key or value means, what values are accepted, and which component owns it.

Documentation and state answer different questions #

A documented default is not necessarily the value configured on this machine. regman does not query the live registry. Use reg for the effective value and its available provenance.

The component that consumes a setting decides whether it is meaningful. Successfully storing a value does not establish that the consumer accepted it. Read the setting's type, range, and application behavior first.

Start with a name or a search term #

An exact key and value lookup is useful when an error names the setting. A key lookup groups its documented values, while a search finds names and summaries when you know the subject but not its location.

Some components document a family of keys using wildcard paths. An exact record is more specific than a matching family description. Read the resolved path so that you know which documentation answered the query.

Installed packages supply the corpus #

Packages place their registry manuals under /usr/share/regman. A missing entry can mean that documentation is absent; it does not establish that the live key is absent. Overlapping definitions are reported rather than silently treated as one authoritative record.

The lookup index is an accelerator. Invalid indexes fall back to reading the manuals instead of serving unchecked index data. Authors can format, lint, and rebuild the index as part of preparing a package.

regman(1) defines lookup, search, path selection, and authoring commands.

Changing a Registry Setting

Peios / Using Peios / The Registry

A registry write changes stored configuration. Its consumer still decides whether the data is valid and when to apply it. Verify both storage and behavior before treating an edit as complete.

Before you start #

Find the owning component and confirm that the value is configuration rather than a reported fact. You need access to the exact key and the destination layer. Keep a working route to the machine if the change affects access.

Read the setting's registry manual. Record its type, valid range, default, and application timing. regman reads installed documentation, not live state. A missing manual entry is not permission to try arbitrary values.

Inspect, change, and verify #

  1. Inspect the setting and its manual. For example, these commands read the kernel event-buffer setting without changing it:

    regman 'Machine\System\KMES' BufferCapacity
    reg ls Machine/System/KMES -l
    reg get Machine/System/KMES BufferCapacity -L
    
  2. Record the current type, effective value, winning layer, and sequence. If the value is absent, record that instead. -L shows the winning entry; it does not enumerate every entry hidden beneath it.

  3. Prepare recovery appropriate to the change. A JSON export is useful for review but does not preserve everything an opaque registry backup does. Include permissions and layer definitions when recovery depends on them.

  4. Write the intended value with an explicit type and destination layer. For example, only after confirming that an 8 MiB event buffer is the intended configuration:

    reg set Machine/System/KMES BufferCapacity qword:8388608 --layer base
    reg get Machine/System/KMES BufferCapacity -L
    
  5. Check the effective value and type. Follow the manual's application point: a live change, service restart, or reboot. Inspect the consumer's state and events, then test the behavior the change was intended to alter.

The desktop equivalent is Changing Registry Values. It still requires the same choice of layer and separate consumer check.

Interpret a different result #

A higher-precedence layer can keep a successful write from becoming the winner. At equal precedence, write order chooses the effective entry. Do not repeat base-layer writes to try to override stronger policy.

A conditional write checks the destination layer's entry. A sequence reported for a winner in another layer is not a version of the entry you intend to change. Read reg(1) before using --expected-seq in automation.

A watch notification reports a registry change, not consumer acceptance. Some consumers reject invalid configuration and keep their last valid state; others have a documented compiled fallback. Read the component's rule and rejection diagnostic. Do not assume every component repairs, clamps, or resets a value in the same way.

Recover and check again #

After a timeout or source failure, read back inspectable state before retrying. A dispatched write or commit can have succeeded despite a lost reply.

Restore the intended entry in its intended layer, or withdraw that layer's entry through the supported tool. Deletion can reveal a different winner rather than select a compiled default. Removing a layer does not restore a key's previous security descriptor or undo actions a service already took.

Repeat both the stored-state check and the consumer check after recovery. If storage is unavailable, start with registry storage failure diagnosis instead of editing backing databases.

When two readers see different state #

Compare effective thread credentials before comparing registry results. A private hive can shadow the global hive, and a privately attached layer can remain active when disabled globally. Impersonating threads in one process need not share a view. An administrator's global read or backup therefore need not describe a sandbox's private configuration.

The kernel defines private hive routing and private layer attachment. The workload's isolation mechanism controls these attachments; reg does not manage them. Limits on scopes and layers can also reject an operation without a key-permission failure.

Registry Editor

Peios / Using Peios / The Registry

Registry Editor displays keys, values, and their registry documentation. A key is a container; a value is named data with a type. The editor reads as your account and distinguishes unavailable access from an empty key.

The tree starts at Machine, Users, and CurrentUser. A direct path can reach a readable child even when you cannot list its parent. The detail pane shows a value's data, type, size, and winning layer, or information about the selected key.

Stored data and documented defaults #

The registry manual supplies descriptions, expected types, defaults, and application timing. Documented values absent from the key are shown as Not set. These are explanatory entries, not stored data or exported values. A type mismatch or malformed value is shown instead of being silently repaired.

A saved registry value can still be rejected by its consuming component. Follow its manual and inspect its status after a change.

Layers #

Writes go to selects the destination layer. A value's displayed winner can come from another layer. Writing a lower layer does not displace an entry with higher precedence. Deleting a value removes the selected layer's entry, so another entry can become visible instead of the value becoming absent.

Layer management changes whole sets of entries. Positive precedence needs the operating-system privilege SeTcbPrivilege; being an administrator is not sufficient by itself. Key owners and permissions are not layered: disabling a layer does not undo a descriptor change.

Export and backup #

Export creates a reviewable registry document of keys and values. Back up includes security descriptors and tagged layer entries. They are not interchangeable recovery formats. A backup's layer manifest does not recreate missing layer definitions on its own.

Import writes the selected document into the chosen layer in a transaction. Restore replaces the target's contents and subtree, including its descriptor, rather than merging into the current contents. Backup and restore have their own privilege requirements.

For a controlled edit, follow Changing Registry Values. The command reference is gxwi-registry-editor(1); the registry's shared semantics remain owned by its own documentation.

Changing Values in Registry Editor

Peios / Using Peios / The Registry

A registry edit changes stored configuration. To establish that the change worked, verify both the resulting entry and the component that reads it.

Before you start #

You need Registry Editor and access to the exact key and destination layer. Record the existing value, type, layer, and relevant permissions. Choose an export or backup suited to the recovery you need.

Edit one value #

  1. Open Registry Editor and navigate to the key, or enter its path and select Go.
  2. Select the value and read its registry manual, including valid values and when a change takes effect.
  3. Check Writes go to. Confirm the selected destination even when a different layer supplies the displayed value.
  4. Open Edit, enter the intended data, and select Save. For a documented but absent value, use Set.
  5. If the editor reports a concurrent change, refresh and inspect the new state before submitting another edit.

Check the result #

Use Refresh or F5. Inspect the value, type, and winning layer. Then inspect the consuming component at the time its manual requires. A conditional write protects the destination layer's entry, not every possible change to a winner in another layer.

Deleting and recovering #

Deleting a key removes its subtree in one transaction or fails. Large subtrees can exceed transaction or open-handle limits. Agree the intended smaller scope before splitting a failed deletion, because several transactions are not one atomic operation.

Deleting a value can reveal a surviving entry from another layer. A saved change or deletion does not by itself select the consumer's compiled default.

Read an import or restore target before confirming it. After a timeout or source failure, inspect current state before retrying: an error alone does not prove that a transaction was rolled back. Changing permissions affects future opens; existing handles retain rights already granted.

Changing System Settings

Peios / Using Peios / The Registry

System Settings changes machine-wide time, locale, startup, and identity settings. Personal account choices belong to My Settings, and shell appearance belongs to Desktop Settings.

Before you start #

You need access to write the relevant registry key or configuration file. Some immediate operations also require a daemon control right. Record the existing setting before a change that needs a restart or affects access.

Change a setting #

  1. Open System Settings and choose the relevant section: Time & Date, Language & Keyboard, Startup & Shutdown, or About.
  2. Inspect the current value and its scope. A switch or list choice applies when selected; typed values use the associated Apply, Save, or Set Clock action.
  3. Make one intended change and read the status line. A refused immediate choice is put back.

Check the result #

The window rereads state every five seconds. Verify the consuming service or the next session as appropriate, not only the stored field.

Time settings are read by timed; setting the clock manually needs its control right and automatic time disabled. Console keyboard changes try to restart the keymap service when permitted; otherwise they take effect at boot. Machine locale defaults affect new sessions. The machine name is applied by netd.

Startup settings include peinit stage timing, console automatic sign-in, and selected kernel-command-line options when dynamic boot is available. Changing the next boot image's inputs does not change the running kernel. See gxwi-system-settings(1) and each setting's registry manual.

The language and format selections save LANG with the time, number, money, measurement, and paper categories. Use reg when changing one independently configured category. For personal precedence and new-session checks, follow Choosing Session Locales.

Removing Registry Entries

Peios / Using Peios / The Registry

Decide whether the intended result is to withdraw one layer's contribution or make a name absent despite contributions beneath it. These are different operations.

Choose the operation #

Intended resultOperation
Withdraw a layer's value entryreg delvalue
Keep a value absent over lower entriesreg mask
Withdraw a layer's key-existence claimreg delkey
Hide a key over lower claimsreg hidekey
Remove the corresponding absence markerreg unmask or reg unhidekey

reg mask --all creates a blanket value mask. It does not delete every stored value. Use reg(1) for exact arguments and layer selection.

  1. Inspect the target and winning layer, then save the recovery data needed for that scope.
  2. Select the destination layer explicitly. Do not assume withdrawing its entry makes the name absent: another layer can become visible.
  3. Run the operation appropriate to the intended result.
  4. Reopen the path, inspect the effective state, and verify the consumer. Removing an absence marker can reveal data that has changed since masking.

Key deletion requires key deletion rights; value changes need value-write rights. Both also require applicable layer access. Hive roots cannot be hidden or deleted through these operations.

Recursive removal and existing handles #

reg del -r uses one transaction and does not follow registry links during its recursive walk. Resource and transaction limits still apply; a large walk can fail. Terminal confirmation is not shown with redirected input.

A lost commit reply leaves the outcome uncertain. Read state before retrying rather than assuming nothing changed. Existing handles can continue to refer to an orphaned key after its path disappears. A replacement at that path is a different object; reopening is necessary to inspect or watch it.

Applying a Registry Batch

Peios / Using Peios / The Registry

Use a reviewed JSON registry document when several entries must become visible together. A transaction provides registry atomicity, not simultaneous application by every service that consumes the settings.

Review, apply, and verify #

  1. Review every operation and its destination layer. All operations must target one hive, even when several hives share one source. Descriptor changes are security changes and require their own review and rights.

  2. Save recovery data appropriate to the changes. A JSON export contains visible keys and effective values, not every descriptor or layer entry.

  3. Apply the document:

    reg apply reviewed.json
    
  4. Inspect the affected entries and verify consuming services. If a commit times out or loses its source reply, inspect state before resubmitting: storage can have committed despite the reported failure.

Text export is for review; text batch input is not implemented. reg(1) defines the supported document schema.

Boundaries of the transaction #

reg apply --dir DIR applies each file as a separate transaction. A directory import is not one atomic unit. Transactions have bounded time and size, no nesting or savepoints, and require source support. Splitting a failed batch can break the consistency requirement that motivated it.

Readers outside a transaction do not see its intermediate writes. Bound reads see that transaction's pending changes. This does not provide value-level conflict detection: if a write depends on an unchanged entry, use --expected-seq with the destination layer's own sequence. reg get -L only exposes that sequence when the destination is the effective winner.

A layer makes entries removable later; a transaction publishes related changes together. Neither is an undo history, and removing a layer does not reverse descriptor changes. A late successful commit can still notify watchers after the caller's timeout. Closing an uncommitted transaction aborts it, but cannot undo an already-dispatched successful commit.

Backing Up Registry Configuration

Peios / Using Peios / The Registry

Choose the format according to the recovery requirement. JSON exchange and opaque registry backups preserve different information.

NeedMechanismLimit
Review visible configurationreg export --json KEY FILE, then reg apply FILEDoes not preserve key descriptors or the complete layered store.
Restore a subtree with its descriptors and tagged entriesreg backup KEY FILE, then reg restore KEY FILEPrivileged replacement, not merge.
Withdraw a managed bundleIts role or policy workflowLayer removal cannot undo permissions or consumer side effects.

Registry Editor exposes the corresponding Export…, Import…, Back up…, and Restore… actions. Text export cannot be reapplied as a text batch.

Capture a recovery copy #

  1. Identify the subtree and the permissions, layers, and consumers that recovery must preserve. Choose protected storage: backup privilege can expose data unavailable through ordinary reads.

  2. Capture the subtree, for example:

    reg backup Machine/System/KMES kmes.snap
    
  3. Confirm success and retain the file with its original path and purpose. Interrupted output is not a verified recovery copy.

  4. Check whether required layer definitions are also backed up. A stream's layer manifest records metadata for validation but does not recreate definitions. Their keys under Machine\System\Registry\Layers must be included or recovered separately.

Backup uses a consistent snapshot while other writes continue. It includes key descriptors, layer-tagged entries, and absence markers. Integrity checks detect corruption; they do not make an untrusted backup safe to restore.

Restore and verify #

  1. Confirm the trusted backup matches the intended target. Save current state if recovery from the restore itself is required.

  2. Review replacement scope, restored permissions, needed layer definitions, and consumer application timing. The backup root's immutable volatile and link flags must match the target.

  3. With replacement approved, restore the earlier example:

    reg restore Machine/System/KMES kmes.snap
    
  4. Reopen paths and inspect representative values, descriptors, and reg layer ls -l. Then verify consumers and their events. Existing handles retain their granted rights, so use fresh opens to test access.

Restore keeps the target key object, replaces its mutable fields and contents, and replaces descendants. It uses one transaction. Rejection before commit leaves no partial restored subtree; a timeout after dispatch can leave an uncertain outcome. Inspect before retrying. Terminal input prompts for confirmation; redirected input proceeds without that prompt.

Entries whose layer definitions are missing remain inactive until metadata exists. Restored entries also receive fresh ordering; recovery is not a way to restore the global write counter.

Required authority #

Backup and restore use SeBackupPrivilege and SeRestorePrivilege, bypass ordinary per-key checks, and are audited independently of key audit policy. Restore can rewrite owners and permissions, including the target key's own descriptor. Positive-precedence layers in the manifest or existing metadata also require SeTcbPrivilege; restoring their metadata has its own gate.

Read the kernel's backup and restore reference before building a recovery tool. A global-hive backup does not include an unrelated private hive shadowing the same path for another credential scope.

Recovering a Registry Layer

Peios / Using Peios / The Registry

A layer keeps a bundle's entries identifiable and removable. It is not a snapshot of everything the bundle changed. Prefer the owning role or policy tool when it also manages files, service actions, or other state.

Inspect and recover #

  1. Record the effective value, its winning layer, and its sequence with reg get KEY NAME -L. Inspect the layer inventory with reg layer ls -l.

  2. Identify the layer's owner and recovery procedure. Save required data and layer metadata before changing it. A narrow subtree backup need not include the definitions that make its layer entries active.

  3. If the owner's workflow permits it, disable the named layer first:

    reg layer set NAME --disable
    
  4. Reread representative values, check the newly winning layer, and verify each affected consumer at its documented application point. Re-enable with --enable if the trial does not produce the intended result.

  5. Delete a layer only after its owner confirms it is unneeded and the replacement state is verified. reg layer del NAME is destructive. Its terminal confirmation is absent with redirected input.

Replace KEY, NAME, and the value name with the reviewed targets. The built-in base layer cannot be disabled or deleted.

Limits of layer recovery #

Disabling a layer removes it from ordinary global resolution. Credentials that explicitly attach the layer can still see it. Inspect the workload's effective thread credentials before concluding that it sees the same state as an administrator's shell.

Removing a layer does not restore key security descriptors, reverse actions already taken by services, or reconstruct earlier values overwritten within that layer. Consumers do not necessarily apply the new winner immediately.

An ordinary write into a new layer is different from retaining previous versions. Equal-precedence layers use write sequence as their tiebreaker, not a fixed order of role names. See Registry Reads, Writes, and Layers for effective reads and authorization.

Operating loregd

Peios / Using Peios / The Registry

loregd supplies the local registry hives that Peios needs during boot. peinit selects the hive names and database paths and supervises the daemon. You normally use the registry through its kernel interfaces rather than starting loregd yourself.

Startup requirements #

The daemon needs these resources before it can serve the registry:

  • A SYSTEM token and SeTcbPrivilege for native protection and RSI access.
  • A Peios kernel with RSI lifetime extension version 1.
  • Writable persistent database paths supplied as hive declarations.
  • A tmpfs-backed /run where it can create and lock /run/loregd.

peinit supplies Machine=/var/state/loregd/Machine.hive and Users=/var/state/loregd/Users.hive. loregd itself has no path defaults and reads no configuration file or registry configuration. The command-line reference describes the accepted declarations.

The runtime lock excludes a second daemon using /run/loregd. Do not use that directory or a live hive for a development test. A daemon restart removes volatile registry data even if the operating system has not rebooted.

Readiness and logs #

If NOTIFY_SOCKET is set, loregd sends READY=1 after registration. The complete notification attempt has a one-second deadline. Failure is logged and serving continues, so a missing readiness message does not by itself prove that registration failed.

Progress goes to standard output and failures to standard error. peinit captures these streams during early boot. The daemon does not require eventd to report an early startup error.

Persistent and volatile data #

Persistent data lives in each named SQLite hive. A hive can have adjacent WAL and shared-memory files while open. Volatile data lives in fresh, per-hive databases under /run/loregd and is discarded on every restart.

Do not treat the main SQLite file alone as a live backup: committed data can remain in its WAL. loregd supports read-only RSI snapshots for higher-level backups, but creates no automatic startup backup. See backup and repair limits.

Stopping the daemon #

SIGTERM and SIGINT close the source device. loregd drains requests, releases transaction state, closes hive connections, and removes volatile stores. The kernel marks the served hives unavailable when their source disconnects. This can affect sign-in and other services that use the registry.

Diagnosing Registry Storage Failures

Peios / Using Peios / The Registry

Diagnose a failure from the daemon's captured error output and the failing operation. Process liveness alone does not establish registry health: loregd can remain registered while SQLite returns storage errors.

Startup failures #

The failure stage identifies the relevant checks:

StageCheck
Argument parsingEvery hive declaration contains a nonempty name and absolute path; folded names are unique.
Runtime directory/run/loregd is tmpfs-backed and available to the SYSTEM daemon; another instance does not hold its lock.
Database preparationParent paths are writable, SQLite can use WAL, and the database has supported schema version 1.
Device accessThe Peios registry device exists and the caller has SeTcbPrivilege.
NegotiationThe kernel supports RSI lifetime extension version 1.
RegistrationThe hive names and their global registration are accepted by the kernel.

Argument and startup failures exit with status 1. Readiness notification failure is a warning and does not terminate serving.

Busy and storage responses #

RSI_TXN_BUSY can indicate a competing write transaction, SQLite lock contention, a blocked checkpoint, or an expired request wait. A read-only snapshot does not own the write connection, but it can keep WAL pages that a truncate checkpoint needs to release.

RSI_STORAGE_ERROR includes database failures and invalid transaction state. An interrupted bound transaction requires abort; using its ID again does not silently start a replacement transaction. A request timeout does not prove that an already-admitted commit failed. See waiting and contention.

Recovery limits #

Startup performs SQLite WAL recovery and removes orphaned persistent keys. It does not restore a backup, rebuild case-folded columns, or repair an arbitrary corrupt database. The schema check is not a full integrity check: it does not validate every existing table definition or detect multiple version rows.

Preserve the affected files and diagnostics before attempting repair. Use a verified recovery procedure for the actual backup format. The daemon has no --inspector, --recover-from-backup, or --dangerously-clear-database switch.

Separate a source outage from a denied operation #

Record the exact operation, key, and error. reg status 3 means access denied; status 5 includes source and syscall failures. Do not replace a source database merely because a setting is missing or unreadable.

The registryd role names the selected source provider, not another daemon beside loregd. Its startup paths come from Peinit's boot policy. Inspect the installed arguments instead of treating a path from an example as a default. Do not start a second provider against the live databases to investigate.

On source disconnection, handles remain but operations needing source data fail. Re-registration produces watch overflow recovery: clients must reread the state they need. A timed-out mutation or commit can already have reached storage, so inspect live state before repeating it after recovery.

LCS owns access checks, routing, layers, and watches. That does not make a source untrusted: access checks use descriptors returned by the source, and structural validation cannot detect every well-formed false descriptor or entry. Protect the source process, launch configuration, and backing files as part of the trusted computing base.

Managing Features from the Command Line

Peios / Using Peios / Features

A package supplies a feature's definition and scripts. feat runs its explicit setup and records lifecycle state; installing the package alone does not enable the feature. Read the feature description before changing it, including when its effects take place.

Use feat list and feat info NAME to inspect definition availability and state. Install performs setup; enable activates installed setup; add performs both. Disable retains setup, while remove disables as needed and then runs teardown. Removing feature setup does not uninstall its supplying package.

Scripts run with the caller's authority. Permission to write the feature's registry state does not guarantee permission for every script operation. An enabled record also does not prove that a service started or a replacement boot artifact was built and activated.

Recover an interrupted step #

The state records a phase as begun before its script runs, then records the settled state on success. Failure can therefore leave partial external effects and an interrupted phase. It is not an automatic package-style rollback.

Read the script's error and inspect actual state before retrying. Scripts are required to tolerate restarting their phase, but that contract is not proof that an arbitrary third-party script is correct. After addressing the cause, retry the phase or use the supported opposite transition. Verify both recorded state and the resources the script manages; editing the numeric state alone does not finish the work.

Keep teardown available #

Remove setup before removing its package. Otherwise the registry can retain a feature whose definition and scripts are gone. Restore the supplying package, review the restored definition, then run teardown while it is available. Package undo and recovery do not reverse a feature's registry or runtime work.

Machine clients should use the documented JSON query or driven event stream, not parse human output. Driven changes provide scripts with empty standard input and do not become cancellation-safe merely because the client goes away. Inspect the eventual state after a disconnected request. feat(1) owns state values, command options, stream outcomes, and exit statuses.

Managing Features in Feature Manager

Peios / Using Peios / Features

Feature Manager controls feature definitions supplied by installed packages. A feature performs configuration beyond copying package files, such as setting up services. Installing its package and enabling its feature are different operations.

Before you start #

You need Feature Manager and permission to run the requested operation through feat. Read what the feature changes before applying it.

Choose the feature state #

  1. Open Feature Manager and inspect the feature's description and state.
  2. Choose Turn On to install and enable its setup, Install Only to set it up without enabling it, or Turn Off to disable it while retaining its installed setup.
  3. To remove the feature's setup, choose Remove and review the confirmation. Its package remains installed.
  4. Follow the card's progress and read the outcome or failed script output.

Check the result #

Confirm the final feature state and verify the affected service or setting. Interrupted identifies a script that did not finish; Try Again reruns it. Review the failure before retrying. Definition Missing means installed feature state survives after its definition package was removed.

An approved operation continues until completion when the window is asked to close. The window stays open with an explanation and closes afterward. Feature Manager delegates authority and state changes to feat; it does not grant privileges. See gxwi-feature-manager(1).

Missing definitions and limited access #

If a definition is missing, restore its package before asking feat to run the feature's cleanup. Removing a package does not undo the configuration its feature created. Keep the package available until the feature is removed.

The read-only view can show feature states without offering change buttons. Permission to change state does not supply every privilege a feature script needs. Read the failed script's output and investigate its access requirements before retrying; the app does not elevate it automatically.

Keeping the Time

Peios / Using Peios / Time

timed keeps the machine clock aligned with network time sources. Certificate validation, authentication, and the ordering of records depend on that clock. A time zone changes how programs display time; it does not correct the clock.

The service compares measurements from several sources, rejects conflicting measurements, and adjusts the clock's rate. Its reported accuracy estimates uncertainty from those measurements. It is not independent proof of the time.

Sources are not trusted individually #

Each server supplies an interval in which it estimates the true time lies. timed selects an overlapping set and rejects sources outside that agreement. A rejected source is called a falseticker.

Three sources with independent failure modes can let an agreeing majority exclude one incorrect source. One source has no independent comparison. Two disagreeing sources do not establish which one is correct. Several names can still share an operator, upstream clock, or network failure.

Authentication proves the identity of a source. It does not prove that the source reports the correct time.

Every source is authenticated #

By default, timed requires Network Time Security (NTS). A Transport Layer Security (TLS) exchange on port 4460 establishes keys for authenticated Network Time Protocol (NTP) messages.

timed checks the certificate against the configured server name, using roots supplied by trustd for server authentication. A DNS alias can change the address used for the connection; it cannot choose a different trusted certificate identity.

Roots are loaded at startup and refreshed after handshake failures. timed does not subscribe to trust-store changes. A distrust change therefore does not immediately invalidate an established NTS session or its cached cookies.

A blocked key-exchange port prevents new handshakes. Cached cookies can keep an existing source usable without another handshake. If no usable source remains, timed reports that the clock is unsynchronized. Allowing plain NTP is an explicit policy choice described in Configuring Time Sources.

The default sources #

When neither configured sources nor eligible network-provided sources supply a list, timed uses these operator hostnames:

  • time.cloudflare.com
  • nts.netnod.se
  • ptbtime1.ptb.de

These names identify three operators. They do not guarantee independent upstream clocks, reachability, or correct time. Replacing a fallback operator requires a configuration or software update; changing a Peios DNS alias does not change the authenticated identity.

Two circles, and how they are broken #

A machine with an incorrect hardware clock can reject valid certificates as not yet valid. timed raises a clock below its recorded build epoch to that lower bound. The epoch is stored in the source tree so that rebuilding the same source does not change the bound.

The floor is a bootstrap aid, not verified time. Certificates still have to be valid at the resulting clock reading. A machine can remain unable to complete a handshake after the floor is applied.

NTS cookies from successful exchanges are saved under /var/state/timed. They can let a restarted service obtain authenticated time before another TLS exchange. The startup hook protects this state for SYSTEM, Administrators, and timed's service identity. Cookie files contain secrets.

Steering, not jumping #

Ordinary correction changes the clock's rate gradually, called slewing. A clock step changes the wall-clock reading immediately and can affect file timestamps, log ordering, and software that uses wall-clock deadlines.

The automatic discipline permits an initial correction of any size when usable sources agree. After synchronization, a persistent large offset can cause a step after 15 minutes. An offset above 1000 seconds is refused rather than automatically accepted after synchronization.

Manual changes and the boot floor also step the clock. Turning automatic time back on restarts source acquisition and permits another initial correction. A reload is not a guarantee of uninterrupted wall-clock time.

Each step emits timed.clock.stepped. Its operation.name distinguishes automatic, manual, and boot-floor. See the installed evman timed.clock.stepped definition and the timed.clock.stepped evman entry for the recorded fields. Slewing does not emit a step event.

Learning the crystal #

timed estimates the machine clock's frequency error and saves it in /var/state/timed/drift. Reusing that estimate can shorten settling after a restart. Accuracy without network measurements depends on the clock's stability and the quality of the saved estimate.

What timed does not do #

timed is a client, not a network time server. It does not serve time to other machines or directly write the hardware clock. The kernel periodically updates the hardware clock when the system clock is marked synchronized.

The machine clock represents UTC. timed applies the selected local-zone data to /etc/localtime; individual programs can choose a different display zone. See Changing the Time Zone and Clock for the distinction and the operational checks.

Configuring Time Sources

Peios / Using Peios / Time

Configure time sources when the machine needs a particular operator or a network's time service. Check the effective sources after applying policy: a saved setting does not establish synchronization.

Before you start #

  • Install and start timed and its clock command.
  • Obtain write access to Machine\System\Time to change policy.
  • Obtain timed's control right to request a reload. Registry write access and the control right are separate permissions.
  • Choose sources with independent failure modes. Prefer authenticated sources and check that their certificates cover the configured names.

The regman entry for Machine\System\Time owns the complete configuration reference. clock(1) describes the command interface.

Naming your own servers #

  1. Inspect the existing state and policy:

    clock status
    clock sources
    reg get Machine/System/Time
    
  2. Set the source list. This example selects the shipped public operators explicitly, so network-provided time servers cannot replace the list:

    reg set Machine/System/Time Servers \
        multi:'time.cloudflare.com,nts.netnod.se,ptbtime1.ptb.de'
    
  3. Reload and check the result using the procedure below.

An entry names a host, optionally a port, followed by supported option words. prefer breaks ties between agreeing sources. It does not make a disagreeing source valid. A malformed entry is logged and omitted.

Precedence is first match, not merge #

timed selects the first nonempty list in this order:

  1. Successfully parsed Servers entries.
  2. Network-provided time servers, when UseFromDHCP permits them.
  3. The shipped fallback set.

The selected list replaces later choices. A domain policy can write Servers; the selector has no separate domain-discovery stage.

Authentication filtering happens after selection. An explicit list containing only plain-NTP sources produces no usable sources when AllowUnauthenticated is 0; it does not fall through to public servers. If every explicit entry is malformed, selection continues to the next list.

To remove an explicit override:

reg del Machine/System/Time Servers
clock reload

This restores the selection order. It does not necessarily select the public fallbacks because network-provided sources can take precedence.

Turning authentication off #

Plain Network Time Protocol (NTP) does not authenticate replies. Someone who can observe and alter the exchange can supply false time. Certificate validation and authentication systems can be affected by an incorrect clock.

For an explicitly configured plain-NTP source, both settings are required:

  • The entry includes unauthenticated or noauth.
  • AllowUnauthenticated is 1.

Use this policy only after accepting the trust placed in the server and its network path. Changing AllowUnauthenticated back to 0 excludes all plain sources, including those explicitly marked unauthenticated.

DHCP time servers #

Dynamic Host Configuration Protocol (DHCP) time servers are eligible when UseFromDHCP is 1 and no valid explicit list takes precedence. They are plain-NTP sources, so AllowUnauthenticated must also be 1.

Before allowing them, account for every network the machine can join. A network controls the time-server addresses it offers. This machine-wide setting follows the machine between networks.

netd publishes DHCP option 42 independently of whether its offered DNS configuration is accepted. See The Resolver Channel. timed applies its own time-source policy to that information.

Poll intervals #

MinPoll and MaxPoll are powers of two seconds. Their defaults are 6 and 10, giving intervals from 64 seconds through about 17 minutes. Values are clamped to the range documented in regman.

Shorter intervals increase server traffic. Longer intervals help estimate frequency error. Keep the defaults unless measurements justify a change.

Doing it from a domain #

Distribute time policy through registry policy using the same values. The policy must still produce sources that pass authentication and selection. A successful registry update does not establish correct time on each machine.

Reload and verify #

  1. Request a reload:

    clock reload
    
  2. Inspect the source list and clock state:

    clock sources
    clock status
    
  3. Check the source names, authentication, failure notes, selected source, accuracy estimate, and age of the last update. Repeat after further polls if the clock is still settling.

A failed configuration read retains the last complete configuration and returns a reload error. A registry notification triggers another read. Malformed individual server entries remain warnings and are omitted. A successful reload means the configuration was read, not that sources have answered or agreed.

When something is wrong #

A source marked falseticker disagrees with the selected set. Investigate that source and the agreement among the others; the label alone does not prove which clock is correct. An unreachable source includes a failure note when timed has one.

If no source is selected, compare Servers, UseFromDHCP, and AllowUnauthenticated with the reported list. Check whether Automatic is 0. A wrong local-zone display needs a zone correction, not necessarily a change of time source.

If reload is refused, check the separate control permission. A refused reload does not undo a registry write. If clock cannot contact timed, it has not established whether sources are usable.

Changing an active source list #

Reordering sources preserves each unchanged source's session and pending work. Removing a source discards results that arrive for that old source. Changing its port or authentication mode starts a new association. A source removed and later added again does not inherit an earlier pending result.

Changing the Time Zone and Clock

Peios / Using Peios / Time

Change the time zone when the clock is correct but local time is displayed incorrectly. Set the clock manually when no suitable time source is available. The machine clock represents UTC; the zone controls its local display.

Before you start #

  • Install timed, clock, and the time-zone database.
  • Obtain registry write access to Machine\System\Time to change settings.
  • Obtain timed's control right to reload or set the clock.
  • Before a manual change, account for its effect on timestamps and software that uses wall-clock deadlines.

clock(1) owns the command syntax. The regman entry for Machine\System\Time describes the settings and access checks.

Using the graphical settings {#in-system-settings} #

Open System Settings and select Time & Date to inspect the machine's zone, automatic-time policy, and sources. Changing machine time is separate from choosing a 12- or 24-hour desktop display; see Desktop Settings.

Verify the effective zone and clock state after a change. A saved setting does not prove that the zone data was applied or that sources agree.

In a terminal #

Change the time zone #

  1. Check the reported zone:

    clock status
    
  2. Select an installed zone, for example:

    reg set Machine/System/Time TimeZone sz:Europe/London
    clock reload
    
  3. Read clock status again and check timed's log for zone errors.

The name identifies data under /usr/share/zoneinfo. An invalid or missing zone is refused before copying, leaving the previous file in place. timed retries a refused name after configuration changes and every 10 minutes. Deleting TimeZone requests UTC.

On restart, timed identifies the zone only when its saved name and installed zone data match /etc/localtime. If identification fails, clock reports UTC (none chosen), even if the existing file contains another zone.

A copy failure after /etc/localtime is truncated can leave incomplete data. The retained status name is not a fresh verification of the file. Resolve copy or saved-name errors before interpreting or setting local time.

Set the clock manually #

  1. Confirm the zone and resolve any errors described above.

  2. Turn off automatic time and reload:

    reg set Machine/System/Time Automatic dword:0
    clock reload
    
  3. Run clock set with the intended local date and time. For example, the syntax for 14:05 on October 19, 2026 is:

    clock set 2026-10-19 14:05
    
  4. Check clock status. It should report manual operation and the intended zone. Manual time is not network synchronization.

Use @SECONDS instead of a local date to specify a UTC Unix timestamp. timed refuses manual setting while Automatic is 1.

Return to automatic time #

  1. Account for a possible clock step when sources agree. Reacquisition permits an initial correction of any size.

  2. Restore automatic operation:

    reg set Machine/System/Time Automatic dword:1
    clock reload
    
  3. Check clock sources and clock status as measurements arrive. Confirm authentication, agreement, accuracy, and fresh updates.

Coordinating changes with timed {#why-not-just-set-the-clock} #

Changing the clock outside timed leaves the service measuring an unexpected error. It can correct the change or refuse a sufficiently large offset. Using clock set coordinates the change with the service and emits timed.clock.stepped with operation manual and the requesting identity. Read the installed definition with evman timed.clock.stepped.

Individual programs can display UTC with date -u or use a TZ environment setting where supported. Those choices do not change the machine clock.

File validation #

Zone files and metadata must be regular files of at most 16 MiB. Aliases to regular files are supported. Timed checks the opened zone file and copies that same data, so validation and copying cannot select different files.

Timed updates the pre-created /etc/localtime file in place. Readers can observe an empty or partial copy, and a write failure can leave a partial copy. Its directory permissions do not allow an atomic rename by the service.

Understanding Clock Status

Peios / Using Peios / Time

clock reports what timed knows about the machine's time. Its status and source views help distinguish a display-zone problem from a failure to obtain usable time. clock(1) owns the command syntax and exit-status reference.

Status #

Read clock status starting with state, following, accuracy, and the age of the last update. The state labels retain their wire spelling:

StateMeaning
synchronisedThe clock is being kept from usable measurements.
settlingThe frequency estimate is still converging.
spikeA large offset is being checked before changing the clock.
unsynchronisedThe clock has no accepted synchronization.

Manual operation adds Automatic is 0: the clock is set by hand. That is not evidence of network synchronization.

Accuracy combines uncertainty reported by the selected measurements. It helps assess clock quality, but does not independently prove the time. Frequency estimates the hardware clock's error in parts per million. The saved drift estimate lets later starts reuse what timed has learned.

Stepped records cumulative steps since startup. Unexpected changes call for inspection of timed.clock.stepped events. Manual changes, automatic corrections, and the boot floor have distinct operation names.

Floor is the recorded build epoch, used as a lower bound. Remaining near the floor does not establish correct time or certificate validity.

Time zone is timed's recorded zone for /etc/localtime. An unidentified file is displayed as UTC (none chosen). A failed copy can also leave the reported name without valid corresponding data. Resolve errors using the zone procedure.

Sources #

clock sources shows each source's state, authentication, reach history, measurements, and age. The leading markers summarize selection:

MarkStateMeaning
*system-peerSelected source for the system's reference figures.
+candidateAgrees and contributes to the combined measurement.
-outlierAgrees but is excluded because of measurement quality.
xfalsetickerDisagrees with the selected set.
?unusableHas answered but cannot supply usable time.
blankunreachableHas no usable reply history.

Auth distinguishes authenticated NTS from plain time. Reach is an octal mask of the last eight polls, newest in the lowest bit. 377 means all eight answered; 376 means the latest poll failed; 0 means none answered. Stale measurements stop contributing when reach is lost.

Last is the age of the last answer. Read any note below a source before changing policy: a connection failure and a certificate failure need different investigation.

Setting the clock #

clock set requests a coordinated manual step. It requires manual mode and timed's control right. The manual-time procedure covers prerequisites, local-zone interpretation, and checks afterward.

Exit statuses #

An unsuccessful query does not establish the state of the clock. In particular, a failed connection differs from a successful source query finding no sources. Scripts should use the exit statuses documented in clock(1) instead of inferring success from partial output.

When reload is refused #

Reloading and setting time require timed's control right. Querying status and sources is public under the default policy. The control descriptor is Machine\System\Time ControlSecurity; SYSTEM and Administrators receive control access by default.

Registry write access is a separate check. A successful policy write does not prove that the caller can reload, and a refused reload does not undo the write. A configuration-read failure also makes reload fail while timed retains its last complete configuration.

Configuring Profiles

Peios / Using Peios / Network Configuration

Network configuration is two kinds of key under Machine\System\Network. A profile, a subkey of Profiles, says how an interface stands on a network: what to take from the network's offer and what to dictate. A rule, a subkey of Rules\Interface, says which interfaces stand in which profile. netd watches the subtree, so a change takes effect within a moment of the write — no restart, no reload command.

Follow this order: inspect the active interface, prepare the profile, select it with a rule, then read back the accepted state. For desktop changes, use Network Manager, whose profile editor shows inherited values and the interfaces a change affects.

Read the registry value reference on the machine with regman 'Machine\System\Network'.

Before you change anything #

  • You need write access to the particular registry keys. Reading status does not grant permission to change configuration; protected Status keys are netd's output, not settings to edit.
  • Record the current rule, profile, and values so you can restore them. Keep local console access or another recovery path if this network carries your remote session.
  • Profile and rule writes take effect live. Changing a profile's resolved values restarts its interfaces' clients, even for a DNS-only profile edit. No reboot or daemon reload is required.
  • Use a derived profile for one interface. Editing default affects every interface using it and descendants that inherit the edited value.
  • The commands below are examples. Replace addresses, names, ids, and bus paths with your own. The vpn, office, laptop, untrusted, and home profile examples assume those profiles already exist.

Warning

Direct reg writes do not use Network Manager's Keep this change? confirmation. A policy edit can disconnect the machine. Have console access or another recovery path before changing the interface used for remote access.

See what you have #

net status
net rules
net profiles

Keep this output for comparison after the change. net status shows each interface with its verdict: the rule that spoke and the profile it stands in. An image's baseline is a profile default that takes the network's address, way out and name servers, and a rule wired that puts every wired interface in it at priority 10.

A static address #

Create the profile before a rule names it. This example derives default/db1 from default, so values not listed here remain inherited, including Dns.Offered and Address.LinkLocal. Lists replace inherited lists; they do not append. An absent value inherits, while a present empty value means none.

Confirm that 10.0.0.5/24 is appropriate and available on your network and that 10.0.0.1 is its gateway before adapting these example writes:

reg new Machine/System/Network/Profiles/default/db1
reg set Machine/System/Network/Profiles/default/db1 Address.Offered dword:0
reg set Machine/System/Network/Profiles/default/db1 Address.Static multi:10.0.0.5/24
reg set Machine/System/Network/Profiles/default/db1 Route.Offered dword:0
reg set Machine/System/Network/Profiles/default/db1 Route.Gateway 10.0.0.1

Then a rule naming the interface by its bus path (from net status, stable across boots), as an exception under the baseline's wired rule so it is judged only for wired interfaces:

reg new Machine/System/Network/Rules/Interface/wired/db1
reg set Machine/System/Network/Rules/Interface/wired/db1 Interface.Path.Equal pci-0000:00:03.0
reg set Machine/System/Network/Rules/Interface/wired/db1 Actions 'multi:JOIN(default/db1)'

The exception is more specific than wired, so it selects default/db1 for that interface and stops offered address acquisition. Check for JOIN(default/db1) by wired/db1 and the intended address and gateway in net status; readiness routed appears once both a usable address and the default route are in place.

Inherited Dns.Offered is a setting, not evidence that a server is available after address acquisition stops. Check resolv status. To pin DNS as well, set Dns.Offered = 0 and Dns.Servers on this derived profile. The inherited link-local setting does not add a fallback beside a static address. See desired state.

Verify the accepted settings #

net rules
net profiles
net status
resolv status
  1. Confirm the rule names the intended profile and matches the intended interface. net profiles lists each profile's own values, not a flattened result; account for inherited values.
  2. Check that net status has no policy REFUSED line. Read the active verdict, rule and profile, then the address, gateway, lease and warnings.
  3. Check the servers and domains in resolv status, and test a relevant name with resolv query <name>.
  4. Test the service you actually need. Readiness routed proves a default route exists, not that a remote service or the Internet answers.

If you also changed firewall rules or a network's Name or Trust, an administrator should run net policy wait and check net policy. That verifies the kernel's packet policy; it does not substitute for checking netd's accepted profile in net status.

If the result is wrong, restore the values you recorded and repeat the checks. net reconcile requests another pass; it does not undo a write. net renew <interface> asks to renew an existing DHCP lease without releasing it first. Both need NETWORK_CONTROL, granted to SYSTEM, and Administrators by default.

Facts a rule can name #

Every <Fact>.<Operator> value present must hold. Comparison is exact; Equal takes a list for any of.

FactMatchesExample
Interfacethe kernel's interface nameenp0s3
Interface.Kindwired, wireless, loopback, otherwired
Interface.Idthe stable id from net status3f2a1b8e-…
Interface.Macthe hardware address52:54:00:12:34:56
Interface.Paththe bus pathpci-0000:00:03.0
Interface.Driverthe kernel drivervirtio_net
Network.Namethe Name you gave the network's recordpalfrey-home
Network.Trustthe Trust you gave itcorporate

Prefer Interface.Path or Interface.Id for a specific card and Interface.Kind or Interface.Driver for a class. Interface (the name) is the least stable: the kernel might call the same card something else after a hardware change. A fact the interface lacks — a tunnel has no Path — makes the condition false, never an error.

Taking the offer, with adjustments #

default believes the network about the address, the way out and the name servers. To keep the address but pin DNS, override two values in a derived profile and point a rule at it — or, if the whole machine should behave so, edit default itself:

reg set Machine/System/Network/Profiles/default Dns.Offered dword:0
reg set Machine/System/Network/Profiles/default Dns.Servers multi:1.1.1.1,9.9.9.9

Three more Dns values decide which names an interface's servers are asked for, which matters the moment a second interface appears — typically a VPN:

reg set Machine/System/Network/Profiles/vpn Dns.Domains multi:corp.example
reg set Machine/System/Network/Profiles/vpn Dns.Default dword:1
reg set Machine/System/Network/Profiles/vpn Dns.Exclusive dword:1

Dns.Domains sends names under corp.example to this interface's servers. Dns.Default sends every other name there too (unset, an interface claims that only when it carries the default route). Dns.Exclusive takes all queries only while the interface is at least addressed and supplies a DNS server. Without those conditions it does not prevent another interface from being chosen. Verify the VPN's addresses and server lines before relying on it to keep names off another network. resolvd owns resolver selection; resolvd(8) describes that service.

To hold an offered address across a server outage:

reg set Machine/System/Network/Profiles/default Address.OnExpiry Keep

Keep trades the risk of an address conflict for continuity; the default Drop is the safe choice.

IPv6 #

Address.Offered covers both families: on a network with router advertisements the interface gets a stable-privacy address per advertised prefix, and with Route.Offered and Dns.Offered the advertised default route and DNS from RDNSS or stateless DHCPv6. Three values change that:

reg set Machine/System/Network/Profiles/office Address.Families multi:ipv4
reg set Machine/System/Network/Profiles/laptop Address.Temporary dword:1
reg set Machine/System/Network/Profiles/office Route.Gateway multi:10.0.0.1,fe80::1

Address.Families = ipv4 stops router discovery on interfaces in the profile and drops IPv6 entries from Address.Static. Address.Temporary adds daily-rotating temporary addresses beside the stable one, for machines whose traffic should not correlate over days; the stable address remains for inbound. An IPv6 entry in Route.Gateway — usually a link-local address — pins the default router instead of believing advertisements.

The stable address survives reboots and reinstalls that keep /var/state/netd ; it is not derived directly from the MAC, and a different network sees an unrelated address. The IPv6 address chapter documents derivation, lifetimes and rotation.

Prefer a cable over WiFi #

When both interfaces have default routes, the metric decides which is used. Wired defaults to 100 and wireless to 600, so no configuration is needed. To invert it, set Route.Metric on the profiles. This describes route preference once links exist; Wi-Fi association is not implemented by netd, wireless is not in the baseline, and Network Manager shows wireless as Not managed.

Name a network, and behave differently on it #

Once an interface has stood on a network, net status shows the record's id. Give it a name and your word on it:

reg set Machine/System/Network/Networks/<id> Name palfrey-home
reg set Machine/System/Network/Networks/<id> Trust home

Changing either label can change both the selected profile and firewall access. Check the active interface and packet policy afterward.

The following illustrates choosing a profile by network. It is not a Wi-Fi setup procedure: a supplicant must supply the link, and wireless network-name identification is unfinished. Create the untrusted and home profiles before a rule names them:

reg new Machine/System/Network/Rules/Interface/radio
reg set Machine/System/Network/Rules/Interface/radio Interface.Kind.Equal wireless
reg set Machine/System/Network/Rules/Interface/radio Actions 'multi:JOIN(untrusted)'
reg new Machine/System/Network/Rules/Interface/radio/home
reg set Machine/System/Network/Rules/Interface/radio/home Network.Name.Equal palfrey-home
reg set Machine/System/Network/Rules/Interface/radio/home Actions 'multi:JOIN(home)'

Until a network has been identified on the link, the Network.* facts are absent, so the radio stands in untrusted first and moves to home once the network is known. Trust is your label, not verified evidence of network identity: a rule that conditions on it is stating that you accept the identification. The same word reaches the firewall: a Flow rule with Network.Trust.Equal = home sees the network the radio is on, so what you open at home stays shut at the cafe. See the network context in the Peios Network Policy specification for the shared firewall contract.

Hand an interface to something else #

An IGNORE verdict leaves a matched interface alone: no new addresses, routes, link changes, or DHCP. If it was previously joined, existing addresses and routes remain; IGNORE is not a cleanup action:

reg new Machine/System/Network/Rules/Interface/leave-alone
reg set Machine/System/Network/Rules/Interface/leave-alone Interface.Equal tap0
reg set Machine/System/Network/Rules/Interface/leave-alone Actions multi:IGNORE

Take an interface down #

A DOWN verdict keeps a matched interface administratively down. DOWN wins equal-priority ties, but a higher-priority rule still wins. Check existing priorities before using the example priority 100:

reg new Machine/System/Network/Rules/Interface/dead-card
reg set Machine/System/Network/Rules/Interface/dead-card Interface.Id.Equal <id>
reg set Machine/System/Network/Rules/Interface/dead-card Priority dword:100
reg set Machine/System/Network/Rules/Interface/dead-card Actions multi:DOWN

The interface id is in net status. Delete the rule, or set Enabled = 0 on it, to let the remaining rules decide again. Verify that they select the intended profile; removing DOWN alone does not guarantee a JOIN.

Ask for the same address #

The address a network last leased is on its record, and netd asks for it first. Write it yourself for a soft reservation — a request the server might refuse, unlike a static address:

reg set Machine/System/Network/Networks/<id> RequestedAddress 10.0.2.50

Set the hostname #

reg set Machine/System/Network Hostname workshop

netd applies it on the next pass. A profile with Hostname.Offered on adopts a network-supplied name when this value is unset; Hostname.Announce tells DHCP servers the name so their DNS can register it. Both are off in a bare profile.

Each change netd makes to the machine's name is recorded in the event log as netd.hostname.changed, with the name before and after (config.text-previous and config.text). The netd manual's hostname chapter says exactly when.

netd validates the name as one network label: letters, digits, and hyphens, at most 63 of them, not beginning or ending with a hyphen, and not localhost. System Settings holds it to that as it is typed: in its About section, Machine Name says what is wrong with a name before it can be applied, and shows the name the machine has now if netd hasn't applied the new one yet; Apply appears once the name has been changed. The About section also shows what the machine is and runs: the system and its edition, the kernel, how long it has been up, the hardware, and the disks.

When netd refuses #

An unknown fact, a JOIN naming a missing profile, or an unknown profile value refuses the whole new interface generation. netd keeps the last good one and net status reports policy REFUSED with the reason. Fix the named entry, then verify the next write was accepted; the registry listing alone does not tell you what is active.

Two equal-priority rules selecting different profiles also refuse a runtime reload when the conflict affects an existing interface. At startup, or for an interface that appears later, the tied interface is instead ignored and its warning names both rules. Make one rule unambiguously win. The generation and interface judgment chapters describe that distinction.

A JOIN naming an existing but disabled profile abstains; its parent, another rule, or the backstop answers. Disabling a profile does not exempt malformed values in it from validation.

Where to go next #

  • The net command — read back what netd did.
  • Networking — the model behind these keys.
  • regman 'Machine\System\Network' — registry values and their meanings.
  • The interface layer as netd runs it, in the netd technical reference manual — how netd reads these keys, builds a generation from them and judges each interface.

The Net Command

Peios / Using Peios / Network Configuration

Use net status first. It shows what netd accepted and what is present on each interface. Use net rules and net profiles to compare that state with the registry configuration. On the desktop, the same starting point is Network Manager's Overview.

net status
net rules
net profiles

net does not write profile or rule configuration. Follow Configuring profiles to change it, then return here to verify the result.

After a change #

  • Profile or interface rule: check net status for the intended verdict, rule and profile, no policy REFUSED line, and the expected addresses and gateway. net profiles shows each profile's own values, so inherited settings still matter.
  • DNS: check resolv status and a relevant resolv query <name>.
  • Firewall rule or network label: as an administrator, run net policy wait, then net policy. A returned registry write is not yet proof that the kernel accepted it.
  • Connectivity: test the required service. routed means there is a usable address and a default route, not a successful Internet probe.

The interface and packet policy are accepted independently. A successful net policy wait does not prove that netd accepted a profile; a good net status does not prove that the firewall accepted a rule.

Reading net status #

hostname   workshop
readiness  routed

enp0s3  [3f2a1b8e-…]
  verdict    JOIN(default) by wired
  state      up, carrier
  readiness  routed
  hardware   52:54:00:12:34:56 pci-0000:00:03.0 virtio_net
  network    palfrey-home [9c0d4e21-…] trust home
  address    10.0.2.15/24
  gateway    10.0.2.2
  dns        10.0.2.3
  lease      bound from 10.0.2.2, 86395s left

verdict is what the interface layer said and who said it: the verdict, the profile (for JOIN), and the rule path that spoke — backstop when no rule did. readiness is absent (down or no carrier), link, addressed or routed, shown for joined interfaces; the machine's is the highest among them. network is the record under Machine\System\Network\Networks identified on the link, with the Name and Trust you gave it.

The bracketed value after the name is the interface id — the inventory key under Machine\System\Network\Interfaces.

Read the interface block, not only the machine's readiness: another interface can make the machine routed while this one is unusable. An IPv4 link-local address counts as addressed; IPv6 link-local alone does not. Only joined interfaces contribute to machine readiness.

A warning line can mean DHCP discovery went unanswered or two rules tied and this interface is ignored. policy REFUSED: means the newest interface generation was rejected and the last good one stands. Correct the named rule or profile and read status again. A listed registry write is not proof it took effect.

Commands #

CommandDoes
net statusHostname, the machine's readiness, whether the newest generation was refused, and every interface: verdict with the rule and profile behind it, link state, readiness, hardware identity, the network identified on it, addresses, gateway, DNS, lease, warnings.
net wait <level> [seconds]Block until the machine reaches link, addressed or routed, or the timeout (default 60) passes. For scripts that need the network.
net renew <interface>Renew the DHCP lease now. Accepts a kernel name or an interface id.
net reconcileRe-run the reconciler immediately rather than waiting for an event.
net policyThe kernel's side of the packet policy: whether the filtering engine (NTFE) is enforcing, its generation, whether every change written so far is in force, whether the last re-read was refused, and how many interfaces have a network context.
net policy wait [seconds]Block until every change made to Machine\System\Network before the command started is in force in the kernel, or the timeout (default 10) passes. Fails if the kernel refused the new generation. For scripts that write a rule and then rely on it.
net rulesThe interface layer, one rule per line: path, priority, conditions, actions.
net profilesThe profile tree, one profile per line with the values it sets itself.

Choose renew or reconcile carefully #

net renew <interface> asks a DHCPv4 client holding a lease to renew it without releasing its current address first. A client with no lease is left as it is; a successful request alone does not prove a new lease arrived. Check the lease afterward. The argument might be a kernel name or the stable interface id shown by net status.

net reconcile asks netd to apply the configured desired state now. It does not reload a different configuration, undo a write, or make an invalid gateway reachable. Neither operation requires a reboot.

Use these commands when a restart is unnecessary. On restart, netd asks to reuse its remembered IPv4 address and keeps that address and applicable routes while revalidation is pending. A rejection or timeout discards that provisional state. It must reacquire offered DNS and IPv6 information. See startup.

Each control request has a 5-second total deadline, including connection, request transmission, and response reading. A timeout does not prove that a renew or reconcile request had no effect. Check status before retrying.

Required access #

status, wait, renew, and reconcile reach netd through /run/netd/control.sock. The control object is a security descriptor: Machine\System\Network\ControlSecurity, or a compiled default when that is unset. status and wait need NETWORK_QUERY, which the default grants to everyone. renew and reconcile need NETWORK_CONTROL, which the default grants to SYSTEM and Administrators. rules and profiles read the registry directly and need only read access to it. policy and policy wait ask the kernel through /dev/peios-ntfe, which ordinary users might lack access to. A denied request reports access denied.

Exit status #

CodeMeaning
0Done; for wait, the level was reached; for policy wait, the changes are in force.
1netd refused or could not be reached; for wait, the timeout passed; for policy wait, the timeout passed or the kernel refused the generation.
2Usage error.

See also #

  • Networking
  • Configuring profiles
  • regman 'Machine\System\Network' on the machine, for every key netd reads and writes.
  • netd's control socket, in the netd technical reference manual: the requests behind every net command, and their replies.

Network Manager

Peios / Using Peios / Network Configuration

Network Manager combines interface configuration, name resolution, and firewall policy in one desktop application. It reads netd, resolvd, kernel state, and registry settings as your account. Each operation remains subject to the backend's access checks.

Finding the right view #

The application groups its views by purpose:

GroupViews and purpose
NetworkOverview, known networks, profiles, profile rules, and DNS
FirewallExposure, rule editing, connection tests, and activity
SystemPort reservations, audit level, and advanced daemon settings

Overview maps an interface to its selected profile and network, with addresses, routes, traffic, and lease information. A Connected summary means there is a route; it does not prove that a particular service or the Internet is reachable. Wireless interfaces are shown as unmanaged by this implementation.

Networks records identities and trust levels. Profiles define configuration and Profile rules choose where it applies. DNS queries resolvd and manages fallback servers, search domains, static names, and its cache. Port-reservation permission to bind a socket is separate from firewall permission for traffic to reach it.

Example firewall data #

The listener, connection, counter, and recent-audit displays under the firewall interface use constructed examples. Affected panels say Example data, and the status line says Example. They use real rules and some real machine context, but are not a live inventory of traffic or listening services.

The saved rules and network settings are real. A connection test predicts a policy result; verify a policy change with the actual connection or service you intended to affect. Do not use an example activity panel as evidence that a connection happened or was blocked.

Permissions and refresh #

Settings are checked for write access by registry key. Runtime Renew lease and Reapply use netd's control right. Read-only panels explain why a change is unavailable. Exposure and Activity also restrict access.

Live machine data refreshes every two seconds; registry changes trigger settings refreshes. A daemon refusal is shown with the previous accepted configuration or generation still in force. See Changing Network Settings before making a change through a remote desktop.

Changing Network Settings in Network Manager

Peios / Using Peios / Network Configuration

Use Network Manager to change the intended profile, selection rule, or firewall rule, then verify its live effect. Some changes can disconnect the desktop through which you are working.

Before you start #

You need permission to change the relevant settings. Record their previous values and keep another recovery path for changes that can affect remote access. Not every change has automatic undo.

Apply a controlled change #

  1. Open Network Manager and inspect the affected interface in Overview. Record the profile, rule, network, and addresses it uses.
  2. Open the relevant profile, profile rule, or firewall rule. Inspect the preview and any affected interfaces or desktop connections.
  3. Save the intended change. If the application warns that it would disconnect an active desktop, read the affected connections before deciding whether to continue.
  4. When Keep this change? appears, test the intended connection before selecting Keep. Select Undo to revert, or allow the 30-second server-side timer to expire.

Check the result #

Return to Overview and check the actual interface state. For a name change, perform the intended lookup; for a firewall change, test the actual connection. Read the accepted policy generation and any refusal. Example firewall activity is not live confirmation.

Which changes have undo #

The keep timer covers firewall and profile-rule changes, exposure changes, and relevant changes to profiles or known networks carrying desktop connections. A change accepted after a disconnect warning also receives the timer. Starting another guarded change keeps the preceding one.

DNS settings, static names, port reservations, audit levels, and new profiles can apply immediately without that bar. Restore their recorded previous values explicitly if needed. The server runs the guarded timer, so losing the browser connection does not prevent its expiry.

See gxwi-network-manager(1), net(1), and resolv(1) for command interfaces and backend behavior.

Checking Connectivity

Peios / Using Peios / Network Configuration

Network readiness, name resolution, certificate trust, and permission to connect are separate checks. Preserve the failed command and its diagnostic before changing configuration.

Follow the symptom #

  1. Run net status to identify the affected interface, its carrier, rule, profile, addresses, and route. Run resolv status for the DNS servers actually selected.
  2. Choose the next check from the table. Use the intended service and host, rather than treating any successful probe as proof of full connectivity.
  3. If a change is necessary, follow the owning component's procedure with a local recovery path. Then repeat the original failed operation.
ObservationNext check
No carrier or readiness absentLink, cable, and the interface verdict.
IGNORE, DOWN, or no profilenet rules and the profile-selection policy.
Carrier but no offered addressProfile families and Address.Offered, server reachability, and DHCP policy.
Only a 169.254 addressLink-local fallback; it does not establish a routed lease.
Address but no default routeRoute.Offered or the configured gateway and route-addition diagnostics.
IP works but a name failsresolv query NAME, server selection, and not-found versus unavailable.
One service failsIts listener, bind authority, packet policy, and application response.
Stored changes do not applynetd's acceptance and the kernel's packet-policy acceptance separately.
TLS verification failsExpected peer identity, selected trust anchors, and the reported certificate.

The profile workflow and resolver guide explain their own checks. For firewall changes, use Changing Network Policy.

Readiness and ownership #

Readiness progresses through absent, link, addressed, and routed. An address can be link-local; a default route does not prove Internet, DNS, or application availability. net wait accepts at least its requested level, while Peinit's declared readiness dependency matches a published level. Check the readiness reference when choosing a service dependency.

netd owns addresses on joined interfaces and its tagged routes. Manual address changes can disappear during reconciliation. It leaves the kernel's IPv6 link-local address and other programs' route tags alone. IGNORE is not a cleanup request. Restarting netd can interrupt offered configuration while DHCP and router discovery run again; it is not a harmless reload.

Network Name and Trust labels are operator policy, not authenticated proof of the network's identity. Changing them can affect both interface selection and the firewall. Wireless association requires a supplicant; netd's profiles do not implement association, and the baseline leaves wireless unmanaged.

Compare daemon and network evidence #

Inspect captured service output when configuration does not explain a failure:

evctl 'LOGS FROM netd SINCE 1h ago TAKE 40'
evctl 'LOGS FROM resolvd SINCE 1h ago TAKE 40'

Use ss -lnt on the receiving machine to inspect TCP listeners. A targeted nc -vz HOST PORT checks a TCP connection, not application correctness. dig @127.0.0.53 NAME A queries the local DNS stub directly; it does not change resolver policy. Choose hosts and traffic you are authorized to test.

An absent echo reply does not establish that a host is down. Ordinary echo uses datagram sockets, while packet capture and some probe modes require raw-socket authority. Neither installing a diagnostic utility nor selecting its privileged mode grants native privileges or a firewall exception.

The network utility compatibility reference describes the Peios ports' file, authority, and supported-mode differences. Tool availability depends on the installed packages, not this guide.

Diagnosing Name Resolution

Peios / Using Peios / Network Configuration

Use resolv to identify whether a name is missing, resolution is unavailable, or an unexpected interface is being used. Interface DNS policy belongs to netd. resolvd applies that policy and machine-wide fallback and static-name settings.

Before you start #

  • Install resolvd and the resolv operator command.
  • Identify the failing name and the network it should use.
  • Obtain registry write access before changing policy. Queries use the resolver's separate query permission, granted publicly by default.

resolv(1) owns command syntax and exit statuses. The regman entry for Machine\System\Network\Dns owns machine-wide settings. Do not edit /etc/hosts, /etc/resolv.conf, or nsswitch.conf to change this policy.

Check a name first #

  1. Read the effective state:

    resolv status
    
  2. Query the failing name. For example:

    resolv query example.org
    resolv lookup example.org
    
  3. Compare an answer obtained without consulting the cache:

    resolv query example.org --no-cache
    

The final command bypasses cache lookup but can store the resulting answer. Read the reported outcome, source, server, and interface. If connecting to an address also fails, investigate connectivity.

Where the servers come from #

netd sends resolvd each interface's servers, domains, and addresses as a scope. Compare the scopes in resolv status with net status and the intended interface profile.

Use Configuring Profiles to change offered or explicit interface DNS settings. A profile change can restart address clients; follow that guide's recovery checks.

Machine-wide fallback servers, extra search domains, and static names live under Machine\System\Network\Dns. They apply after a successful complete configuration read. A read failure retains the previous configuration and is logged. A lost registry watch can prevent later changes from being observed.

Verify which interface gets a name #

A query selects one scope. The order is exclusive scope, longest matching search domain, matching reverse subnet, default route, then lowest metric among up scopes with servers. Fallback servers are considered only when no earlier step chooses a scope.

An exclusive scope must be at addressed or better. It still wins without servers; upstream work then becomes unavailable rather than using another interface. At link alone, the exclusive rule does not apply. Verify the interface state as well as its flags when diagnosing VPN name routing.

A bare name such as printer requires a search domain. All up scopes can contribute domains, including scopes without servers. A qualifying exclusive scope supplies only its own domains. With no applicable domain, a bare name is answered locally as not found and is never sent upstream unchanged.

See the routing and search expansion chapters for tie-breaking and failure behavior.

Static names #

With registry write access, add a static name when this machine should answer it without DNS. Replace the sample address with the intended host:

reg new Machine/System/Network/Dns/Hosts
reg set Machine/System/Network/Dns/Hosts printer sz:10.0.2.9
resolv query printer
resolv reverse 10.0.2.9

Verify both directions. Static names apply without a cache flush after the configuration is read. Synthetic localhost names take precedence over static names. The synthetic-name chapter describes hostname, reverse, and .local handling.

The resolv command #

resolv query reports individual records and where the answer came from. resolv lookup returns addresses and a canonical name. resolv reverse queries names for an address. resolv status reports scopes and counters.

resolv flush clears the shared cache and requires the resolver control right. Registry editing has separate permissions. Every command exchange has a ten-second deadline; a failed exchange is not evidence that a name is absent. See resolv(1) for scripting contracts.

Not found versus unavailable #

ObservationNext check
notfound from DNS or cacheCheck spelling and compare a query without cache lookup.
notfound locally for a bare nameCheck applicable search domains.
unavailableCheck the selected scope, its servers, and reachability.
netd disconnected, no scopesCheck netd; only local answers and configured fallbacks are available.
netd disconnected, scopes listedThese are the last snapshot, not a fresh view of the links.
A demoted serverCheck its failures; healthy servers are tried before demoted ones.
A stale answerCheck static overrides, then compare a query without cache lookup.
Access deniedInspect the native control permission separately from stub reachability.

Read the service log when startup or updates fail:

evctl 'LOGS FROM resolvd SINCE 1h ago TAKE 40'

A restart replaces resolvd's stale socket and clears transient state. Do not remove its runtime directory as a routine diagnostic step. Inspect permissions and the exact startup error using the failure guide.

Three doors #

Programs reach the same resolver engine through the native socket, the local DNS stub at 127.0.0.53, or glibc's Name Service Switch (NSS) module. Native applications can use libresolvd.so; other DNS clients use the constant resolver configuration pointing at the stub.

A direct query to another server tests that server and bypasses normal scope selection. It does not establish how Peios applications resolve the name.

Implementation boundaries {#what-is-not-there-yet} #

resolvd does not implement DNSSEC validation, DNS over TLS, multicast DNS, or per-program resolution policy. Answers report unvalidated. Allowed callers use the same policy; native query access controls permission to ask.

Going deeper #

  • PSPU, Name Resolution Interface, defines the protocol contract. defines request and outcome contracts.
  • resolvd TRM explains the implementation and its limits.
  • netd's resolver channel describes the live network information sent to resolvd.

Changing Network Policy

Peios / Using Peios / Network Policy

Peios Network Policy uses registry rule trees under Machine\System\Network. netd applies Interface rules; the kernel's NTFE applies RawPacket, Packet, and Flow rules. The two consumers validate their own layers independently.

Inspect, change, and verify #

  1. Establish the intended connection and listener. An allow rule does not start a listener or grant its port reservation.
  2. Record net status and, with kernel-device access, net policy. Distinguish a stored rule from the accepted generation. A refused update keeps the previous accepted configuration active.
  3. Preview the smallest change. Network Manager offers configuration tools, but its labeled example activity data is not evidence of a real flow.
  4. Preserve old values and local recovery access before changing a remote connection's path. Rule and network-label changes can affect established connections on their next packet.
  5. Write the intended policy, then run net policy wait and net policy. Check net status separately for interface/profile acceptance and test the actual service connection.

Read Changing Network Settings for exactly which desktop changes have a keep/undo countdown. Direct registry edits and the development PNP viewer do not provide that safeguard. A timeout or refusal from the acceptance check needs investigation.

Choose the evaluation layer #

Use Flow for most connection and service policy. Packet evaluates per-packet conditions, including traffic without a tracked flow. RawPacket works at wire-side seats; its available facts differ. An allow in one layer does not override a refusal in another. Interface selects a profile, leaves an interface alone, or keeps it down.

Rules have conditions, actions, and inherited priority. A matching child is an exception within its parent tree; separate trees still compete. Highest priority wins, then the stricter verdict. An effect such as counting does not grant access. The shared authoring reference defines the vocabulary; the kernel's evaluation reference defines execution.

Check a changing flow #

A flow's cached verdict is its sentence. Its direction follows the originator, including replies. Policy or network-context changes cause reevaluation on the next packet. Consulted Time.* conditions can also expire a sentence; Start.* describes connection start and stays fixed. Loopback has two local endpoints and must pass both judgments.

Use native Local.* facts for a local program or service. They derive from socket identity stamps, not a claimed process name or a projected Unix UID. Missing identity can mean a kernel endpoint, shared receivers, or no listener. The identity reference explains when each fact exists.

DROP is silent. REJECT(Refused) resembles an unavailable listener; REJECT(Prohibited) reports policy refusal. Some packets cannot receive a refusal, so the engine counts a degraded drop. A newly rejected established TCP flow can be torn down at both ends. Kernel-generated refusal packets have a specific bypass; ordinary traffic does not inherit it.

Interpret observations #

Generation zero is permissive before policy ingestion. An accepted empty packet forest has a drop backstop; an unmatched interface is ignored. Record which state the machine is in before interpreting a missing rule.

A cached sentence produces no fresh evaluation event for each packet. Missing events do not prove delivery, and captured frames can precede a later drop. Check surfaced capture loss, verdict overwrite, and refusal counters alongside flow attribution.

Network Rule Authoring

Peios / Using Peios / Network Policy

Rule paths live beneath Machine\System\Network\Rules. Interface belongs to netd; RawPacket, Packet, and Flow belong to NTFE. Each executor can accept or refuse its own generation independently. A successful registry write is not an acknowledgment from either executor.

A rule's name identifies it in diagnostics and cannot contain path separators. Its conditions are ANDed. A matching child specializes its parent's matched region. Priority inherits from the parent, or defaults to zero at a root. An empty action list abstains; Enabled = 0 disables the subtree.

Conditions #

Condition names have the form <Fact>.<Operator>. Missing facts do not match, except through an explicit presence test. Integer operands accept documented numeric types or decimal text; integer lists accept ranges. Unsupported operator/type combinations reject the generation.

OperatorFamiliesValue
EqualallMembership: a scalar, or a list (REG_MULTI_SZ) meaning any of. Integers accept a-b ranges; addresses accept CIDR prefixes and (IPv4) a-b ranges.
GreaterThanintegerA single integer; strictly greater.
LessThanintegerA single integer; strictly less.
HasflagsA flag name or list; all listed bits set.
HasntflagsA flag name or list; all listed bits clear.
Presentall, and Tag.<name> / Counter.<name>1: the fact exists for this packet or flow; 0: it does not. The one operator that looks through the absent-fact law. On a fact its layer never has, it refuses the generation rather than becoming an always-true condition.

Fact vocabulary #

Availability depends on the layer and the actual subject. A condition using an unavailable fact cannot make a connection pass. A Present test for a fact that the layer never supplies is rejected. Native endpoint identity comes from the socket's effective-identity stamp, not a name supplied by the application.

FactFamilyValuesPresent when
Directionstringin, outalways. Flow: the originator's side, for the flow's whole life
Interfacestringinterface name, for example, eth0always. Flow, outbound: the route's device
EtherTypeintegernumber, or ipv4, ipv6, arpalways. Not a Flow fact (a flow's family is its addresses')
SrcMacMACaa:bb:cc:dd:ee:ffframe has an Ethernet header; at the IP seats outbound, the machine's own device address
DstMacMACaa:bb:cc:dd:ee:ffframe has an Ethernet header. Not a Flow fact
VlanintegerVLAN idthe frame is VLAN-tagged (device seats) or the interface is a VLAN device (IP seats)
SrcAddr, DstAddraddressexact (10.0.0.5, fd00::1), CIDR (10.0.0.0/8, fd00::/64), IPv4 range (10.0.0.1-10.0.0.99)IP packet
Protocolintegernumber, or tcp, udp, icmp, icmpv6, sctpIP packet
TtlintegerTTL / hop limitIP packet. Not a Flow fact
Dscpinteger0..63IP packet. Not a Flow fact
Fragmentinteger0 or 1IP packet (only ever 1 before defragmentation, that is, at the RawPacket seat). Not a Flow fact
SrcPort, DstPortinteger0..65535TCP, UDP, or SCTP
TcpFlagsflagsFIN, SYN, RST, PSH, ACK, URG, ECE, CWRTCP. Not a Flow fact
IcmpType, IcmpCodeintegerICMP / ICMPv6 type and codeICMP or ICMPv6
Lengthintegerpacket length in bytes at the seat (stack view)always. Not a Flow fact
FlowStatestringnew, established, related, invalid, untrackedPacket layer at its proper seat; never at the RawPacket or Flow layers
Relatedinteger0 or 1: the flow was expected by another (an ICMP error for a live flow, FTP data)Flow layer only
Time.Year, Time.Month, Time.DayOfMonth, Time.DayOfWeek, Time.Hour, Time.Minute, Time.Secondintegerwall clock, UTC; DayOfWeek is ISO (1 = Monday .. 7 = Sunday)always. In Flow, a consulted condition expires the sentence at its next flip
Start.Year, Start.Month, Start.DayOfMonth, Start.DayOfWeek, Start.Hour, Start.Minute, Start.Secondintegerthe wall clock when the flow began, UTCFlow layer only; fixed for the flow's life, never expires a sentence
Localstringprogram, kernel, shared, none: what stands at this machine's end of the flowFlow layer only; always present there
Local.UserSIDS-1-5-19, or a well-known name (SYSTEM, LocalService, NetworkService, Everyone, Administrators, Users, …)Flow, Local is program
Local.GroupSID setSIDs or well-known names; any of the token's enabled groups (deny-only groups are invisible; the logon SID is among them)Flow, Local is program
Local.Integrityintegera level, or untrusted, low, medium, high, systemFlow, Local is program
Local.ConfinementSIDthe confinement SIDFlow, the program is confined
Local.CapabilitySID setany of the confinement's capability SIDsFlow, the program is confined
Local.ServiceSIDa service name (resolvd), or its S-1-5-80-… SIDFlow, the program is a service
Local.Processstringthe process GUID, 8-4-4-4-12 hex (case-insensitive)Flow, Local is program
Remote, Remote.*as Localthe other end of the flow, when it is on this machine tooFlow, loopback flows only
Interface.Kindstringwired, wireless, loopback, tunnel, bridge, otherInterface layer only; always
Interface.Idstringthe stable interface id (the inventory key name)Interface layer only; always
Interface.MacMACaa:bb:cc:dd:ee:ffInterface layer only; the interface has a hardware address
Interface.Pathstringbus position, for example, pci-0000:00:03.0Interface layer only; it is hardware
Interface.Driverstringkernel driverInterface layer only; it is hardware
Network.Idstringthe network record's key name under Networks\every layer: a network has been identified on the interface the packet crossed (see the network context)
Network.Namestringthe operator's Name on the recordevery layer; the record has one
Network.Truststringthe operator's Trust on the recordevery layer; the record has one
Network.Kindstringthe Interface.Kind the network was seen onInterface layer; a network has been identified
Tag.<name>integerthe flow tag's valuethe flow carries the tag (Packet and Flow layers; never RawPacket)
Counter.<name>[(...)]integera counter view, see belowthe packet has the view's key facts and a cell exists

Actions #

Names are case-insensitive. An action list can combine effects and a verdict; effects do not themselves authorize traffic. Unknown expressions or invalid operands reject the generation. PROMPT has no handler transport in the implemented engine and applies its fallback immediately.

ExpressionSpeciesMeaning
NULLabstentionNothing. A rule whose actions yield no verdict abstains.
PASSverdictThis layer approves.
DROPverdictRefuse silently.
REJECT / REJECT(Refused)verdictRefuse; look like nothing is listening — TCP RST, else ICMP port-unreachable.
REJECT(Prohibited)verdictRefuse; say policy did it — ICMP admin-prohibited for every protocol.
PROMPT(Handler[, Fallback])deferralAsk a userspace handler; on no answer apply Fallback (an action expression, nesting up to 4 deep). No handler transport exists in this release: the fallback applies immediately and the prompt is recorded.
TAG(Name, Set[, n])effectSet flow tag Name to n (default 1).
TAG(Name, Add[, n])effectAdd n (default 1) to the tag; an absent tag counts as 0 first.
TAG(Name, Clear)effectRemove the tag; it reads as absent afterward.
COUNT(Name[, n])effectEmit n (default 1) into stream Name.
COUNT(Name, Length)effectEmit the packet's byte length — the bandwidth primitive.
REPORT(level)effectEmit an ntfe.verdict.reported audit event, level 1..5, if the level clears CurrentReportingLevel. One report per rule per evaluation, at the highest level listed.
JOIN(profile)verdict, Interface layerBring the interface up and stand in the named profile: a path under Profiles\, using either path separator.
IGNOREverdict, Interface layerNever touch the interface; something else owns it.
DOWNverdict, Interface layerKeep the interface administratively down.

Interface actions are limited to its verdicts, NULL, and REPORT. JOIN requires an existing profile; a disabled profile causes abstention. Conflicting equal-priority profile choices have special startup/reload handling in netd's judgment reference.

Counter and tag references #

Counter.<name>(window, key) reads a stream written by COUNT. A window is seconds, minutes, hours, or days, at most one day; omission selects a cumulative total. A key selects SrcAddr, DstAddr, Interface, or a +-joined combination; omission selects a global cell. For example, Counter.dns(10s, SrcAddr) reads a per-source ten-second view.

A view requires some rule to write its stream. Sliding windows use eight buckets and can be stale by an eighth of a window. Matching reads the state before the current evaluation's effects, so a count does not affect its own threshold check. Missing cells and tags remain absent, rather than reading as zero in every condition.

Tag dependencies can only flow upward through RawPacket, Packet, and Flow; downward dependencies reject the generation. Tags survive policy generation changes. The kernel's store reference owns capacity, lifetime, and refusal accounting.

Executor references #

QuestionOwning reference
Profile values, inheritance, and accepted offersConfiguring Profiles and netd's registry manual
Interface fact and action rulesInterface judgment
Packet seat order and available factsSeats and dispatch and snapshot
Validation, rule limits, and reporting levelPolicy ingestion
Priority, abstention, and effectsEvaluation
Cached verdicts, time changes, and refusalsFlow layer
Native endpoint identityIdentity facts

Image seeds add ordinary, deletable rules; this reference does not promise which services an image exposes. DHCP and router discovery need policy too. Inspect installed rules and their accepted generation before changing them. For worked packet-policy patterns, see Authoring Packet Rules.

Network Utility Compatibility

Peios / Using Peios / Network Tools

These contracts describe the Peios package recipes, not a promise that every image contains each utility. Use the installed manual for exact options. Begin diagnosis with Checking Connectivity. The tools retain the invoking native token; installing one grants no extra privilege, port reservation, or packet-policy exception.

Probe and inspect #

ToolPurposeBoundary
pingICMP echoOrdinary IPv4/IPv6 echo uses datagram sockets; raw modes have separate authority checks.
tracepath, traceroute, mtrRoute, path MTU, and latency evidenceOrdinary UDP and echo-datagram modes need no raw-socket privilege; other modes can require it.
ssSocket inspectionNumeric UIDs are compatibility projections, not native owner identities.
digQuery a chosen DNS serverDirect queries do not change resolvd configuration.
ncTCP/UDP communicationOpenBSD implementation with Debian portability patches; optional TLS mode is not built.
tcpdumpLive capture or saved-capture decodingLive packet access needs native authority; ordinary file read access suffices for saved captures.
arpingLocal-link ARP probesUses packet authority and does not trace routed paths.
nmapTargeted host/service inspectionConnect mode and raw-packet modes have different authority requirements.

Ordinary echo does not use a POSIX group-range setting to authorize callers. PNP still evaluates its traffic. Raw and packet sockets require enabled SeTcbPrivilege; a tool's behavior-selection flag cannot confer it. MTR can fall back to echo datagrams when raw sockets are unavailable.

Nmap selects probing behavior using native privilege rather than projected UID zero. -sT -Pn requests TCP connect probing without raw host discovery; --privileged and NMAP_PRIVILEGED only select behavior. Its scripts retain the caller's authority. User data lookup uses an absolute $HOME/.nmap with normal FACS checks. Ncat and Nping are not included by this recipe.

tcpdump rejects Unix -Z identity dropping because a numeric UID change does not reduce native authority. Launch it with the intended native token. Capture filters select observations, not allowed traffic, and a captured frame can still be rejected elsewhere in the stack.

Named libpcap savefiles and Nmap logs are created with protected owner-only native descriptors. Existing destinations must be regular, singly linked, owned by the effective principal, and provably protected for that owner. Rotation follows the same creation rule. Streams supplied by a caller, stdout, shell redirection, and script-owned file operations instead follow their own destination policy. A private file does not protect its directory entry from a principal authorized to replace it.

Transfer and relay #

curl uses OpenSSL's system trust paths. Cookie, HSTS, and Alt-Svc saved state receives a private descriptor for the effective principal at creation, with no fallback to Unix mode bits. Equal projected UIDs do not confer access. State output requires a regular writable destination; ordinary downloads use normal destination policy. wcurl uses curl for file downloads.

socat supports TCP, UDP, Unix sockets, files, PTYs, process execution, and OpenSSL TLS. It starts only explicitly requested listeners or children, under the caller's token. Unix ownership, mode, umask, identity-switch, chroot, and network-namespace options are rejected rather than presented as native isolation. TUN, POSIX message queues, readline, and libwrap are excluded. Regular relay output uses ordinary FACS policy. Select the expected TLS identity and anchors for a private service explicitly.

For synchronized contents and private cryptographic output, use Copying Contents and Checking TLS.

Registration and throughput #

whois follows registration-server queries and referrals under normal PNP rules. Its recipe excludes mkpasswd and IDN conversion: supply ASCII or already converted punycode. /etc/whois.conf can override server selection.

For a measurement between cooperating hosts, start iperf3 -s on the receiver and iperf3 -c HOST on the sender. UDP, reverse direction, and parallel streams use -u, -R, and -P. The default port is 5201; the server needs native bind authority and policy for control and test traffic. Installation starts no measurement service.

iperf3 uses anonymous in-memory payload buffers. Received -F output and PID files use protected owner-only creation and validate existing regular, singly linked destinations before truncation. Send-side inputs use ordinary read checks; logs and redirected output use their destination's policy. Optional RSA authentication restricts measurement access but neither creates a Peios logon nor encrypts measured traffic. Protect private keys and the server's authorized-user file separately.

Copying Contents and Checking TLS

Peios / Using Peios / Network Tools

Choose the intended identity and destination policy before running a transfer or generating secret output. These instructions apply to the Peios ports; ordinary upstream builds do not establish the native-file guarantees below.

Synchronize contents #

  1. Identify the source and destination. Use a destination directory you control and preserve any contents that replacement could discard.

  2. For recursive contents, symbolic links, and modification times, adapt:

    rsync -rlt source/ destination/
    rsync -rlt source/ alice@server:destination/
    
  3. Verify the resulting contents and native descriptor. -X additionally copies ordinary user.* attributes, not descriptors, signatures, or other security attributes, even with explicit attribute filters.

New files use destination inheritance; updates retain the destination's complete descriptor. Unix owner, group, and mode are not native authority. Archive/security-preservation requests such as -a, -p, -o, -g, --chmod, ACL preservation, and --fake-super are refused. This is not a native security backup or restore mechanism.

Ordinary replacement uses an unnamed temporary inode in the destination filesystem. Publishing requires permission to read and restore the entire destination descriptor, including audit metadata. Unsupported staging or insufficient rights fail without silently falling back to in-place writes. The destination inode/descriptor check and final rename are not one atomic security transaction; coordinate concurrent permission changes separately.

If the interruption and hardlink tradeoff is appropriate, explicitly choose rsync -rlt --inplace source/ destination/. This retains the inode and its descriptor but changes its other hardlinks too. Interruption can leave partial contents. It is not an equivalent retry after a staged update was refused.

Alternate staging, partial/backup modes, delayed updates, hardlink preservation, basis-directory optimization, special-file preservation, batch mode, and unsafe symlink traversal are excluded. Replacement that would delete an object to change its type or link target is refused; deletion is a separate decision. Daemon serving is disabled, including over a remote shell, while normal SSH server-side transfers remain available. SSH supplies the recipient identity. Client password files need protected owner-only native policy.

Create private cryptographic output #

OpenSSL uses trustd's generated trust paths by default. Per-command CA files, directories, or environment overrides select different trust without modifying the machine store. Use trust for machine trust; do not rehash its generated directory independently.

  1. Choose a directory you control and the intended effective principal.
  2. Use the command's named output option for secret material: for example, the applicable -out, -keyout, -secret, -sess_out, or -keylogfile.
  3. Confirm success and inspect the resulting native policy before arranging any intentional service sharing.

Private keys, secret-bearing PKCS12 exports, session/key-log files, derived or random key material, RNG state, and decrypted plaintext use protected owner-only creation. Mixed exports are treated as potentially secret; public certificate/key output uses ordinary destination policy. Existing secret outputs must be regular, singly linked, owned by the effective principal, and provably protected for that owner. Refusal does not fall back to 0600.

Shell redirection creates its own destination. openssl ... > key.pem does not obtain the tool's named-output guarantee. Administrative privileges and mandatory controls still apply to native private files.

Verify a TLS peer #

openssl s_client reports certificate errors without necessarily stopping. For a strict check, require verification success and the intended identity:

openssl s_client -connect example.org:443 -servername example.org \
  -verify_return_error -verify_hostname example.org

Replace the host with the service being tested. For an IP identity, use -verify_ip. SNI alone is not hostname verification. Inspect a failed chain, name, or trust check rather than disabling verification to obtain success. A successful certificate check does not grant network access or change machine trust; listeners and connections remain subject to native policy.

File Sharing

Peios / Using Peios / Sharing Folders

Peios can share folders with Windows, Mac and Linux computers on your network. People reach a shared folder from their own computer's file manager and work with its files as if they were local, signed in with an account on the Peios machine. If you have used file sharing on Windows, this will be familiar: Peios speaks the same protocol, SMB, and uses the same model of shares, share permissions, and file permissions.

The file server is fservd, a service that peinit runs. You manage it with the File Sharing window or the fserv command.

Shares #

A share offers one folder on this machine under a name, such as Projects for /srv/projects. A Windows user reaches it as \\peios-box\Projects, and a Mac or Linux user as smb://peios-box/Projects, where peios-box is this machine's name on the network.

A share is defined once and switched on for each protocol it is served over. SMB is the only protocol so far, and a new share is served over it unless you say otherwise. Removing a share stops offering the folder; the folder and its files stay exactly where they are.

Shares live in the registry under Machine\Software\Fservd\Shares. fservd watches the key, so a change applies to new connections within a few seconds, without restarting anything. People already connected keep the share they connected to until they disconnect.

Browsing to the server, such as opening \\peios-box in File Explorer, lists the shares the person browsing can use: fservd tries each one as them, so nobody sees the name of a share they can't open. An administrator can list every share to everyone instead, with Show every share in the File Sharing window or fserv listing all. A share whose name ends in $ is never listed, but people who know its address can still open it.

Signing in #

People who connect sign in with an account this machine knows, such as a local account. The client proves it knows the account's password with NTLMv2, and fservd passes that proof to authd, which checks it against the account. fservd never sees the password. A successful sign-in creates a logon session for the person, as signing in at the console does, except that its logon type is Network.

fservd doesn't accept guest sign-ins, or the older LM and NTLMv1 proofs. Every signed-in session is signed, so a message changed on its way across the network is refused. Traffic is not encrypted, so share sensitive files only over networks you trust.

A client can sign its session in again without disconnecting, as Windows does on long-lived connections, and may switch to another account as it does. Files already open stay open with the access they were granted; everything after that is done as the new account. When a client reconnects after its network drops, it names its earlier session, and fservd closes that session's files first if it belongs to the same account, so nobody is locked out of their own files by a connection that is already gone.

Anonymous connections #

Some devices, such as scanners and media players, connect without signing in. Every share refuses them unless you turn on Allow anonymous for it, in the share's Network Access in the File Sharing window, or with fserv share set <name> --anonymous on. Browsing the server anonymously shows only the shares that allow it.

An anonymous connection acts as the Anonymous identity. It belongs to Everyone but not to Authenticated Users, and has Untrusted integrity, so it can use only files and shares that grant Everyone access, and it can't change anything labelled above Untrusted, which by default is everything. The Read-only for everyone signed in and Administrators can change; others read restrictions refuse it, since they grant signed-in people only. An anonymous session's messages are signed only if the device asks, and then with keys anyone can work out, so a message changed in transit isn't reliably detected.

Who can do what #

fservd acts as each signed-in person for every file operation: when someone opens a file through a share, the kernel checks the file's own permissions against that person's token, exactly as it would for a program they ran on this machine. A file someone couldn't read at the console, they can't read through a share either.

A share can also have its own network access, a security descriptor that limits what people can do through that share. When someone connects, fservd checks the share's network access; every file they then open is limited to what it granted. Network access only ever narrows the files' own permissions. It can make a share read-only for everyone, but it can't let anyone change a file whose permissions refuse them.

A share with no network access of its own leaves the decision to the files' permissions alone. That is the default, and it is usually what you want: the folder's permissions already say who can use the files. Add network access when the network should be more restricted than this machine, as described in Restricting Network Access.

Files in use #

When a Windows program opens a file it can say what others can do with the file while it has it open: read it, change it, or delete it. On Peios the kernel keeps those rules for everyone, so they apply to programs on this machine as well as to other people on the network. A program here that tries to change or delete a file someone has open without allowing it gets a "device or resource busy" error until they close it.

Deleting works as it does on Windows: a file deleted while others have it open keeps its name until the last of them closes it, and can't be opened again meanwhile.

File attributes #

Windows gives files attributes such as read-only and hidden. Through a share they work like this:

  • Read-only is a Peios attribute too, so it sticks. A read-only file can't be changed or deleted, by anyone, on the network or on this machine, until the attribute is cleared; attrib -r clears it here.
  • Hidden follows the Linux convention: a file or folder whose name starts with a dot is shown as hidden. Marking another file hidden from Windows has no lasting effect.
  • Created is the file's creation date. Copying a file onto a share keeps its original date, and Windows can change it. Peios also keeps the date the file system created it, which nothing can change.
  • Archive always shows as set on files, and changes to it aren't kept. A backup that copies only files with Archive set, such as robocopy /M or xcopy /M, copies every file each time.
  • Not indexed is kept as the file's PGSS Indexing preference, the user.pgss.indexing attribute that attrib +i sets here: setting it from Windows keeps the file's contents out of search, and clearing it removes the preference. A folder's preference covers everything inside it, but Windows shows it only on the folder itself. On a file system that can't keep it, it's accepted and not kept.
  • Temporary is accepted from Windows and not kept.
  • Extended attributes, the name and value pairs some Windows programs attach to files, are kept as Linux extended attributes named user. followed by the name in capitals, so getfattr shows them here. Linux programs' own user. attributes appear to Windows the same way, except user.peios. ones, which Peios reserves, and the indexing preference, which appears as not indexed. Peios standards' user.pgss. attributes, such as a file's icon, keep their lower-case names when Windows writes them back.

What is recorded #

fservd records an event when someone sets up a session, connects to a share, signs in again, or their session ends, and when its configuration is loaded. Each records the client's address and the person's security identifier. fservd.session.started carries the logon session that authd created, so you can join it to authd's authd.logon.attempted record and to the kernel's audit records of the files that person opened. Run evman fservd.share.connected to see what each event holds, and see Diagnosing File Sharing for queries.

For the command and its options, read fserv(8); for the service, read fservd(8). Every registry value is documented by regman: run regman 'Machine\Software\Fservd'.

Sharing a Folder

Peios / Using Peios / Sharing Folders

Share a folder when people on other computers need to open and save its files. When you finish, the folder is reachable from Windows, Mac and Linux computers by an address such as \\peios-box\Projects.

Before you start #

  • Sign in as a member of Administrators. Only Administrators can change shares.
  • Make sure the folder exists, and that its permissions let the people who will use it open its files. Sharing a folder doesn't change its permissions: File Sharing explains why.
  • Each person who connects needs an account on this machine.

Share a folder with the File Sharing window #

  1. Open File Sharing from the launcher. From a terminal, fserv --window opens the same window.
  2. Choose Share a folder in the sidebar.
  3. In Folder, type the folder's full path, such as /srv/projects, or choose Browse… to pick it.
  4. In Name, keep the suggested name or type another. The name is part of the address people type, so a short name without spaces is easiest.
  5. Leave Network access set to No network restriction, unless the share should be more restricted than the folder's own permissions.
  6. Choose Share Folder.

The new share's page shows its addresses under Connect, and the file server's state is on the Service page. If the file server is stopped, choose Start, and turn on Start when Peios starts so the share is available after every restart.

Share a folder with the fserv command #

  1. Add the share:

    fserv share add Projects /srv/projects
    
  2. If the file server isn't running, start it, and make it start at boot:

    fserv service start
    fserv service boot on
    

fserv share add refuses a folder that doesn't exist, a name another share already has, or a name with characters that SMB doesn't allow, such as / or :. Read fserv(8) for every option.

Check the result #

Run fserv share show with the share's name:

fserv share show Projects

The output includes SMB on, the access, and the addresses to connect to:

Share           Projects
Folder          /srv/projects
SMB             on
Access          No network restriction
Windows path    \\peios-box\Projects
Mac/Linux       smb://peios-box/Projects

fserv status shows whether the file server is running. Then connect from another computer, as described in Connecting to a Share.

Stop sharing a folder #

On the share's page in File Sharing, choose Stop Sharing…, or run:

fserv share remove Projects

The folder and its files stay where they are. People already connected keep the share until they disconnect.

Connecting to a Share

Peios / Using Peios / Sharing Folders

Connect to a share to open and save its files from another computer. You sign in with your account on the Peios machine, not the account on the computer you are using.

Before you start #

  • Get the share's address from its administrator. It looks like \\peios-box\Projects for Windows, or smb://peios-box/Projects for a Mac or Linux. Or browse to the server, \\peios-box, to see the shares you can use.
  • Know your account name and password on the Peios machine.
  • Your computer must support SMB 3.1.1. Windows 10 and later, current versions of macOS, and Linux with a recent kernel or Samba do.
  • If your computer can't find the Peios machine by name, use its IP address in place of the name, as in \\192.0.2.10\Projects.

Connect from Windows #

  1. Open File Explorer.
  2. Type the share's address, such as \\peios-box\Projects, in the address bar, and press Enter. To choose from the shares you can use, type the server's address, \\peios-box, instead.
  3. When Windows asks for network credentials, type your account name and password on the Peios machine.

To give the share a drive letter, choose Map network drive from the This PC menu, or run this in a terminal, replacing alice with your account name:

net use Z: \\peios-box\Projects /user:alice

Windows asks for the password, then shows the share as drive Z:.

Connect from a Mac #

  1. In Finder, choose Go › Connect to Server.
  2. Type the share's address, such as smb://peios-box/Projects, and choose Connect.
  3. Choose Registered User, and type your account name and password on the Peios machine.

Connect from Linux #

Most Linux file managers connect to an smb:// address. In GNOME Files, choose Other Locations, type smb://peios-box/Projects in Connect to Server, and sign in with your account name and password on the Peios machine. Leave the domain as it is: the Peios machine ignores it.

Check the result #

The share's folder opens, and you can open its files. What you can do with each file depends on its permissions on the Peios machine, and on any network restriction the share has.

If the connection is refused, see Diagnosing File Sharing.

Restricting Network Access

Peios / Using Peios / Sharing Folders

Restrict a share's network access when people should be able to do less over the network than on this machine, such as only reading files they could change at the console. A share's network access only ever narrows the files' own permissions; to let someone use files they can't use now, change the files' permissions instead.

Before you start #

  • Sign in as a member of Administrators.

  • Decide whether a preset fits. Most needs are one of these:

    • No network restriction: each file's own permissions decide. This is the default.
    • Read-only for everyone signed in: nobody can change files through the share.
    • Administrators can change; others read: only Administrators can change files through the share.

    Both restrictions grant signed-in people only, so they refuse anonymous connections even on a share that allows them.

Choose a preset #

In File Sharing, open the share's page, and choose Use beside the preset under Network Access. Or run fserv share set with the preset's name, open, read-only or admins-change:

fserv share set Projects --access read-only

Choose specific people and groups #

  1. In File Sharing, open the share's page.
  2. Under Network Access, choose Choose… beside Specific people and groups.
  3. Choose Add… to add the people and groups who can use the share, and give each Read, Change, or Full control. Remove the entries for anyone who shouldn't use it, including Authenticated Users, which a share without a restriction starts with. To admit anonymous connections on a share that allows them, grant Everyone instead.
  4. Choose OK.

From the command line, give the share a security descriptor in SDDL. This one lets Administrators change files and every signed-in person read them:

fserv share set Projects --security 'O:BAG:BAD:(A;;0x1301bf;;;BA)(A;;0x1200a9;;;AU)'

The rights are read (0x1200A9), change (0x1301BF), and full control (0x1F01FF). To name one group, put its security identifier in place of AU.

Check the result #

Run fserv share show Projects. Access names the preset in use, or says Custom network permissions. The change applies to new connections within a few seconds; anyone already connected keeps the access they connected with until they disconnect.

Connect as someone the share should restrict, and try the change it should refuse. A share that grants someone nothing refuses their connection outright, and fservd records fservd.share.connected with access-denied.

Diagnosing File Sharing

Peios / Using Peios / Sharing Folders

Diagnose a file-sharing problem when someone can't reach a share, can't sign in, or can't open or change its files. fservd records each step of a connection as an event, so the records usually say which step failed and why.

Before you start #

  • Sign in as a member of Administrators, so you can read the events and the file server's log.
  • Note the time of the failure, and the address of the computer that failed, if you know it.

Check the file server #

Run fserv status. Service should be active, and Shares should count the share as on SMB. If the service is stopped, start it with fserv service start. A warning such as fserv: warning: share Old: Path is missing names a share that can't be used; fix it with fserv share set, or remove it.

If a client can't connect at all and fservd records no fservd.session.started, check that the firewall admits SMB: net policy should show the smb flow rule, which passes inbound TCP port 445. fservd's package adds it; a rule an administrator wrote that refuses the port, or a missing rule, stops every connection before it reaches fservd.

Read the connection's events #

List the last hour of fservd's events:

evctl 'EVENTS fservd.* SINCE 1h ago TAKE 50'

A connection produces fservd.session.started when the person signs in, then fservd.share.connected for each share they open. Each record has the client's address in source.address. Show only failures:

evctl 'EVENTS fservd.* SINCE 1h ago WHERE outcome.success == false'

Then read outcome.reason on the failed record:

EventReasonWhat to do
fservd.session.startedauthentication-failedRead authd's record, below
fservd.session.startednot-ntlmv2Sign in with an account, not as a guest, using NTLMv2
fservd.share.connectedno-such-shareCheck the name, and that SMB is on for the share
fservd.share.connectedaccess-deniedThe share's network access grants this person nothing, or they connected anonymously and the share doesn't allow it

Run evman fservd.session.started for every reason and field.

Find out why a sign-in failed #

authd records every sign-in it handles as authd.logon.attempted:

evctl 'EVENTS authd.logon.attempted SINCE 1h ago WHERE outcome.success == false'

Its outcome.reason says whether the account name or password was wrong (authentication-failed), the account is restricted, or the account isn't allowed to sign in over the network (logon-type-not-permitted). authd never records the account name a failed sign-in gave.

When someone can connect but can't use a file #

fservd acts as the person for every file operation, so a file they can't open over the network is usually one they couldn't open at the console either. Check the file's permissions on this machine first. If those allow the operation, check the share's network access: fserv share show with the share's name shows it, and a restriction such as Read-only for everyone signed in refuses every change.

To record exactly which file access the kernel refused, add an audit entry to the folder's descriptor. Every record of the person's file access then carries the same subject.token.auth-id as the object.session.id on their fservd.session.started record.

Read the file server's log #

fservd writes a line to its log for each share it serves when it starts, and for each share it can't use:

evctl 'LOGS FROM fservd SINCE 1h ago TAKE 40'

Check the result #

Ask the person to connect again. A successful connection records fservd.session.started and fservd.share.connected with outcome.success true.

Filesystem Layout

Peios / Using Peios / Files and Volumes

The base layout separates packaged files, local overrides, generated output, and mutable state. Images and local mounts can differ. A path alone does not prove persistence, a separate storage budget, a backup policy, or permission to remove its contents.

LocationPurpose
/usrPackaged executables, libraries, helpers, shared files, and defaults.
/lclOperator-managed software and file-based overrides.
/system/retcGenerated configuration projected into the runtime /etc view.
/var/statePersistent service and identity state, including protected secrets.
/var/cache, /var/log, /var/crashComponent-managed caches and diagnostic data; event records need not be text files here.
/homeHuman home directories. Services use their configured state paths.
/data, /srv, /optBulk data, served content, and software with its own layout.
/runRuntime sockets, service directories, and locks.
/tmp, /var/tmpTemporary work; check the actual mount and cleanup policy.
/boot, /system/bootBoot inputs, the EFI mount, and generated boot artifacts.
/mnt, /mediaMount locations; creating a directory does not attach storage.
/proc, /sys, /devKernel and device interfaces.

Follow the runtime view #

The conventional /bin, /sbin, /lib, /libexec, /share, /include, and /conf views place local directories above vendor directories. The real-root /etc view additionally puts /system/retc above /lcl/etc and /usr/etc. An existing generated name can therefore hide a local override. Find the owning registry setting before editing generated output.

The +ro flag protects a stratum through that view; it does not make direct access to the backing /usr path universally read-only. On the reviewed x86-64 base, /lib64 is a relative link to usr/lib/x86_64-linux-peios, not a StrataFS mount. The /lib view still covers modules and firmware. Temporary boot views can differ from real-root views.

Use StrataFS inspection to identify the actual provider before changing a file. Removing a local override can reveal a vendor file; it does not create a whiteout.

Default policy is not a live inventory #

The retained fsbase recipe supplies these policy intentions. Later package, service, installer, or administrator changes can narrow them further. Inspect the deployed descriptors rather than assuming a path proves access.

ScopeIntended baseline
Public software and selected local configuration treesSYSTEM and Administrators manage; other users receive read/traverse access where specified.
/var/state, caches, logs, crash data, /data, and /srvAdministrative control with traversal where specified; no universal read grant to service contents.
/homeTraversal without a general directory-list grant; each home supplies its own policy.
/tmp and /var/tmpShared creation with creator-specific child policy, not inherited public access to every temporary file.
/var/state/secretsSYSTEM-only baseline.
Identity storesThe owning service and SYSTEM; for example, lpsd's credential store has its own narrower policy.

These are not interchangeable repair templates. In particular, applying a public system-tree descriptor recursively to private state exposes data. /lcl/policy holds privileged boot policy and is not ordinary override storage.

The retained installed layout uses a disk-backed /tmp without automatic boot clearing in fsbase. A live image's volatile layer has a different lifetime. Check actual cleanup and mount configuration before relying on reboot to erase a file. Check which EFI filesystem is mounted before replacing boot artifacts; generating an image elsewhere does not activate it.

Identifying Devices

Peios / Using Peios / Files and Volumes

Before a mount or destructive operation, compare the selected device's size, model, partition layout, and live use. Kernel names such as /dev/sda and /dev/nvme0n1 can change with discovery order.

IdentityWhat it follows
Filesystem UUIDThe filesystem; a clone can duplicate it.
Partition UUIDThe partition table entry, independently of its filesystem.
Hardware IDThe device's advertised serial or worldwide identity.
Bus pathThe device's position in the hardware topology.
Label or partition labelA human-selected name that need not be unique.
Disk sequenceAn instance in this boot, not a persistent reference.

The device manager exposes applicable links under /dev/disk/by-*. Check the resolved target, especially when clones are attached. A stable name does not prove that erasing the target is appropriate.

Do not assume those links exist in an initramfs without the device manager. A boot hook can resolve root=UUID= by probing devices directly. Check the image's actual discovery path. A real-root service depending on the links needs the appropriate device-manager dependency, plus handling for removal or discovery failure.

Device naming does not authorize opening the node. Its security descriptor and operation-specific checks still apply. Interface renaming similarly provides a configuration name, not proof of network identity or trust.

Mounting Storage

Peios / Using Peios / Files and Volumes

Inspect the device, existing mounts, and intended target before attaching storage. Use lsblk, part list, and mount, retaining diagnostics alongside the listings. Limited visibility does not prove a disk is unused.

Choose the missing-descriptor behavior #

PolicyPurpose
Deny missingUse provisioned storage with valid stored descriptors.
Ephemeral synthesisDerive missing descriptors without saving those derived values.
Persistent synthesisAdopt missing descriptors incrementally through deferred write-back.

A valid stored descriptor remains authoritative. A corrupt one is refused rather than replaced through synthesis. Unmanaged policy is reserved for kernel-owned cases; it is not an administrative way to disable file security. StrataFS has a fixed policy.

Synthesis considers parent inheritance, then the mount template, then the kernel fallback. Omitting a template does not mean private access. Persistent synthesis is not a whole-tree conversion, and a readable cached descriptor does not prove it reached storage. Before moving to deny-missing, verify the stored descriptors of rarely used files as well as ordinary working files.

The kernel mount reference owns defaults and administration, while descriptor storage owns synthesis, corruption, deferred write-back, and repair. tmpfs, devtmpfs, and boot images do not all default to ephemeral synthesis.

Verify the attachment boundary #

Policy belongs to the superblock, not the mountpoint. Bind paths can share it; a second mount of the same device need not create an independent policy. A policy change neither rewrites stored descriptors nor revokes cached rights on existing handles. Other filesystems mounted below it remain separate.

mount(1) documents attach-time policy and template options. Policy is set on the detached mount before attachment, so failure at that step does not expose a mount with unintended policy. Other setup can still have happened before a later failure. A nonzero status is not proof that no state changed.

Remount and bind operations are not policy-change interfaces. Disk Manager's inspection does not make its unimplemented privileged commit workflow usable. Changing policy on an existing instance requires a supported integration with the kernel API. The narrower volume-management privilege can satisfy that API's gate; do not add TCB merely because a command diagnostic names it.

Read-only mounting and ephemeral synthesis are separate choices. An ext filesystem can replay its journal even on a read-only mount. For preservation, use an inspection method that also prevents journal and device writes, such as the installer's documented read-only loop and noload procedure.

After attachment, verify source, target, filesystem, writable state, policy, and template. Missing policy details leave verification incomplete. Reopen files when checking a changed policy instead of testing through old handles.

Arrange startup deliberately #

Prelude's hooks mount the root before Peinit. Additional storage can use a service with an explicit identity, privileges, dependencies, and failure policy. A service using device-manager links must wait for those links, and must still handle later device removal.

Define repeat-start and partial-failure behavior. A successful Oneshot service can become inactive while its mount remains attached; service state is not live mount state. Do not use an option that lacks an existing-mount guard as proof of idempotence. Verify both the service result and the mount itself.

Mount Operations and Their Boundaries

Peios / Using Peios / Files and Volumes

mount attaches a filesystem or changes an existing mount. With no operands, it reads live mount state rather than attaching anything.

Source, target, and policy are separate choices #

A source identifies the storage or filesystem being mounted. A target is where its contents become visible. A mount policy controls how the Peios access model treats objects on that filesystem.

A new filesystem's policy is set before attachment. Failure to set that policy prevents attachment with an unintended policy. This does not make the whole command transactional: target creation or later propagation changes have their own effects.

Bind mounts share a source filesystem rather than copying it. Superblock options can affect shared state, while per-mount attributes concern the selected view. The command rejects superblock changes in a bind remount instead of silently changing every view of the filesystem.

Inspect live state before and after a change #

This implementation does not use /etc/fstab to supply missing operands or /etc/mtab as its source of truth. It reads the kernel's mount table. Listing and attachment are different modes, so a listing filter is not necessarily a valid attachment type expression.

A filesystem probe can refuse an ambiguous device rather than choosing between conflicting signatures. Inspect the source and resolve ambiguity before attempting an attachment.

Failure is not a rollback report #

A propagation change can fail after a filesystem has been attached. A nonzero status therefore does not establish that the target stayed unchanged. Retain diagnostics and inspect the live mount before retrying.

The accepted --onlyonce flag is not enforced by the executor. It does not make repeated invocation idempotent. Check existing attachments explicitly.

Fake mode skips mount syscalls, but target preparation can still create directories. It does not prove that a real operation will pass authorization or filesystem checks. A requested mkdir mode is not a verified Peios security descriptor; establish the target's security separately.

Keep storage lifecycle visible #

Regular-file images can need loop devices. The command can allocate or reuse suitable loop backing, and newly allocated loops use automatic cleanup. That mechanism does not make an image safe to modify through uncoordinated concurrent access.

mount(1) defines source syntax, policy restrictions, loop handling, namespace selection, and status codes. The filesystem's own documentation owns its specific parameters.

Detaching a Mounted Filesystem

Peios / Using Peios / Files and Volumes

umount detaches a filesystem from the mount tree. Its operand can name a mount point or a source resolved through live mount state.

Name the intended attachment #

A source mounted at several locations is ambiguous. Name the particular mount point when only that attachment should be removed. All-targets mode is an explicit request to expand the operation to every matching mount.

Recursive mode expands beneath a target and works from deeper mounts upward. Expansion can stop on a failure, leaving a partially changed tree. Inspect what remains before retrying.

Detachment and final cleanup can differ #

An ordinary unmount can fail while resources are busy. Lazy unmount removes the attachment from the visible tree while deferring cleanup until references are released. It is not a guarantee that every user has stopped using the filesystem or that a device is ready to remove.

Forced unmount is another distinct request whose meaning depends on the filesystem. Read-only fallback changes state instead of proving a detach. Use the mode that matches the recovery task, rather than escalating flags until a command returns success.

Check the resulting state #

The command reads /proc/self/mountinfo, including after entering a selected mount namespace. A query in another namespace can show a different set of attachments.

An aggregate failure can coexist with successful top-level operands. umount(1) defines ambiguous-source handling, expansion stopping rules, loop cleanup, and the status distinctions.

Inspecting Storage Devices

Peios / Using Peios / Files and Volumes

lsblk shows block devices and their relationships. It helps distinguish a whole disk, a partition, and a layered device before an operation uses one of those objects.

Before you start #

Use a terminal with Peiosutils installed. For examples that create files, start in a disposable working directory without existing example names.

Perform the task #

Run the command:

lsblk -o NAME,SIZE,TYPE,MOUNTPOINTS

Check the result #

The output shows available devices, sizes, types, and known mount points. The device set depends on the running system.

Missing information is not a negative finding #

Columns come from several sources, including kernel device information, filesystem probing, mount state, and device-node security. A source can be unavailable or unreadable even when the device exists.

An empty filesystem identity does not prove that the device is blank. Probe access can be denied, and missing optional libraries can limit the information available.

The owner and mode columns describe the device node, not the files stored inside its filesystem. Peios node security is not equivalent to a set of traditional mode bits.

For scripts, choose explicit columns and a structured output mode. The human tree is intended for inspection. lsblk(1) defines column sources and the representation of incomplete information.

Partitioning a Disk

Peios / Using Peios / Files and Volumes

part manages GPT partition tables. Begin with its read-only inventory and verification commands, and identify the whole disk by more than its transient device name. An unreadable inventory entry is not an empty disk.

Plan the EFI and root partitions, or the data layout required by the intended consumer, before writing. Partition changes can destroy access to existing filesystems. Preserve needed data and unmount the target's filesystems first. The whole-disk and mounted-device guards remain relevant even when replacing an unfamiliar table is explicitly allowed.

Creating a table, adding an entry, and deleting an entry are separate changes. The tool does not resize filesystems, relocate data, install a bootloader, or supply an undo transaction. A newly added partition is not yet a formatted or secured filesystem.

After a successful write, verify the table and confirm that the kernel sees the intended partition devices before formatting. A valid table does not prove an existing filesystem fits an edited entry. Use the installer for its supported whole-disk workflow rather than reconstructing that workflow from isolated partition commands.

part(1) owns size units, type aliases, confirmation flags, alignment, table recognition, and exit status. In particular, a bare size is a sector count; use an explicit unit when expressing a byte-sized plan.

Inspecting StrataFS

Peios / Using Peios / Files and Volumes

Use stratafs to inspect the current mount namespace before changing a merged path. It does not elevate the caller or modify files. An incomplete protected view fails rather than pretending to be a complete answer.

stratafs list
stratafs resolve /bin/sh
stratafs origin /bin/sh

The stack lists strata in precedence order. A path can have one provider, merged directory participants, shadowed same-type objects, masked different types, or an absent entry. The origin report names the actual providers; write and delete reports explain routing, not authorization.

A write can happen in place, copy up to the create stratum, or create a new object. Symlinks, immutable state, missing parents, and read-only strata can change that answer. The attempted operation still performs its own checks.

Review local overrides #

Use sweep on a mount to find objects in its create stratum, then diff on a selected override before deciding whether to retain it. A gap exists only locally; an override has a lower counterpart; a shadowed entry is hidden by a higher object or ancestor. Directory overrides can still merge contents.

Deleting a local object can reveal the lower object because StrataFS does not use whiteouts. The +ro flag prevents modification through the view, not all direct writes to the backing tree. Neither a sweep result nor a routing report is permission to remove the listed paths.

Diagnose a security or copy-up failure #

StrataFS requires stored descriptors under its fixed deny-missing contract. A lower mount's synthesis does not repair a missing stored descriptor for the view. Copy-up preserves the source's full descriptor; ordinary creation uses inheritance. A failed preservation step fails copy-up. Do not apply overlayfs assumptions to this implementation.

A stale copy-up after provider changes can require reopening. A successful open does not guarantee the first write succeeds. Use the kernel's StrataFS documentation for provider identity, copy-up, and failure semantics. stratafs(1) owns output states, JSON limits, and probe-oriented exit codes.

Disk Manager

Peios / Using Peios / Files and Volumes

Disk Manager displays disks, partitions, mounts, and startup mounts. Use it to inspect the machine's storage layout. Its change forms do not modify storage because the privileged disk-service backend is not implemented.

What is shown #

A disk page lists its model, capacity, device, partition table, and partitions. The bar represents each partition's share of the disk and marks free space. Opening a partition shows available filesystem, label, identifier, usage, and mount information.

Mounts lists active mounts, their options, and available access-policy information. At Startup shows configured startup mounts. StrataFS views include their constituent strata when readable.

Disk Manager samples every two seconds. It reads block information, the kernel mount table, filesystem statistics, and permitted policy data. Some raw-device and policy details need additional privileges. Unreadable information is marked rather than invented.

Before choosing a separate command that changes storage, compare the device, model, serial number, exact size, partition layout, and mount points. Not Readable and Contents unknown report missing visibility; neither means that a disk is empty or unformatted. Nonadministrative accounts can still see kernel-listed partitions even when raw-device details are refused.

A later mount can cover an earlier mount at the same point or an ancestor. Inspect the mount hierarchy when a filesystem seems to have disappeared. StrataFS lists strata in precedence order. Startup entries identified by UUID are distinct from system-managed mounts; displaying either does not enable editing it.

Reading a missing-permissions policy #

The labels describe how the kernel handles a missing security descriptor:

LabelPolicyInterpretation
Deny Accessdeny-missingDeny descriptor-based access until a valid descriptor is supplied
Give Permissions, Not Savedsynth-ephemeralDerive a descriptor and retain it in memory
Give Permissions and Save Themsynth-persistDerive a descriptor and schedule persistence
Not ManagedunmanagedNo filesystem access-control check from this policy; other kernel checks still apply

An ephemeral descriptor can remain cached with the inode. Do not interpret the UI description as a promise to derive a fresh descriptor on every open. Corrupt stored descriptors are not equivalent to absent descriptors and are not repaired by choosing synthesis. A filesystem without descriptor storage cannot persist the synthesized result.

The mount's permissions view describes its fallback template, not the access rules of every object already on that filesystem. Check the actual object when diagnosing an access refusal.

What cannot change storage #

The forms for erasing a disk, adding or removing a partition, formatting, mounting, unmounting, changing mount policy, startup configuration, and ejecting all end by reporting that nothing changed. Passing validation or confirming one of these forms is not a completed disk operation.

Use the separately documented storage tools when you need to perform an actual operation. Their risks and access requirements belong to those tools; do not infer them from this read-only inspection interface. See gxwi-disk-manager(1) for data sources and limitations.

Diagnosing Storage Pressure

Peios / Using Peios / Files and Volumes

Keep the exact failing operation, path, error, and time. A read-only mount, permission denial, or I/O failure is not automatically a space problem. Start with an existing path involved in the failure, or its existing parent.

df -hT /affected/existing/path
df -i /affected/existing/path

Record the filesystem, type, mountpoint, available space, inode availability, and diagnostics. Do not substitute the root filesystem's figures without checking that the path belongs to it.

Measure a narrow, authorized directory with du, retaining its errors and exit status. A partial walk understates what it could not read. Use the command's filesystem-boundary option when appropriate and avoid treating merged views as independent physical copies.

Filesystem usage and directory totals need not agree. Open-but-unlinked files, metadata, reserved space, snapshots, compression, sparse allocation, hard links, and stacked filesystems can affect the comparison. A pathname survey cannot account for every allocated block.

Choose the owner's supported remedy: package cache cleanup, log retention, service data maintenance, or removal of a known expendable build artifact. A large file is not proof that deletion is safe. Do not delete package transaction journals, live databases, or boot files merely to make space.

After the separately chosen remedy, repeat the same measurements and retry the original operation. Removing a pathname can not release its storage until an owning process closes it. Record that limitation instead of escalating to broader deletion.

Managing Packages

Peios / Using Peios / Packages

Package Manager presents peipkg's package queries and transactions. It runs as your account and uses the same plans, permission checks, history, and audit records as the command-line package manager.

Before you start #

You need the package database access required for the task, a running GXWI session, and the relevant repository or package file. Reading package records and changing installed software are separate permissions.

If the package supplies a configured feature, remove the feature's setup in Feature Manager first. Keep the package installed until cleanup reaches Not Installed; its scripts are needed to undo the configuration. If cleanup fails, preserve its output and resolve the feature state before removing the package.

Review and apply a transaction #

  1. Open Package Manager. Use Installed, Available, or Updates to select the package and action.
  2. Read the plan: packages to install, update, downgrade, or remove, and the expected download and installed sizes.
  3. Review any separate approval for an elevated action, such as replacing unowned files or accepting a downgrade. Approve only the action you intend.
  4. Confirm the plan and follow progress to the final outcome. Answer a modified-configuration-file question only after reviewing that file.

Check the result #

Inspect the final outcome, warnings, and History, then verify the installed package version and intended application behavior. Check Files compares installed files with package records. A transaction that was interrupted can offer Resolve; the most recent eligible transaction can offer Undo.

After plan approval, closing the window does not cancel the transaction. The application waits for it to finish. Do not assume a lost browser connection rolled back a change.

Explicit overrides and changed files #

A refusal can offer a specific retry, not permission to ignore every check:

  • Continue Anyway accepts stale repository metadata after refreshing failed to obtain newer information. That approval is recorded.
  • Replace It permits an install to displace an unowned file while keeping the displaced copy. An operation without that option needs its conflict resolved separately.
  • Update Anyway bypasses the publisher's alternate-update instruction. Check what that update method does before bypassing it.
  • Repositories leads to explicit review of an untrusted repository's key. The application does not approve repository trust during a refresh.

For a modified configuration file encountered during removal, Keep It leaves an unowned file, Delete It removes it while keeping a copy beside it, and Stop Everything cancels the removal. Inspect the final outcome and history rather than assuming a canceled interaction undid every action.

Repositories, roles, and roots #

Repositories lists sources and offers refresh, add, trust, and removal operations. Trust requires your explicit review of the signing key; update checks refresh repositories already trusted. Stale metadata and publisher-controlled update refusals have separate, explicit overrides.

Roles shows claims and their owning packages. Installation Roots shows named roots; creating them is a peipkg root task. Install from File uses the shared file dialog for a .peipkg file. See gxwi-package-manager(1) and peipkg(1).

Upgrading Peios from the Desktop

Peios / Using Peios / Packages

Upgrade Peios changes the machine's Peios release through upgrade-peios. Package Manager handles other software updates. This window uses the same release plan and permissions as the upgrade command.

Before you start #

You need permission to upgrade, trusted repository metadata, and a recovery plan appropriate to the release. Read the shared release-upgrade guidance before applying a machine-wide change.

Review and apply the upgrade #

  1. Open Upgrade Peios. Check the current release and edition package. Use Check Now to refresh already trusted repositories and request a plan without applying it.
  2. Read every proposed change, download size, and installed-size effect.
  3. Choose whether Apply Its Settings at the Next Restart should defer the release's registry seeds. Review the upgrade confirmation and any separate package approvals.
  4. Start the upgrade and follow it to completion. If the plan changed before execution, review the new plan before accepting it.

Check the result #

Read the final outcome and installed release state. The application does not restart the machine. If settings are deferred, verify that pending state and apply them at the planned restart. Apply Now requests their immediate application instead.

Once approved, the transaction continues to its result even if the window is asked to close. Continue Anyway after stale-repository information is an explicit choice to use the available metadata, not a successful refresh. See gxwi-upgrade-peios(1) and the upgrade command's documentation.

Recovering from a refusal or incomplete result #

An untrusted repository needs confirmation in Package Manager; checking for a release does not grant that trust. When another package change holds the backend lock, wait for it to finish before trying again.

A settings-application failure does not undo an installed release. Inspect the pending seeds and the reported package result separately. Apply Now asks the release updater to apply waiting seeds; a restart also provides the configured application point.

The driven upgrade protocol reports an explicit cancellation separately from completion. A canceled result stops before release seeds are staged or applied. Already completed backend effects are not a general rollback transaction.

An installed package version does not establish which kernel or services are running. Follow the shared release-upgrade activation checks before relying on the update. The desktop provides a result display, not proof that all changed software has restarted.

Stored Records

Peios / Using Peios / Reading Records

eventd stores events, logs, and metrics so that you can inspect what a Peios machine recorded. Each kind answers a different question and has a different delivery guarantee.

The stores hold these records:

KindContentsDelivery
EventsStructured records from kernel ringsSequence receipts and detected-loss records
LogsText with an origin and output-stream flagBest effort through the trusted output broker
MetricsNumeric samples identified by names and labelsBest effort with publication authorization

A metric series combines a name with its labels. Samples from different label sets belong to different series even when they share a name.

Producers and record meaning #

Service output reaches eventd through peinit's output broker. A log retains its origin, stream, and run context. Hooks and health checks can have their own origin suffixes under the service name; jobs have job identifiers. A service attached through TTYPath writes to its terminal instead of that capture path. Standard error identifies a stream, not necessarily an error. Read Service Output and Logging for capture and backpressure behavior.

Structured events identify a type and carry fields defined by its event catalog. Use evman to interpret those fields rather than inferring identity or causation from the event name. A kernel ring is volatile; eventd supplies stored history within collection and retention limits.

Counters describe accumulating quantities, gauges describe changing levels, and histograms describe distributions. Compare samples within the same label set and account for producer restarts before interpreting a counter's rate. eventd publishes its own health under eventd.*.

Use Event Viewer for interactive inspection, or query records with evctl. Its read policy is the same boundary for either client.

Visibility #

Queries run with the caller's socket identity. eventd checks access to record names and individual fields before returning data. It omits denied records and fields without announcing their existence. An empty result therefore does not establish that nothing happened.

Use the query client rather than opening the databases directly. Direct file access bypasses eventd's query authorization.

Retention and loss #

Stored history is finite. Retention removes old records and can remove records to meet configured size limits. Kernel event rings can overwrite records before eventd reads them; log and metric sockets can drop input. A successful send is not a persistence acknowledgment.

The eventd.events.lost event describes detected missing event sequences. It cannot reconstruct their payloads. eventd.store.quarantined describes a corrupt database moved aside. Use the eventd evman records to interpret the fields of either event.

See Finding Missing Records when a result differs from what you expect.

Interpreting Events

Peios / Using Peios / Reading Records

An event records an observation: an access check completed, a service started, or a package changed. Its type identifies the observation, and its fields describe it. Read the definition before drawing conclusions from a record or from its absence.

Find the definition #

Each component supplies event and field definitions in .evman files under /usr/share/evman. The event manual reads those installed definitions. Consult the catalog shipped with the producer's version when interpreting older records.

An event definition describes its trigger, tier, field presence, and any meaning specific to that event. A field definition supplies its general type and vocabulary. A group names fields that travel together. The catalog can define fields that no current event carries; a definition alone is not proof that a producer writes the field.

The catalog format defines how components maintain these records. Event and field lookup belongs to the catalog, rather than a separately maintained table in Learn.

Some components also describe their events in their manuals, where an event's meaning depends on the mechanism behind it:

  • The kernel's access control subsystem describes its audit records in Event Families and Delivery. The registry's Audit page and StrataFS's Audit page describe theirs. The kernel's Emission Policy page describes how it decides which event types to write.
  • eventd describes the events it writes about itself in Synthetic Event Payloads.
  • Authentication Events describes the logon, attestation, and credential events of authd and lpsd.

Identify the transport and origin #

KMES carries kernel and userspace events in shared per-CPU rings. The kernel adds the event's sequence, CPU, timestamp, and identity stamps. Userspace chooses its event type and payload, so a kernel-looking type name does not establish a kernel origin. Check emitter.class and distinguish the stamped identity from identities asserted inside the payload.

emitter.token.guid identifies the effective token at emission; emitter.true-token.guid identifies the primary token before impersonation. emitter.process.guid identifies the process instance. A null identity stamp must remain unknown. It does not identify a privileged caller. Read the kernel event model for the stamp and wire-layout contract.

Some records use other paths:

  • eventd inserts its own operational events into its store. They have no KMES sequence or kernel-stamped emitter identity.
  • LCS watch records report registry changes through a key file descriptor. They have their own binary format and are notifications, not KMES events or an audit trail.
  • Logs and metrics use separate ingestion paths and stores. Their delivery guarantees differ from event collection.

A KMES identity stamp is kernel attribution, not a cryptographic signature. It does not authenticate the truth of an arbitrary payload or provide non-repudiation for an exported record.

Decode fields according to their definitions #

A dotted payload path describes nested MessagePack maps: subject.token.sid means the sid key inside token inside subject. It is not a literal subject.token.sid key at the top level. A path cannot be both a value and a container for other fields.

Read absence against the event's declared presence: required, optional, or conditional. Do not replace an omitted value with zero, an empty string, or nil. Required data missing from a record needs investigation; optional data missing from it establishes no value.

Types carry units and wire representations. SIDs, GUIDs, and ACEs use binary values; time and duration values use nanoseconds. Masks need their object kind. Parallel arrays must be interpreted together. Resolve principal names for display while preserving the original SIDs. The value conventions define the complete table.

Consumers should ignore unknown fields and retain unfamiliar values from open enumerations. Closed enumerations and field types have stronger contracts. The extension rules distinguish additive changes from vocabulary changes that require a new version. Successful transport decoding does not prove catalog conformance.

Account for loss and ordering #

A reader has its own position in each shared ring; it does not receive a private buffer. Writers can overwrite unread events. Slow readers do not block other readers or the producer, and overwritten records cannot be recovered from KMES. A later attachment can still read records that remain in the ring.

Sequence establishes order within a CPU for one boot. Keep CPU and boot context with it. Wall-clock adjustments and different CPUs prevent timestamps from establishing a total causal order across the machine.

eventd persists the records it receives and reports detected sequence gaps. Collection, storage failure, retention, filtering, and authorization can all limit what a query returns. Follow the missing-record workflow before treating an empty result or a gap in a filtered display as proof of what happened.

Querying Records

Peios / Using Peios / Reading Records

Use evctl to read events, logs, and metrics from a terminal. It sends one query to eventd and writes only the records that the caller can read.

Before you start #

Before querying:

  • Install the evctl client and start the configured eventd service.
  • Use an identity permitted to read the requested records.
  • Choose the record kind and time range needed for the investigation.

Run a query #

  1. Select an EVENTS, LOGS, or METRIC query using the observability query language in the Peios userspace protocols specification (PSPU).
  2. Pass the complete query as one quoted argument to evctl. Quoting prevents the shell from expanding patterns or splitting strings.
  3. Read standard output for records and standard error for diagnostics. Check the exit status before treating a finite result as complete.

For exact flags, output formats, and exit statuses, read evctl(1). The default socket is /run/eventd/query.sock; --socket selects the configured path when the deployment uses another location.

Simplify an expression that exceeds the limit #

eventd rejects expressions deeper than 128 levels with the query error expression depth exceeds 128 levels. The limit applies separately to nested grouping parentheses and to the structure built from AND and OR predicates. A long flat chain can exceed the limit even without parentheses.

Remove redundant grouping and simplify the predicates before retrying. The rejection is a query error, not an empty successful result. Check standard error and the exit status as you would for another query error.

Check completion #

For a finite query, evctl holds the initial records in a temporary spool until eventd confirms completion. A query failure before that confirmation publishes none of those records. Copying a completed spool to the output can still fail and leave partial output.

A streaming query confirms its initial result before publishing it, then prints live records as they arrive. A later failure does not invalidate records already published. Restarting the query starts a new query; it does not resume an acknowledged cursor.

An empty successful result means that no matching, readable records were returned. It does not prove that every record remains available.

Event Viewer

Peios / Using Peios / Reading Records

Event Viewer reads this machine's records from eventd. It separates Events, Metrics, Logs, and Settings, and performs queries as your account. The backend filters records according to their read policy.

Events and logs are displayed newest first. A list starts with the newest 200 records; Show older adds another 200, and a window holds at most 1,000. Pause keeps the list still and Resume continues updates. Selecting a row shows its available fields.

Event filters narrow by type and source. Log filters narrow by origin, text, or errors. Metrics use named dashboards of charts rather than the row list. Dashboard preferences are personal and stored under CurrentUser\Software\gxwi-event-viewer.

Interpreting missing records #

A missing event is not proof that it did not occur. Retention, query filters, time range, and access policy all affect the result. Event Viewer tries to read the policy and explains known hidden names. When that policy cannot be read, it reports that some data could be hidden rather than claiming complete visibility.

The Settings tab edits eventd configuration and read policy only where access permits it. It uses eventd's registry manual for meaning, defaults, ranges, and application timing. The viewer's dashboard schema belongs to its own registry manual.

See Reading Events and Logs and gxwi-event-viewer(1).

Reading Events and Logs

Peios / Using Peios / Reading Records

Use Event Viewer to find a recorded event or a service's logs. Narrow the query enough to inspect the relevant records, then retain the context needed to interpret them.

Before you start #

You need Event Viewer, a running eventd query service, and access to the records. Know the approximate time, origin, or event type involved.

Find a record #

  1. Open Event Viewer and select Events or Logs. Services Manager's Logs action can open the selected service's origin.
  2. Set the relevant type or source for events, or origin and text filter for logs. Use the errors-only filter when that matches the question.
  3. Select Pause if new rows make inspection difficult. Select a row to inspect its full visible fields.
  4. Use Show older to extend the displayed history and Resume when you want live updates again.

The initial time range is the last 24 hours. Select a range containing the incident before paging backward; any time removes the time restriction but cannot restore records removed by retention. Apply typed filters with Enter or Apply. An errors-only filter selects standard error, which is not proof that each selected line reports a failure.

If following stops, preserve the notice before selecting Show the newest. Resuming at the newest records does not establish what happened in the gap. Use Copy on relevant rows to preserve their visible fields with the job, boot, time range, and filters.

Check the result #

Read the record's time, type or origin, and fields, together with any visibility note. A list is bounded to 1,000 rows, so use a narrower query or evctl when your investigation needs a different range or query shape.

If eventd refuses the connection, address that refusal rather than treating the empty display as a result. If records remain absent, check the filter, retention, and read policy before concluding that nothing was recorded.

For a systematic check of scope, access, retention, and collection failures, follow Finding Missing Records. Keep a visibility notice with the evidence: it describes readable names or an unknown policy, not proof that hidden matching records exist.

Arranging Metric Dashboards

Peios / Using Peios / Reading Records

Event Viewer's Metrics tab lets you arrange charts into personal dashboards. A chart's time range, transformation, aggregation, and grouping change the question it asks eventd.

Before you start #

You need read access to the metric and permission to save your dashboard preferences if they should persist. Inspect what the metric measures before choosing its chart options.

Arrange a chart #

  1. Open Metrics and select or create the intended dashboard. Without saved dashboards, the viewer shows eventd health.
  2. Add the relevant metric and choose the time range.
  3. Select the transformation and aggregation suited to its meaning. A cumulative counter often needs a rate or delta; a measured level can use its recorded samples.
  4. Choose whether series are combined or displayed separately, then save the arrangement.

Check the result #

Check the chart's units, range, and series labels. A combined series can hide differences between its individual sources. A gap can indicate no sample or inaccessible data, not a measurement of zero.

Dashboard preferences allow up to 64 dashboards and 32 charts per dashboard. Malformed saved entries are skipped. Exact storage syntax is owned by gxwi-event-viewer.regman; eventd owns query and metric semantics.

Finding Missing Records

Peios / Using Peios / Reading Records

Check query scope and collection health before concluding that a record was never written. Keep the evidence before changing retention or removing stored files.

Before you start #

Record the incident time, service or event name, and relevant job and boot identifiers. A service restart creates another run; matching only its name can mix unrelated attempts. Preserve available records before changing retention or attempting storage recovery.

For Event Viewer controls and visibility notices, follow Reading Events and Logs. The daemon checks below apply regardless of the client.

Inspect the result #

  1. Check the query's record kind, name filters, and time range. A relative time range changes each time the query runs.
  2. Check the command's exit status and diagnostics. A connection or query error is not an empty successful result.
  3. Confirm the caller's identity and intended read policy. Authorization can omit records or fields without disclosing them.
  4. Inspect detected-loss and quarantine records when your identity can read them. Consult eventd.events.lost and eventd.store.quarantined in evman for their field meanings.
  5. Check retention and storage diagnostics. Records removed by retention or held in an excluded historical shard do not return through queries.

Interpret the evidence #

The absence of a loss record does not prove complete collection. eventd cannot count every datagram rejected by a full kernel socket queue, and a storage failure can prevent the daemon from persisting its own report.

Logs reflect text received from the output broker. Whether a service sends its output to that broker belongs to the service manager's configuration. Do not change eventd's read policy to compensate for a producer that never sent a record.

A logical retention limit is not a hard filesystem quota. SQLite can retain free pages, and write-ahead logs occupy additional disk space.

Retention and unavailable history #

Read the effective settings and their defaults in eventd's registry manual. Age and size limits are removal criteria, not a promise of minimum history. Size pressure can remove records younger than the age limit. Event retention can remove an earlier boot together with its loss records; log and metric retention remove older entries or samples.

A query timeout means the query failed to finish. It is not itself evidence that ingestion lost records. Save the error, then try a narrower time range to investigate the failing query.

A running daemon can exclude an unreadable or unsupported historical shard while serving its other stores. Inspect startup diagnostics as well as the query result. Corruption encountered during a query fails that query; quarantined stores are not silently repaired into complete history.

Current retention values cannot show which records an earlier configuration removed. Likewise, a missing loss event cannot account for the final volatile batch lost during power failure. Keep these limits with the investigation.

Preserve the store #

Do not delete live database files to make a query succeed. Preserve the query, diagnostics, timestamps, and relevant configuration, then follow the deployment's recovery procedure. Replacing a corrupt store gives the service an empty store; it does not recover lost history.

Deleting records leaves pages for reuse and does not necessarily shrink a database file. eventd does not automatically run VACUUM. Do not treat a logical retention setting as a procedure for repairing or compacting a live store. Keep quarantined files intact for the administrator handling recovery.

Check the conclusion #

Record which possibilities the evidence supports: query scope, authorization, retention, collection loss, or unavailable storage. If the checks are inconclusive, retain that uncertainty. Save a completed query with its completion context instead of labeling an empty display as proof that an event never happened.

Saving Query Evidence

Peios / Using Peios / Reading Records

Keep a query result with its diagnostics and scope so that another reader can distinguish a completed capture from an empty or failed attempt.

Before you start #

Before capturing records:

  • Choose a private directory and unused output filenames.
  • Select a finite query without STREAM.
  • Record the identity, machine, query text, time zone, and client version.

The destination directory's native security descriptor and inheritance must restrict new files to the intended readers. A shell umask or chmod is not a substitute for that Peios access policy. Use an existing directory you control; ask its administrator to establish the policy if needed.

Check that both output names are unused regular-file destinations, not existing files, symlinks, or pipes. Shell redirection can truncate a file before the query runs. Allow space for the output and the client's temporary spool. The process's temporary directory must be writable, suitable for sensitive data, and support anonymous temporary files (O_TMPFILE).

Capture the result #

  1. Write standard output directly to the result file and standard error to a separate diagnostic file. Avoid a pipeline that can close early.
  2. Record the command's exit status immediately after it exits, before another command replaces the shell's status value.
  3. Inspect the diagnostics and mark a nonzero or interrupted attempt as failed. A failed output copy can leave part of a completed result.
  4. Keep the exact query, capture times, status, and diagnostics beside the result. Record any result-count limit and whether a relative time range was used.

For example, after checking the private destination and unused names:

evctl --format jsonl 'EVENTS kacs.* SINCE 1h ago TAKE 50' > incident-events.jsonl 2> incident-events.err
capture_status=$?
printf 'evctl exit status: %s\n' "$capture_status"

This is at most 50 readable matching records since one hour ago, not all records from that hour. The relative range moves on each attempt. Keep the start and finish times, query, installed evctl version, and status beside the capture. JSON Lines stores one JSON object per record.

If the shell cannot open a redirection target, the client might not run. Preserve that error too. For a client failure, consult evctl(1) for exit statuses and inspect both destination and temporary-storage errors. Use new names for another attempt rather than overwriting its evidence.

evctl treats an output pipe closed by its reader as success. A pipeline that selects only the first records therefore does not establish that the whole query was captured. Filter a saved result after capture instead.

Check the result #

For a direct capture to a regular file, a zero status means the finite query and output publication completed. It does not establish complete system history: authorization, retention, and collection loss still bound what the result contains.

Keep the original capture private and unchanged. Permission to read a record does not automatically permit sharing it with another audience.

Finding an Event's Meaning

Peios / Using Peios / Reading Records

evman reads installed event documentation. It explains what an event records and what its fields mean; it does not report which events occurred on this machine.

Read the event and the field together #

An event definition describes when it is emitted and which fields it can carry. A field definition describes the field's general type and meaning. An event can add a narrower explanation for its use of that field.

Pay attention to required, optional, and conditional presence. A missing field is not necessarily malformed if the event's rules make it conditional. Likewise, a familiar field name does not imply that every event carries it.

Distinguish enumerated values from an open vocabulary #

A closed value list claims completeness under its definition. An open list can grow, so consumers need a deliberate policy for values they do not recognize.

Some common fields belong to the record header rather than the payload. Their documentation identifies that location. Do not assume that the same information appears twice.

Search the installed corpus #

Exact lookup selects a named event or field. Prefix lookup helps explore a subsystem, and keyword search matches names and summaries. Derived names can resolve through documented suffix or standard-attribute rules; read which rule supplied the result.

For example, look up an access-check event, a field, or a subsystem prefix:

evman kacs.audit.access.checked
evman subject.token.sid
evman kacs.audit

The field card lists events that carry the field. Use those relationships when replacing a field-index lookup. The installed packages determine the available definitions; a missing package can mean missing documentation. For an older capture, keep the producer's version and catalog with the record rather than assuming the current definitions are identical.

Packages supply definitions under /usr/share/evman. Catalog validation checks consistency across those definitions. A valid catalog describes an interface; it does not establish that a particular event was recorded or that its payload passed runtime validation.

Use the event store or Event Viewer to investigate occurrences. Use evman(1) for lookup and catalog-validation syntax.

Inspecting the Raw Event Stream

Peios / Using Peios / Reading Records

revstrm reads KMES directly, without eventd's storage or query path. It is a diagnostic consumer, not a durable audit sink. Use eventd for stored history and retain its collection/retention limits when drawing conclusions.

Observe a bounded stream #

  1. Confirm that the caller has enabled SeSecurityPrivilege and the native event interface is available. Administrator membership alone does not establish that the privilege is enabled.
  2. Run revstrm to follow, or revstrm --snapshot to drain available data and exit. Snapshot drains CPU rings in order; it is not an atomic cross-CPU snapshot or a request for history predating attachment.
  3. Narrow display with repeatable --type globs or --origin classes. Use --pretty to expand payloads when studying individual records.
  4. Record loss markers and stderr with the output. A ring that falls behind overwrites old data, and display filtering does not prevent that loss.

The header gives UTC time of day, CPU, per-ring sequence, origin, and event type. It omits the calendar date and does not merge CPUs into one event order. Do not interpret a displayed sequence gap without accounting for filters.

Interpret payloads and completion #

The installed event catalog supplies field types. Known SIDs, GUIDs, masks, enumerations, timestamps, durations, and byte counts receive readable forms; unknown bits and values remain numeric. Without a matching catalog entry, field-name fallbacks are less authoritative. Malformed MessagePack falls back to a hex preview rather than becoming a decoded record.

Compact output can truncate a long payload. Pretty output expands it but can slow draining. Redirecting to a file or reducing output cost can help; neither guarantees lossless capture. Native file policy applies to the chosen destination.

Follow mode ends on interruption, output failure, or exhausted drain threads. The implementation treats output failure as termination and can finish after per-ring errors, so a zero exit status alone is not a complete-capture attestation. Inspect diagnostics and loss accounting. revstrm(1) defines its option and output details; evman explains event schemas.

Operating eventd

Peios / Using Peios / Reading Records

eventd runs as a managed service with protected store directories and a restricted service identity. Its package supplies registry seed files; installing those files does not apply their contents to the registry.

Startup configuration #

The registry key Machine\System\eventd supplies six required paths: three store directories and three socket paths. Missing or invalid paths prevent startup. eventd(8) and the eventd regman records describe the command and configuration values.

The service definition runs a short --prepare-security hook as SYSTEM before starting the daemon. That hook prepares registry authorization defaults. The long-running service does not acquire policy-editing permissions merely because the hook needed them.

A deployment must provision the service identity, privileges, registry configuration, and protected directories together. Copying the executable alone is not a complete installation.

Live changes #

The daemon watches configuration and applies valid tuning changes. Invalid live changes keep the last valid setting. Store paths, socket paths, and shard count apply at restart. Read each regman record's applies field before planning a change.

Read policy and metric publication policy use security descriptors under Machine\System\eventd\Security. A read grant does not grant metric publication. Broader grants can disclose records that were already stored.

Health and storage #

The daemon writes its own eventd.* health samples directly to the metric store. These do not pass through the publication socket. Health counters restart when eventd restarts, so compare changes with that lifecycle in mind.

A store-size metric measures disk use, while retention limits logical live data. A database can retain reusable free pages after deletion. Inspect both filesystem capacity and retained data when diagnosing pressure.

For implementation details, read the eventd manual.

Changing Event Viewer Policy Settings

Peios / Using Peios / Reading Records

Event Viewer's Settings tab exposes eventd's configuration and read policy. Configuration controls the service; policy controls which names and fields accounts can read. Your personal dashboards are separate preferences.

Before you start #

You need write access for the selected configuration or policy entry. Record its current value or descriptor and read eventd's registry manual. Socket and storage paths are displayed but are not editable here.

Change and verify #

  1. Open Settings and select the relevant configuration group or read-policy pattern.
  2. Read the expected type, range, default, and application timing. Enter the value and save, or use the permissions editor for a pattern.
  3. Inspect the result. A value outside the accepted range is refused.
  4. Verify the service's active behavior at the stated time. For access policy, query as the affected account rather than only as an administrator.

Pattern scope #

A pattern can cover a name and its descendants. The most specific matching pattern wins. Removing a specific pattern exposes the broader policy; it is not necessarily a denial. The fallback * patterns cannot be removed through this interface.

A new pattern starts from the permissions that already apply to its name and changes only when the descriptor is applied. Confirm the intended scope before adding a broad grant or deny. Use eventd's own documentation for the precise access model and configuration semantics.

The Peios C SDK

Peios / Developing for Peios / SDK Basics

The Peios C software development kit (SDK) provides libraries for programs that use Peios security, registry, and event services. Use libpeios for application services and librsi for a registry storage backend.

Both libraries expose a C application binary interface (ABI). C++ and other languages can call that interface without depending on the libraries' internal Rust implementation.

Choosing a library #

The libraries have separate roles and can be linked into the same program:

LibraryRoleHeaderLink option
libpeiosSecurity, registry clients, and events<peios.h>-lpeios
librsiRegistry storage backends<rsi.h>-lrsi

The internal peios-cabi crate supplies allocation, error handling, and system-call helpers. Applications do not link it directly.

The SDK repository releases these components together. The shared objects retain separate compatibility boundaries: libpeios.so.0 and librsi.so.0. A package version identifies a release; the shared object's SONAME identifies its binary interface. An SDK release does not imply a kernel release.

Portable data and kernel services #

Security identifiers, access control lists, security descriptors, and MessagePack values can be built and parsed in userspace. These operations do not need a running Peios kernel.

Opening tokens, accessing registry keys, and sending or receiving kernel events require the corresponding Peios kernel services. Building a program on a development host does not establish that these operations work there.

The SDK pins kernel headers and shared semantic crates when it is built. That source pin identifies the build input. It is not a requirement to run that exact kernel commit, and it does not establish compatibility with every kernel version.

Starting with C #

Begin with installing and linking, then compile a complete program. Read library conventions before managing buffers or file descriptors.

For a registry backend, start with registry sources. The installed headers own the complete function declarations and parameter contracts. The SDK reference explains how to use those contracts.

Installing and Linking

Peios / Developing for Peios / SDK Basics

Link your application to the library whose services it uses. Install the matching development package when compiling, and the runtime package on machines that run the resulting executable.

Before you start #

Prepare these build inputs:

  • A C or C++ compiler for the target system.
  • The development package for libpeios, librsi, or both.
  • The Peios kernel userspace API headers required by those packages.
  • pkg-config configured to find the target system's package metadata.

Choosing packages #

Each library has the same package split. Replace libpeios with librsi for registry source development:

PackageContentsNeeded for
dev.peios.libpeiosVersioned shared libraryRunning dynamically linked programs
dev.peios.libpeios-develHeaders, linker symlink, and peios.pcCompiling programs
dev.peios.libpeios-staticStatic archiveStatic linking
dev.peios.libpeios-debuginfoSeparate debugging informationDebugging library code
dev.peios.libpeios-debugsourceSource files for debuggingStepping through library code

Use headers and libraries from the same SDK package set. Do not combine headers from an arbitrary kernel checkout with an unrelated library build. The library headers include <pkm/*.h> definitions; the directory name is part of the installed include interface.

Linking an application #

Use the complete first.c program from compiling a first program:

  1. Include <peios.h> or the individual <peios/*.h> headers that the application uses.
  2. Obtain the compiler and linker options from the peios pkg-config module. Put the library options after the source files or object files.
  3. Build the program for the same target as the installed library.

For librsi, use <rsi.h> and the rsi pkg-config module. Applications that serve registry data and also access other Peios services can link both.

Checking the result #

A successful compile confirms that the headers are available. A successful link confirms that the required symbols are present in the selected library. Run the first-program example to check portable data handling.

Calls that access tokens, registry keys, or kernel events need a Peios kernel with the required services. Test those calls on the target system with the privileges and objects described by their guides.

Static linking #

The static package contains libpeios.a or librsi.a. Select that archive explicitly when constructing the linker command. Static linking includes the SDK code in the executable; the application's other dependencies still follow their own linking rules.

Rebuild statically linked applications when adopting an SDK fix. Updating the shared-library package alone does not replace code in those programs.

Debugging static builds #

The packaged static archives retain linker symbols but omit DWARF debugging information. Each library's debug package describes its shared object; it does not supply the missing SDK internals for a statically linked program.

To debug statically linked SDK code, use the unstripped archive the SDK's build gives, or rebuild the matching source with its recorded compiler and dependency inputs. Keep those inputs with the binary so that debugger source paths and layouts match the executable.

Compiling a First Program

Peios / Developing for Peios / SDK Basics

Parse a security descriptor, read its owner, and print the owner's security identifier (SID). This example runs entirely in userspace and does not open tokens or change system security.

Before you start #

Prepare these inputs:

  • A C compiler and pkg-config.
  • The libpeios development package and its matching runtime library.
  • A writable directory for the source and executable.

Creating the program #

Save this complete program as first.c:

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <peios/security.h>

int main(void)
{
    /* An SDDL descriptor: owner and group are Administrators (BA), with a
       DACL granting them full access (FA). */
    const char *sddl = "O:BAG:BAD:(A;;FA;;;BA)";

    /* 1. Parse the SDDL text into self-relative SD wire bytes.
          First call probes for the size (cap == 0), then retrieve. */
    ssize_t need = peios_sddl_parse_sd(NULL, 0, sddl);
    if (need < 0) {
        fprintf(stderr, "parse probe failed: %s\n", strerror(errno));
        return 1;
    }

    unsigned char *sd = malloc((size_t)need);
    if (!sd)
        return 1;

    ssize_t sd_len = peios_sddl_parse_sd(sd, (size_t)need, sddl);
    if (sd_len < 0) {
        fprintf(stderr, "parse failed: %s\n", strerror(errno));
        free(sd);
        return 1;
    }
    printf("security descriptor: %zd bytes\n", sd_len);

    /* 2. Parse the SD into a zero-copy view. The view borrows `sd` — it
          must stay alive and unmodified until the final read. */
    peios_sd_view view;
    if (peios_sd_parse(sd, (size_t)sd_len, &view) != 0) {
        fprintf(stderr, "sd parse failed: %s\n", strerror(errno));
        free(sd);
        return 1;
    }

    /* 3. Pull out the owner SID. On success `owner` points INTO `sd`. */
    const void *owner;
    size_t owner_len;
    if (peios_sd_view_owner(&view, &owner, &owner_len) != 0) {
        fprintf(stderr, "owner lookup failed: %s\n", strerror(errno));
        free(sd);
        return 1;
    }

    /* 4. Format the owner SID as its "S-1-…" string. The byte form of a
          SID is bounded, but its string form is variable, so we probe.
          A string length excludes the NUL, so allocate len + 1. */
    ssize_t slen = peios_sid_format(owner, owner_len, NULL, 0);
    if (slen < 0) {
        fprintf(stderr, "sid format probe failed: %s\n", strerror(errno));
        free(sd);
        return 1;
    }

    char *str = malloc((size_t)slen + 1);
    if (!str) {
        free(sd);
        return 1;
    }
    if (peios_sid_format(owner, owner_len, str, (size_t)slen + 1) < 0) {
        fprintf(stderr, "sid format failed: %s\n", strerror(errno));
        free(str);
        free(sd);
        return 1;
    }

    printf("owner: %s\n", str);

    /* 5. Free `sd` — every pointer the view returned pointed into
          it, so it had to outlive the last read. */
    free(str);
    free(sd);
    return 0;
}

The Security Descriptor Definition Language (SDDL) string sets the owner and group to Administrators. Its discretionary access control list (DACL) grants that group full file access. Parsing this string does not grant any access to the process running the example.

Building and running #

  1. Compile the source with the package's compiler and linker options:

    cc first.c $(pkg-config --cflags --libs peios) -o first
    
  2. Run the executable:

    ./first
    

Checking the result #

The program prints:

security descriptor: 84 bytes
owner: S-1-5-32-544

The owner SID identifies Administrators. The byte count describes the encoded descriptor produced by this example, including its owner, group, and access control list.

Understanding ownership #

The program probes the output size before allocating each variable-sized buffer. The string allocation adds one byte for the terminating NUL.

The parsed view and owner pointer borrow the descriptor allocation. The program frees that allocation after formatting the owner, so every borrowed pointer remains valid throughout its use.

Read library conventions for the result and ownership rules used by the other SDK functions.

Using the SDK from Rust

Peios / Developing for Peios / SDK Basics

Use the peios crate to access Peios through Rust handles and Result values. The peios-sys crate exposes the underlying unsafe C functions. Both use the public C application binary interface (ABI).

Before you start #

  • Install Rust and Cargo.
  • Install matching libpeios headers and libraries, version 0.5.12 or later.
  • Install pkg-config and libclang for binding generation.
  • Place the peios-rs checkout beside your application for this example.
  • Run token operations on a Peios kernel.

Add the dependency #

  1. Add a local dependency to your application's Cargo.toml:

    [dependencies]
    peios = { path = "../peios-rs/peios" }
    
  2. Create src/main.rs:

    use peios::token::{Token, TokenAccess};
    
    fn main() -> peios::Result<()> {
        let token = Token::open_self(false, TokenAccess::QUERY)?;
        let identity = token.user()?;
        println!("identity: {identity}");
        Ok(())
    }
    
  3. Run cargo run. The token handle closes when it leaves scope.

Check the result #

The program prints the caller's security identifier (SID). A native-call error on another kernel does not indicate a successful Peios access check.

Generate the API reference with cargo doc -p peios --open from the SDK checkout. The repository's docs/building.md covers SDK discovery and host tests.

Linking and types #

Use dynamic linking for ordinary Rust applications. The C static archive contains its own Rust runtime, which can conflict with a Rust executable's runtime. The static feature only selects that archive; it does not remove those conflicts.

The optional uapi feature re-exports kernel types through peios_sys. Those types come from the recorded kernel snapshot. Import them through that re-export when sharing values with these bindings: a separately compiled copy of the same structure has a different Rust type identity.

Names without regard to case #

peios::casefold compares names as the registry compares them: Unicode Simple Case Folding, pinned to Unicode 16.0, with no normalisation. Windows matches names the same way, so use it wherever a program must match names as Windows clients expect, as a file server does. fold folds one character; eq and cmp compare whole names. Code that must build without libpeios, such as a protocol engine tested on another system, can depend on the peios-casefold crate itself, which peios::casefold re-exports.

Identity and event ownership #

A scoped impersonation guard belongs to the thread that creates it. Rust rejects moving or sharing the guard across threads. Keep identity-dependent work on that thread, and call revert when you need to check restoration. Dropping the guard attempts restoration but cannot return an error. Impersonations do not nest: restoration clears the impersonation rather than restoring an earlier impersonated identity.

Events own their type names and payloads. You can retain them after the next read or after closing the reader. A low-level read returns EAGAIN if its slot is empty, overwritten, or changes generation during copying. After a generation change, attach and map the ring again.

Event emission checks names, payload lengths, and batch counts before converting them to the C ABI's fixed-width fields. Values that do not fit return EINVAL. Socket receive calls also reject an unrepresentable handle capacity before allocating its buffer or consuming a message.

Access checks and request identity #

Audit Contexts in Rust explains object descriptions and denial results. Token Messages in Rust covers received-handle ownership, truncation, and explicit peer-identity fallback.

Using the SDK from Go

Peios / Developing for Peios / SDK Basics

Use peios-go to read Peios security formats and call native Peios operations. The module uses Go directly; applications do not need a C compiler or an installed C SDK library at runtime.

Before you start #

  • Install Go 1.26 or later.
  • Place the SDK checkout beside your application for this local example.
  • Run native operations on a Peios kernel. Portable format parsers also work on other systems.

Add the dependency #

  1. Add these entries to your application's go.mod:

    require github.com/peios/peios-go v0.0.0
    replace github.com/peios/peios-go => ../peios-go
    

    The version is a local placeholder. Before publishing your application, use a published commit or release and remove the local replacement.

  2. Create main.go:

    package main
    
    import (
        "fmt"
    
        "github.com/peios/peios-go/security"
    )
    
    func main() {
        descriptor, err := security.ParseSDDL("O:SYG:BAD:(A;;FA;;;BA)")
        if err != nil {
            panic(err)
        }
        wire, err := descriptor.MarshalBinary()
        if err != nil {
            panic(err)
        }
        fmt.Printf("descriptor size: %d bytes\n", len(wire))
    }
    
  3. Run go run . from your application directory.

Check the result #

The program prints the descriptor size. This example parses Security Descriptor Definition Language (SDDL) without changing a system object. Parsing validates structure; the kernel separately checks your authority when you apply a descriptor.

Use go doc github.com/peios/peios-go/security for the package reference. The repository's docs/building.md describes SDK development and tests.

Audited access checks #

Audit Contexts in Go uses the maintained access package and explains how to handle denial separately from an unsuccessful check.

Audit Contexts in Rust

Peios / Developing for Peios / SDK Basics

An audit context names the object behind an access check. The Rust AuditContext type owns the encoded description and lends it to an AccessCheck. The kernel can then include that description in an audit record when the applicable audit policy calls for one.

The description is the daemon's claim, not independently observed identity. It does not grant access or replace the security descriptor. See The Audit Context for the shared format and Access Decisions for the rules governing audited objects.

Build and use a context #

This helper checks a service object using a supplied caller token, descriptor, access mask, and object-specific generic mapping:

use std::os::fd::BorrowedFd;

use peios::access::{AccessCheck, AccessDecision, AuditContext};
use peios::security::{AccessMask, GenericMapping, SecurityDescriptor};

fn check_service(
    caller: BorrowedFd<'_>,
    descriptor: &SecurityDescriptor,
    desired: AccessMask,
    mapping: GenericMapping,
) -> peios::Result<AccessDecision> {
    let context = AuditContext::new("service", &[("name", "jellyfin".into())])?;
    AccessCheck::new(descriptor, desired, mapping)
        .token(caller)
        .audit_context(&context)
        .check()
}

The example names an illustrative service. Replace its name with the actual object being checked, and define asserted object fields in the owning event catalog fragment. Do not label an arbitrary request as another component's object merely because its name is convenient.

A completed check returns an AccessDecision. Inspect allowed: denial is an ordinary decision, not a Rust Err. An error means the check itself could not complete. The check evaluates access; your daemon still enforces the result before performing the operation.

Values and ownership #

Field values convert from &str, u64, u32, i64, i32, bool, &[u8], and &SidRef. A security identifier (SID) uses its binary representation. Use the declared field type rather than converting every value to a string. Leave absent fields out instead of supplying nil or a placeholder value.

The constructor copies the encoding into owned storage. Temporary field slices need not outlive the returned context. AccessCheck borrows that context for the check; as_bytes lends the encoded bytes without transferring ownership.

Invalid kind or key names, repeated keys, and oversized encodings are rejected with EINVAL. Names are single kebab-case segments, and the encoded context is limited to 4096 bytes. Other construction failures remain errors to handle.

Accept an existing encoding #

AuditContext::from_bytes takes a Vec<u8>, validates the encoded context, and adopts it on success. It applies the shared validator's structural rules, which are broader than the scalar-only constructor. Passing validation does not prove that fields are cataloged, truthful, or appropriate for this object.

Keep the caller token and descriptor associated with the same request while constructing and checking the context. Neither a successfully encoded context nor a successful audit write is an authorization decision by itself.

Audit Contexts in Go

Peios / Developing for Peios / SDK Basics

The github.com/peios/peios-go/access package provides portable audit-context encoding and native access checks. Attach the encoded object description to access.Request so the kernel can identify the object in an audit record. The context does not grant authority or replace the security descriptor.

The Audit Context defines the common encoding. Access Decisions explains when a daemon supplies it and how its claims are marked.

Encode and check #

This helper checks an illustrative service using an existing token handle and security descriptor. Native checks require a Peios kernel on Linux/amd64.

package example

import (
	"syscall"

	"github.com/peios/peios-go/access"
	"github.com/peios/peios-go/security"
)

func CheckService(
	caller syscall.Conn,
	descriptor []byte,
	desired security.AccessMask,
	mapping security.GenericMapping,
) (access.Result, error) {
	context, err := access.AuditContext("service", []access.Field{
		{Name: "name", Value: "jellyfin"},
	})
	if err != nil {
		return access.Result{}, err
	}
	return access.Check(access.Request{
		Token:        caller,
		Descriptor:   descriptor,
		Desired:      desired,
		Mapping:      mapping,
		AuditContext: context,
	})
}

Use the actual service name and its object-specific mapping. Define the asserted fields in the owning event catalog fragment. A nil Token selects the calling thread's effective token; it does not mean an anonymous client. Pass the intended caller explicitly when checking another principal's access.

access.Check returns syscall.EACCES for denial, retaining the granted subset and audit outputs in its result. Other errors mean the check could not complete. This differs from the Rust wrapper, which represents denial in AccessDecision.allowed. Do not ignore a Go error because a result was returned.

CheckList returns per-node decisions for an object tree. Inspect each node's Status; a successful call does not mean every node grants the requested access.

Encode values deliberately #

Each access.Field pairs a name with a value. The encoder accepts strings, booleans, byte slices, and signed or unsigned integer types. Pass a SID's Bytes() result for a binary security identifier, not the SID object or its text form. Floating-point values, nested objects, and nil are not constructor field values.

Names are single kebab-case segments, repeated keys are rejected, and the encoded context is limited to 4096 bytes. An empty field list emits only the object kind. The encoder returns access.ErrAuditContext for invalid context structure and can also return an encoding error.

The returned byte slice owns its encoding. Keep its contents unchanged until the check completes. Do not reuse it concurrently as a mutable work buffer.

Validate an existing map #

Call access.ValidateAuditContext when another encoder built the bytes. Its structural validation is broader than the scalar-field constructor; it is not proof that the values match the catalog or describe the real object.

Both native check variants validate a non-nil Request.AuditContext before calling the kernel. Nil omits the context; a non-nil empty slice is invalid. For a daemon-owned object that requires an audit context, omission is not a substitute for handling an encoding error.

The historical libp-go/sd constructors and CheckRequest examples do not apply to this API. Use access.AuditContext, access.Field, and access.Request from the maintained module.

Token Messages in Rust

Peios / Developing for Peios / SDK Basics

The Rust socket helpers send and receive per-message identity with file descriptors. ReceivedMessage owns each received descriptor, including its optional token, so rejecting a message can release those resources by dropping it. The request bytes remain in the caller's receive buffer.

Use Per-Message Identity for the shared interface contract. A conveyed token identifies the authority the sender could convey; it does not authorize every requested operation.

Send one identity with a request #

For a connected socket and an existing user token, the sending call is:

use std::os::fd::AsFd;
use peios::socket;

let sent = socket::send_message(
    jobs.as_fd(), request, Some(user_token.as_fd()), &[], 0,
)?;

The caller retains its descriptors. Check the returned byte count according to the transport's framing rules. On a stream, a partial write is not a complete request. Do not blindly replay the whole request and its ancillary data after a partial write.

Receive and reject incomplete requests #

This helper requires an attached identity and rejects truncation. The application chooses an 8-descriptor bound; choose a bound appropriate to your own protocol and validate the number and purpose of descriptors after receipt.

use std::error::Error;
use std::os::fd::{BorrowedFd, OwnedFd};

use peios::socket;
use peios::token::{ImpersonationLevel, Token};

fn receive_identity(
    connection: BorrowedFd<'_>,
    buffer: &mut [u8],
) -> Result<(usize, Token, Vec<OwnedFd>), Box<dyn Error>> {
    let message = socket::recv_message(connection, buffer, 8, 0)?;
    if message.truncated || message.control_truncated {
        return Err("incomplete request or ancillary data".into());
    }
    if message.len == 0 {
        return Err("empty request or closed stream".into());
    }
    let identity = match message.token {
        Some(token) => token,
        None => return Err("this protocol requires an attached identity".into()),
    };
    if identity.impersonation_level()? < ImpersonationLevel::Impersonation {
        return Err("identity cannot be used to act for this caller".into());
    }
    Ok((message.len, identity, message.fds))
}

This is an identity/ownership helper, not a stream message decoder. A stream read can contain only part of the application's frame. Reassemble and validate the frame before interpreting its contents. Do not use zero-length data as an identity-only request with this helper.

Returning an error drops descriptors already received. Moving the token or OwnedFd values out transfers their ownership to the caller; those handles close when their new owners drop them. Do not close their raw descriptor numbers separately. Received handles are close-on-exec.

The example requires at least the local impersonation level because its server intends to act for the caller. An identification-only protocol needs its own explicit contract. Checking the level does not enter impersonation or perform an access check.

Choose fallback identity explicitly #

A protocol can instead specify that an absent attached token means the connected peer's primary token. In that case, obtain the peer process handle from the kernel and open the token through it:

use std::os::fd::AsFd;
use peios::socket;
use peios::token::{Token, TokenAccess};

let peer = socket::peer_pidfd(connection.as_fd())?;
let identity = Token::open_process(
    peer.as_fd(), TokenAccess::QUERY | TokenAccess::DUPLICATE,
)?;

This is the connected peer's primary identity, not necessarily the identity of a client that peer represents. Do not substitute a process number named in the payload. Do not use fallback after truncation, an invalid attached token, or a failed token query; those are failures rather than absence.

Apply the protocol's level and authorization checks to a fallback token too. Opening a primary token does not convert it into an impersonation token or enter impersonation. If acting under it is required, use the token duplication and scoped impersonation interfaces described by the SDK.

A scoped impersonation guard stays on its creating thread. It does not carry identity safely across arbitrary async task migration. Explicitly revert when you need to handle restoration failure; dropping the guard cannot report it.

Access Control Overview

Peios / Developing for Peios / Access Control

KACS — the Kernel Access Control Subsystem — is the heart of Peios's security model, and it is the part of the SDK you are most likely to reach for. This section is a tour: it explains how the pieces fit together and points you at the right guide (and the right reference page) for each task. If you have not yet read the library conventions, read those first — everything here assumes the error and buffer rules they describe.

The four nouns #

Almost everything in KACS is built from four things:

NounWhat it isSDK home
SIDThe unique binary name of a principal — a user, group, machine, or well-known system actor.security.h
Security descriptor (SD)What protects an object: its owner, its group, and the ACLs that grant or deny access. Built from ACEs, each naming a SID and an access mask.security.h
TokenThe runtime object that carries an identity — a user SID, groups, privileges, an integrity level, claims. Every access decision is made against a token. A token is a file descriptor.token.h
Access checkThe act of deciding whether a token can perform a desired access on an object, given the object's SD.access.h

The relationship is simple to state: an access check asks whether a token (the subject) is granted some access to an object protected by a security descriptor, and both the token and the SD are expressed in terms of SIDs.

The shape of a decision #

When you need to make an authorization decision in your own code, the pattern is almost always the same three steps:

  1. Get the subject's token. Usually the caller's — often through peios_token_open_peer on a socket, so you learn who connected — or your own effective token (token_fd = -1).
  2. Get the object's security descriptor. You either hold it already, read it off a file with peios_file_get_sd, or build one with a peios_sd_builder.
  3. Run the check. peios_access_check tells you whether the desired rights are granted, and exactly which subset was granted.

The checking access guide walks that end to end.

Advisory versus enforced #

There is one distinction worth internalising early. The SDK's access check is advisory: it computes what the answer would be. It does not enforce anything — enforcement of a real operation (opening a file, adjusting a token) happens inside the kernel against the subject's own process security block.

So you use peios_access_check when your code is the resource manager: you own some object — a record in your database, a slot in your service — that isn't a kernel object, and you want to make the grant/deny decision using Peios identities and the same rules the kernel would apply. For actual kernel objects (files, tokens, registry keys), you don't pre-check and then act; you act, and the kernel enforces, returning EACCES if denied.

Identity is not always your identity #

A recurring theme in KACS is acting as someone other than yourself:

  • Impersonation lets a service temporarily adopt a caller's identity so its access checks run as them — the way a server does work "on behalf of" a client without running as root and hand-rolling permission logic. See working with tokens.
  • Restricted tokens let you drop power — derive a strictly less-privileged token to hand to less-trusted code.
  • Integrity levels and confinement bound what a token can touch regardless of its SIDs.

These are what make KACS more than POSIX uid/gid, and the token module is where you reach for them.

Where to go in this section #

  • Working with tokens — who am I, who is calling me, and how to act as someone else.
  • Checking access — building a security descriptor and making a decision end to end.
  • Securing files — the native open and reading/writing file security descriptors.
  • Hardening a process — turning on process mitigations.

For the exhaustive per-function detail behind any of these, the reference section documents every symbol.

Working with Tokens

Peios / Developing for Peios / Access Control

A token is the runtime carrier of an identity, and it is a file descriptor. This guide covers the everyday token tasks; token.h is the exhaustive reference for every call and field.

Choosing a token #

To inspect your own identity, open your effective token and query it:

int tok = peios_token_open_self(0, KACS_TOKEN_QUERY);
if (tok < 0) { /* errno */ }

unsigned char sid[PEIOS_SID_MAX_BYTES];
ssize_t n = peios_token_user(tok, sid, sizeof sid);   /* the user SID */

uint32_t il;
peios_token_integrity(tok, &il);                      /* integrity level RID */

struct peios_privilege_set privs;
peios_token_privileges(tok, &privs);                  /* held/enabled privileges */

close(tok);

peios_token_open_self gives you the effective token — if your thread is impersonating, that's the impersonated identity. Pass KACS_TOKEN_OPEN_REAL in the flags to get your process's real primary token regardless. The access argument is the handle rights you want; KACS_TOKEN_QUERY is enough to read.

Group SIDs and other list-valued classes come back as buffers you parse with the security.h views: read CLASS_GROUPS with peios_token_query, then peios_sid_array_parse it.

Who is calling me #

The most useful token trick in a service is learning the identity of whoever connected to your socket. When a client connects over a Unix stream or seqpacket socket, KACS captures their token at connect() time, and you open it from the accepted connection:

int conn = accept(listener, NULL, NULL);
int caller = peios_token_open_peer(conn);   /* QUERY | IMPERSONATE rights */
if (caller < 0) { /* errno */ }

/* Now query the caller's identity, or impersonate them (below). */

This is local authentication with no passwords and no handshake — the kernel vouches for who is on the other end. The handle comes with fixed QUERY | IMPERSONATE | DUPLICATE rights — enough to inspect the caller, act as them, and (for a process launched on their behalf) turn the identity into a primary token, but never to adjust it.

It works in the other direction too: right after connect(), peios_token_open_peer(sock) on the client's socket returns the identity of whoever is listening (at Identification level — enough to check, not to act as), so a client can verify it reached the genuine service and not something else that bound the path.

Acting as the caller #

Once you hold a caller's (impersonation) token, you can impersonate them: adopt their identity on your current thread so every subsequent access check runs as them, not as your service. This is how you do work on a client's behalf without running privileged and re-implementing their permissions.

if (peios_token_impersonate(caller) != 0) { /* errno */ }

/* ... do the work here: file opens, access checks, etc. all run as the caller ... */

peios_token_revert();   /* back to your own identity */
close(caller);

Always pair peios_token_impersonate with peios_token_revert, ideally in the cleanup path, so a failure partway through can't leave your thread wearing someone else's identity. peios_token_revert is a safe no-op if you weren't impersonating.

The full flow for a request handler is: accept → peios_token_open_peer → peios_token_impersonate → serve the request → peios_token_revert → close. When the handler runs start to finish on one thread and has no other use for the token, peios_token_impersonate_peer(conn) collapses the open, impersonate and close into one call.

A client decides how far its identity travels: peios_socket_set_impersonation_level(sock, KACS_IMLEVEL_IDENTIFICATION) lets the server learn who it is without being able to act as it. And a client that writes on behalf of many identities over one connection — a service impersonating its callers through a connection pool — turns on peios_socket_set_pass_token(sock, true), after which every send carries whoever is impersonating at that moment and the server's peios_token_open_peer tracks it request by request.

Handing an identity to a manager #

Impersonation acts as someone on your thread. The other shape is handing an identity to another process so it can act — the pattern behind the Peinit jobs socket (PSPU §7): a submitter such as backupd holds a token for the user whose data it is backing up, and wants Peinit to run the backup job as that user, not as backupd. Nothing is impersonated; the token itself is attached to the request, and the kernel vouches that the sender could have acted as it.

int jobs = socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0);
connect(jobs, ...);                                   /* who may submit is who may connect */

const char *req = "{\"command\":\"submit\",\"image_path\":\"/usr/bin/backup\"}";
if (peios_socket_send_message(jobs, req, strlen(req), user_token, NULL, 0, 0) < 0) {
    /* EACCES: user_token lacks TOKEN_IMPERSONATE; EPERM: the attach would lower its level */
}

Three things make this safe, and none of them is the manager's to get wrong:

  • The kernel gates the attach like an impersonation. You need TOKEN_IMPERSONATE on the handle, and the token arrives at the sending socket's impersonation level — so a token the sender could only identify, never act as, cannot be smuggled through. Peinit refuses anything below Impersonation. For a job that must reach remote systems as the user, set the socket to Delegation first: peios_socket_set_impersonation_level(jobs, KACS_IMLEVEL_DELEGATION) — and the attach then only succeeds if the token itself is at Delegation, since the level only ratchets down.
  • The receiver owns what it is handed. peios_socket_recv_message gives the manager a token handle with QUERY | IMPERSONATE | DUPLICATE — enough to inspect the identity, check its level with peios_token_impersonation_level, and duplicate it into a primary token for the new process, but never to adjust it.
  • No token means the sender's own. A request that attaches nothing is run as the connecting process's primary token: the manager opens it through peios_socket_peer_pidfd and peios_token_open_process — the kernel's handle on the peer, never a PID the peer named — which is fork-like and needs no privilege on the submitter's part.

Descriptors travel the same way: pass a socket for the job to serve on, or a pipe to receive its output, as SCM_RIGHTS on the same message. The full protocol — what the manager does with them and how the job is managed afterward — is PSPU §7; the calls are in the reference.

Dropping power #

To run less-trusted code with less authority than you hold, derive a restricted token and hand it over. peios_token_restrict can delete privileges, demote groups to deny-only, and add restricting SIDs:

struct peios_token_restrict spec = {
    .privs_to_delete = KACS_SE_DEBUG_PRIVILEGE | KACS_SE_IMPERSONATE_PRIVILEGE,
    .flags           = KACS_TOKEN_RESTRICT_WRITE_RESTRICTED,
};
int weak = peios_token_restrict(my_primary, &spec);

The result is a strictly less-powerful token. Combined with integrity levels and confinement (both set when minting a token), this is the basis of sandboxing on Peios.

Minting tokens #

Creating a token from scratch requires SeCreateTokenPrivilege and is the province of authentication authorities, not ordinary programs. When you do need it, the token-spec builder is the ergonomic path — typed setters for the user SID, groups, privileges, integrity, claims, and the rest, then peios_token_builder_create. Mind the index convention for owner/primary-group references, and don't add the logon SID yourself — the kernel injects it.

Next #

  • Checking access — use a token to make an authorization decision.
  • token.h reference — every token call in full.
  • Impersonation — the operator-side model and its two gates.

Keep request identity bound to the work #

Capture is not a promise of usable impersonation. Query the effective granted level after admission: the primary-token identity gate and integrity ceiling can reduce it to Identification even when installation succeeds. A restricted server cannot escape through an unrestricted same-user client. A privilege that satisfies the identity gate does not bypass the integrity ceiling. The kernel admission reference defines the exact result.

Scope impersonation around the complete client operation and revert on every exit path, including errors. Reverting an inner scope does not restore an outer impersonation stack; it returns to the primary identity. Keep service maintenance outside that client scope. Thread-pool reuse and asynchronous migration need explicit handling because impersonation is thread-local.

A pooled connection can carry different senders over time. Connection-level capture alone cannot identify every forwarded request. Enable per-message identity deliberately, and bind the token returned with a receive to that message when consumers can run concurrently. A later peer-token query can observe a later received identity. The transport reference defines stream boundaries, seqpacket behavior, datagram attachment, and unsupported transport cases; ordinary pipes are not peer-token sockets.

A client should verify the server identity returned by peer capture before sending sensitive requests. Possession of a familiar socket path is not a substitute. Delegation level permits further conveyance where an implemented network authentication mechanism supports it; the level alone does not supply remote credentials or implement that mechanism.

SDK token opens use close-on-exec descriptors by default. Distinguish that handle flag from the thread's impersonation state, which exec reverts. Intentionally passing a token handle across exec does not install it as the new program's effective identity.

Checking Access

Peios / Developing for Peios / Access Control

This guide walks a complete access decision: you have an object to protect, a caller to check, and you want KACS to tell you what they're allowed. The exhaustive detail lives in access.h and security.h; here you put them together.

When to use this #

Reach for peios_access_check when your program is the resource manager — you own something that isn't a kernel object (a document, an API route, a record) and you want to gate it with Peios identities and rules. For actual kernel objects, don't pre-check; perform the operation and let the kernel enforce.

Remember the check is advisory: it computes the answer, you enforce it.

When an identity authority supplies facts without an OS token, use the separate supplied-identity check. It preserves unknown versus known-empty groups and filtered versus complete claims. It never adopts the service's own token or creates a user session. Only an explicit granted decision permits admission; missing context requires more facts or refusal. Its initial backend runs inside libpeios and does not need a kernel rebuild. The token-based instructions below remain unchanged.

Step 1 — describe what protects the object #

An object is protected by a security descriptor. If you don't already have one, build it. Say the resource should be readable and writable by its owner and read-only for a "viewers" group:

/* An ACL: allow OWNER full, allow VIEWERS read. */
peios_acl_builder *acl = peios_acl_builder_new();
peios_acl_builder_allow(acl, owner_sid, owner_len, KACS_ACCESS_ALL, 0);
peios_acl_builder_allow(acl, viewers_sid, viewers_len, KACS_ACCESS_READ, 0);

size_t acl_len;
const void *acl_bytes = peios_acl_builder_bytes(acl, &acl_len);

/* Wrap it in a security descriptor with an owner. */
peios_sd_builder *sd = peios_sd_builder_new();
peios_sd_builder_owner(sd, owner_sid, owner_len);
peios_sd_builder_dacl(sd, acl_bytes, acl_len);

size_t sd_len;
const void *sd_bytes = peios_sd_builder_bytes(sd, &sd_len);

(You can also write the descriptor as SDDL text and parse it — often easier when the policy is fixed.)

Step 2 — identify the subject #

The subject is a token. Most often it's the caller you opened from a socket, or your own effective token. In the request you pass either a token fd or -1 for your own effective token.

Step 3 — run the check #

Fill in a request and call. desired is what you're testing; mapping folds any generic rights to the object class's specific bits (use the class's published mapping — here you'll treat the object like a file):

struct peios_access_request req = {
    .token_fd = caller_fd,               /* or -1 for my own token */
    .sd       = sd_bytes, .sd_len = sd_len,
    .desired  = KACS_ACCESS_READ | KACS_ACCESS_WRITE,
    .mapping  = peios_file_generic_mapping,
};

uint32_t granted = 0;
int rc = peios_access_check(&req, &granted, NULL);

Step 4 — interpret the result #

if (rc == 0) {
    /* Every desired right was granted. */
} else if (errno == EACCES) {
    /* Denied. `granted` still holds what WAS allowed — for example maybe READ
       succeeded but WRITE did not. Decide per-right from `granted`. */
    bool may_read  = granted & KACS_ACCESS_READ;
    bool may_write = granted & KACS_ACCESS_WRITE;
} else {
    /* A real error: bad token fd, malformed SD, etc. */
    perror("access_check");
}

The key idea: a denial is not an error to log and bail on — it's the expected "no". And because granted is filled even on denial, you can ask for a broad set of rights in one call and read back exactly which subset the subject has, rather than probing right by right. Clean up the builders (peios_acl_builder_free, peios_sd_builder_free) and the token fd when done.

Intent is not an authorization ticket #

For a resource managed by the application, set backup or restore intent only when that resource operation actually has the corresponding purpose. The subject must still hold the enabled privilege, and the complete pipeline can narrow its contribution. The request's intent does not change the token.

A successful advisory check does not grant rights to a later filesystem open, write, or descriptor update. Those operations enforce their own contracts. Do not implement backup as "pre-check with backup intent, then assume any ordinary open is authorized." Use the kernel object's supported operation and retain its actual result. Likewise, a prior WRITE_OWNER result does not eliminate the descriptor-update rules about the new owner SID.

For MAXIMUM_ALLOWED, inspect the returned mask rather than treating success as a grant of every possible bit. Result-list checks apply object-type-tree semantics; they are not a collection of unrelated scalar checks. A caller that cannot reproduce local claims, PIP, mapping, or audit context should record that gap instead of presenting a rehearsal as the original decision.

Per-property checks #

If your object has properties or property-sets with their own object ACEs, evaluate the whole tree in one call with peios_access_check_list: supply an object-type tree and get one result per node, so you learn (for instance) that a caller can read most of an object but not one protected field — without a separate check per field.

Auditing a decision #

Pass a non-NULL peios_access_audit to learn what a SYSTEM_AUDIT ACE match would log, and whether a staged central access policy would decide differently — the signal you watch when rolling out a policy change.

If your daemon guards objects of its own, name the object in the request's audit context, so the kernel's audit record of the decision says what was checked:

struct peios_audit_field name = {
    .key = "name", .value_type = PEIOS_AUDIT_STR,
    .bytes = "jellyfin", .len = strlen("jellyfin"),
};
uint8_t ctx[128];
ssize_t n = peios_audit_context_encode("service", &name, 1, ctx, sizeof ctx);
req.audit_context = ctx;
req.audit_context_len = (size_t)n;   /* check n >= 0 first */

Do not write an event of your own recording the grant or the refusal. The kernel's record is the audit record, and a SACL on the object decides whether it is written (PGSS §6.7).

Next #

  • access.h reference — every field of the request and the audit outputs.
  • Access decisions — the operator-side account of how KACS reaches a verdict (and how to debug a surprising denial).

Securing Files

Peios / Developing for Peios / Access Control

Use libpeios to open a file with explicit access or to read and change its security descriptor. Select the descriptor components needed by the task so that an update preserves unrelated security settings.

Before you start #

Prepare the required authority and inputs:

  • A Peios kernel with the Kernel Access Control Subsystem (KACS).
  • A process token with the rights needed for the requested operation.
  • The libpeios headers and matching library.
  • A validated security descriptor for operations that supply one.

Opening a file #

A native file open requests a specific access mask. The resulting handle carries the access granted at open. Choose that mask deliberately before passing the handle to another process.

  1. Initialize struct peios_open_params to zero.
  2. Set desired_access to the file rights the caller needs.
  3. Choose the disposition that matches the operation. Use KACS_DISPOSITION_CREATE when an existing path must be an error, or KACS_DISPOSITION_OPEN when the file must already exist.
  4. For creation, supply the creator descriptor when required by the application's security policy. For an existing file, leave sd as NULL and sd_len as zero.
  5. Call peios_file_open and check its return value before using the descriptor or the status output.
  6. Close the returned descriptor when its ownership ends.

If a create-only operation reports EEXIST, decide whether the application can accept the existing object before opening it separately. A preceding path-existence check cannot make creation and opening atomic.

Supply a new file's descriptor when you create it, rather than creating the file and then setting its descriptor. Between those two calls the file exists with whatever descriptor it inherited. The handle a creating open returns has the access it asked for, even where the new descriptor would not grant it to the creator, so you can create a file only others can read and still write it through that handle.

To keep other processes from writing or deleting the file while you use it, set KACS_OPEN_SHARE_ACCESS in flags and name what you allow in share_access.

See opening a file for the parameter contract and the kernel's supported create options.

Reading a security descriptor #

The KACS_SECINFO_* selection identifies which components to read. A request for the owner and discretionary access control list (DACL) does not also request the system access control list (SACL).

  1. Choose peios_fd_get_sd when the application already owns a suitable handle. Otherwise, use peios_file_get_sd with the intended path policy.
  2. Probe the required length with a zero-capacity buffer and check for failure before converting the result to size_t.
  3. Allocate the buffer and check that allocation succeeded.
  4. Repeat the query. If the descriptor grows and the call reports ERANGE, probe again or stop according to the application's retry policy.
  5. Parse only the bytes returned by a successful query.
  6. Keep the buffer unchanged while using parsed views, then release it.

A size probe does not reserve the descriptor or prevent another process from changing it. Do not use the probe's length as though it were the length returned by the second call.

Changing selected components #

Use peios_sd_builder to construct the descriptor that carries the replacement components:

  1. Create a builder and check that it is not NULL.
  2. Add the replacement components, such as the DACL.
  3. Obtain the encoded bytes and check for a retained builder error.
  4. Call peios_fd_set_sd or peios_file_set_sd with the corresponding KACS_SECINFO_* selection.
  5. Check the result before reporting success, then free the builder.

Selecting only KACS_SECINFO_DACL preserves the owner, group, and SACL. Changing an owner or integrity label has additional permission checks; possessing a syntactically valid descriptor does not satisfy those checks.

Checking the result #

Read the selected components again through the intended object handle and compare them with the requested values. Distinguish a failed update from a failed verification query, and preserve the relevant errno before cleanup.

The file-security reference describes each library entry point. The kernel file-security guide owns the kernel's access checks and descriptor merge rules.

Hardening a Process

Peios / Developing for Peios / Access Control

Peios lets a process opt into hardening — exploit mitigations enforced by the kernel on that process's security block. The SDK exposes this through a single call, peios_process_set_mitigations. This short guide covers using it well; the full flag set and semantics are in process.h and the operator docs.

Harden yourself at startup #

The common case is a program hardening itself early in main, before it processes any untrusted input:

#include <stdio.h>

#include <peios/process.h>

int main(void)
{
    /* Enforce W^X and speculation mitigation lock; abort on failure. */
    if (peios_process_set_mitigations(-1, KACS_MIT_WXP | KACS_MIT_SML) != 0) {
        perror("set_mitigations");
        return 1;   /* refuse to run unhardened */
    }
    /* ... the rest of the program runs with those protections on ... */
}

pidfd == -1 targets the calling process. mitigations is a mask of KACS_MIT_* bits (from <pkm/psb.h>); combine the ones you want and set them together.

Three things to know #

It's one-way. Mitigation bits can only be set, never cleared — once on, they stay on for the life of the process. That's the point: a mitigation you could turn off is one an attacker could turn off. Treat each call as a permanent commitment.

It's all-or-nothing, and fails closed. If any requested protection can't actually be activated, the call changes nothing and returns -1. You never end up believing a mitigation is on when it isn't. So request the set you require together and check the result once — success means the whole set is active. (Bits from earlier successful calls stay on regardless.)

Targeting another process is privileged. To harden a process other than your own, you need PROCESS_SET_INFORMATION on it and PIP dominance over it — you can't reach into a process you don't already dominate. For self-hardening (-1), neither is needed.

Choosing what to enable #

The bit catalog and what each mitigation defends against is documented operator-side under process mitigations (and in the Peios Kernel TRM §3.3, the Process Security Block). A couple of notes for the SDK caller:

  • KACS_MIT_ALL is the mask of all valid bits — useful for validating input, not usually what you'd blanket-enable without thought.
  • KACS_MIT_CFI is a legacy alias that expands to KACS_MIT_CFIF | KACS_MIT_CFIB.

Enable the specific protections your program can tolerate, verify the call succeeded, and prefer to do it before you touch untrusted data.

Activation and lifecycle #

A valid mask can still fail because a platform cannot activate the protection or existing mappings violate it. Late WXP, TLP, or LSV requests validate existing state; generating incompatible mappings first does not exempt them. TLP and LSV inspect file-backed executable mappings, while WXP also constrains anonymous executable memory. Plan JIT and library-loading behavior before choosing a policy.

Architecture support is part of activation. The maintained kernel refuses live CFIF requests with ENODEV; CFIB activation is self-only. Having rights to another process does not overcome either limitation. SML can be satisfied by a platform reporting itself unconditionally unaffected. UI_ACCESS remains reserved; do not use the valid-bit mask as a recommended hardening profile.

Fork inherits committed mitigations. Exec preserves them, while recomputing PIP from the executable. PIE governs subsequent exec and NO_CHILD governs subsequent process creation; neither retroactively changes the running image or removes existing children. NO_CHILD permits thread creation and exec.

Handle failures before accepting untrusted work. Read back the committed mask and correlate it with the process GUID; a requested mask or an earlier process's report is not evidence about a replacement process. Self-targeting removes the cross-process authority gates, not input and activation checks. A failed request leaves earlier successful commitments intact.

Do not assume a generic service launcher applies a mitigation mask. Verify the deployed launcher and the running process. The maintained Peinit launch path does not add a per-service mitigation request; inherited flags and application self-hardening remain separate.

Next #

  • process.h reference — the call in full.
  • Process mitigations — every mitigation and its threat model.

Authentication Conversations

Peios / Developing for Peios / Authentication Clients

The authentication client library, libauth.so.1, connects applications to the Peios authentication authority. It carries credential conversations, identity queries, self-account changes, and requests to end logon sessions. The authority checks the connected caller and decides what it can do.

Authentication and logon #

Both operations use the same credential conversation. Authenticate returns an established identity and the requested groups and claims. It creates no OS token, session, home directory, or user registry. Logon additionally checks local logon policy and returns a token and session for the caller to install. An Authenticate result cannot be exchanged for a token later.

Use Authenticate for a service that needs to check identity before applying its own access policy. Authd does not need to understand a Wi-Fi network or the meaning of a department claim. The service interprets the identity data.

The shared authentication request supplies the identifier, supported credential types, an optional required type and any method binding. A password-based consumer sets Password as required: advertising support alone also permits an account whose source intentionally requires no credential.

Authenticate separately requests full source group membership and selects None, Named or AllPermitted claim disclosure. AuthenticationSecurity checks group and named-claim permissions before credential collection. Forbidden named disclosure fails the request. An authorized named claim absent from the source is listed explicitly; unrequested groups differ from an empty membership set. Group results exclude locally synthesized token groups.

Claim names use KACS's per-character Unicode lowercase mapping, without normalization or full case folding. Équipe and équipe name the same claim; ß and ss do not. This applies to lookup, duplicate detection, known absence, and claim-specific permission GUIDs. Results retain the source's spelling; claim-value matching is unchanged. A Named absence can therefore supply partial KACS claim knowledge using the same name rule. Other sources must establish matching semantics before their absence assertions are adapted.

This replaces the unpublished ASCII-only development rule. Before upgrading, regenerate affected non-ASCII claim permission GUIDs using auth-policy's claim_guid helper while preserving grants and denies. ASCII identifiers stay unchanged. Resolve source records containing newly equivalent duplicate names; authd refuses their assertions rather than choosing one. Rebuild named-disclosure clients with matching auth-core and libauth revisions. An older authority's ASCII-only absence result cannot be accepted safely. Use the current framing and ABI versions described below.

AllPermitted returns readable claims and a coverage marker. Complete means the result is the whole claim set and omitted names are absent. Filtered means some names might be restricted; omitted names remain unknown. Authd determines coverage from policy rather than the presence of hidden claims, and never reports restricted names or counts. A consumer must deny a policy decision that needs unknown information. Conditions using returned values or complete group membership can still be evaluated normally.

In C, begin with peios_auth_authenticate_begin, read AuthenticationView and the existing identity getters at record index zero, and enumerate absent claims with peios_auth_authentication_absent_claim. The operation owns the result until destroyed. The Rust Client::authenticate wrapper returns an owned Authenticated result through Operation::authenticated. No token accessor succeeds for this operation. AuthenticationView.claim_coverage preserves this knowledge through the C ABI; the owned Rust result exposes ClaimCoverage. The coordinated unpublished C ABI and public PGSS framing versions are 6. Rebuild clients with the matching library; the source protocol is version 4.

An MSCHAPv2 originator advertises Capabilities::MSCHAPV2 and requires credential type 3. The source's single typed prompt supplies a 16-byte authenticator challenge in parameters. The answer contains the peer challenge (16 bytes) followed by the NT response (24 bytes). The source owns challenge freshness, account eligibility, and credential-version checks. The completed result includes a 20-byte authenticator response for this exchange, exposed as mschapv2_authenticator_response through the C view and owned Rust result. Other proof types carry no MSCHAPv2 output. This uses the existing Authenticate and disclosure grants and creates no token.

An NTLMv2 originator, such as a file server, names nobody: it sends an empty identifier, advertises only Capabilities::NTLMV2, and requires credential type 4. The authority, not a source, sends the single prompt, whose parameters are the 8-byte server challenge to put in the NTLM CHALLENGE message. Answer with three length-prefixed spans copied from the client's AUTHENTICATE message: UserName and DomainName as UTF-16LE, then NtChallengeResponse. The authority routes on the user in the answer and the owning source verifies it. A logon then returns a token with the 16-byte SessionBaseKey as ntlmv2_session_key in the grant; general authentication returns it in the authenticated result instead. The key is for NTLM key exchange and signing in this one protocol session, and cannot be used to sign in again. Key exchange, the message integrity code and the client's AvPairs remain the originator's to process.

Credential collection #

A logon begins with a proposed identity, logon type, and the credential types the application can collect. The authority can request several rounds of answers. Each round contains messages to display and prompts to answer. The application controls its interface; the library does not read a terminal or create a window.

stateDiagram-v2
    [*] --> Waiting: Begin
    Waiting --> Prompt: Credential request
    Prompt --> Waiting: Answer round
    Waiting --> Complete: Successful reply
    Waiting --> Denied: Authority refusal
    Waiting --> Failed: Transport or protocol error
    Waiting --> Cancelled: Cancel
    Prompt --> Cancelled: Cancel

Prompt labels are display text. Credential types and parameters determine how to collect an answer. Applications advertise supported types and reject requests they cannot handle. Passwords must not be echoed. Secure Shell (SSH) credentials retain the binding to the authorized originator's live transport.

The supported credential list describes what the client can collect. It does not force the source to request a password. An empty list permits only a conversation that needs no collection; it does not bypass account policy.

The authority reads the connected caller's token from the kernel. A proposed logon type is checked against that caller's originator policy. Fields such as the remote host remain claims supplied by the client, not independently verified identity.

Credential verification establishes identity. Token derivation combines that identity with this machine's grants. A source does not send a finished token or choose the machine's privilege set and integrity level.

An unknown account and an incorrect credential share the authentication failure response. The local source performs a decoy password verification for unknown accounts instead of taking a cheap early-return path. This does not make account existence secret: the separate identity interface can report that a principal does not exist. For diagnosis, compare the authority and source authentication events, without recording credential values.

Tokens and sessions #

Successful logon returns a token descriptor, session ID, and profile. The profile supplies a home directory, shell, and display name; these fields are session-start preferences, not proof of identity.

The operation owns the token until the caller takes it. Taking the token transfers responsibility for closing its descriptor. Installing it and starting a process are separate, explicit actions through the Peios software development kit (SDK). Destroying an operation closes any token it still owns.

The shared protocol transport accepts at most one descriptor per message. It rejects extra descriptors and truncated ancillary data, closing received descriptors if it cannot accept the complete message.

A service manager requests a service token through a distinct attestation operation. Self-service credential changes identify the caller from the connection; they do not accept a target username.

Completion and uncertainty #

An authority refusal differs from a lost connection. If a connection fails after a change was submitted, the change could have taken effect. The error reports this as outcome_unknown. Cancellation stops communication but cannot roll back a submitted change. The library never retries a mutation on the application's behalf.

Ending a session can terminate the program requesting the action. For that case, authd replies before termination and reports prospective process counts. A permission query is advisory: the later action is checked again.

Identity results #

Identity queries retain the difference between a missing identity, an unavailable source, and a refused request. A field can have an empty value or be withheld for a stated reason. These are different results.

Enumeration returns an opaque continuation cursor and a list of sources that did not contribute. A page with no records can still have a cursor. Continue until the cursor is empty, and preserve the incomplete-source information when presenting the result.

Read Using the Authentication Client for the operation loop and resource ownership.

Self-Service Operations

Peios / Developing for Peios / Authentication Clients

The authentication client library supports operations on the caller's own account without granting local account-administration rights. The daemon identifies the caller from the connected process's token.

Account details and display names #

Use Client::own_account() or the corresponding C operation to read the caller's local account. The result includes its display name, credential policy, whether a password exists, and enrolled public-key information. It never contains a plaintext password or its verifier.

Use Client::set_display_name() to change the caller's presentation name. The request does not accept a target account name, and a display name does not change the account's security identifier (SID) or sign-in name.

These operations use lpsd's self-service socket. A caller whose account is not held by the local source cannot use that socket to administer a different source's account.

Credential changes need proof #

Password and key changes use credential conversations through authd. The local source asks the caller to prove an accepted current password. Opening the socket or possessing a session token alone is insufficient.

Follow the same prompt handling as a logon: display messages, collect only supported credential types, and answer the current round. An account without a usable password for this proof needs an administrator's help.

Self-service key removal selects a key by its SHA-256 fingerprint. The administrative lps key remove command selects by key ID instead. Use the identifier required by the interface you are calling.

Session actions are checked separately #

Client::may_end_session() queries whether the caller can request an action. Client::end_session() requests the action and checks permission again. A successful query does not guarantee a later request will succeed.

Warn the person before ending a session because running programs can lose unsaved work. The requesting program can be among the processes stopped. Read Sessions and Account Changes for the result's limitations.

Submitted changes can have uncertain outcomes #

A transport error after submission can leave a change's outcome unknown. The public error exposes outcome_unknown; preserve that distinction in the user interface and inspect state before offering a retry.

Canceling or destroying the operation releases client resources. It does not undo a request the daemon has already received. The library does not automatically retry mutations.

For full signatures and ownership rules, use <peios/auth.h>. Local administrator operations are a separate interface; they are not part of the public self-service library.

Using the Authentication Client

Peios / Developing for Peios / Authentication Clients

Use libauth to communicate with the authentication authority from your application. C callers use <peios/auth.h>; Rust callers use peios-auth, which wraps the same shared library.

Before you start #

Prepare the client dependencies:

  • Install the dev.peios.libauth runtime and the dev.peios.libauth-devel software development kit (SDK).
  • Use an account or service identity permitted to perform the operation.
  • For Rust, add the peios-auth crate from the matching authd source revision.

Link the application #

For a C application with a client.c source file:

  1. Include the public header in C:

    #include <peios/auth.h>
    
  2. Obtain compiler and linker flags through pkg-config:

    cc client.c -o client $(pkg-config --cflags --libs auth)
    

For Rust applications built with Cargo, make auth.pc discoverable through PKG_CONFIG_PATH. For an explicit development build, set PEIOS_AUTH_LIB_DIR to the directory containing libauth.so. At runtime, the loader must also find libauth.so.1. A development shell can set LD_LIBRARY_PATH to that directory.

Drive an operation #

Use this sequence for each operation:

  1. Create a client. Default options use the system sockets. Supply explicit socket paths only when selecting a trusted authority or a test server.

  2. Begin the operation. Input strings and buffers are copied before the call returns. A null C handle means the arguments were invalid. A connection failure instead produces an operation with an error result.

  3. Call peios_auth_operation_step(). When it returns PEIOS_AUTH_WAIT, obtain the descriptor, event mask, and maximum wait from peios_auth_operation_poll_info(). Wait, then call step() again, including after a timeout. Never read, write, or close that descriptor.

  4. At PEIOS_AUTH_PROMPT, display the round's messages before collecting answers. Submit answers in prompt order, with their original references and the current round ID. Answer a message-only round with an empty answer array. Clear caller-owned secret buffers after submission.

  5. At a terminal state, inspect the typed result or error. If the operation granted a token, take it only when your program is ready to own the descriptor. Check outcome_unknown before offering to repeat a change.

  6. Destroy the operation and client. Returned C views borrow the operation; copy any data needed after its next mutable call or destruction.

For blocking programs, peios_auth_operation_wait() performs the wait loop until a prompt or terminal state. The Rust wrapper provides the same choice through Operation::step() and Operation::wait(). Its result methods return owned Rust data.

Check the result #

For Authenticate and Logon, peios_auth_operation_guid() returns a borrowed authority operation identifier after a reply supplies it. The Rust accessor is Operation::operation_guid(). An empty C span or Rust None means that the identifier is unavailable. Copy the C span before mutating the operation.

The identifier links to object.authentication.operation.guid in authority events. It is not proof of identity or permission. Older authorities can omit the optional metadata. Malformed or inconsistent metadata removes the correlation link without changing the credential or token result.

The getter is an additive symbol with unchanged ABI 6 layouts. A program using it needs a libauth build exporting the symbol. Existing clients remain compatible with that library, and the public framing remains PGSS version 6.

A completed permission query means that authd permitted the proposed action at the time of the query. A completed logon provides a token and session profile. Neither result changes the calling process's identity.

Use the public header for function signatures, constants, ownership rules, and the application binary interface (ABI) contract. Keep each operation under one caller's control; different operations can run concurrently.

Reading Identities

Peios / Developing for Peios / Authentication Clients

Use the identity operations in libauth when an application needs account or group information. Native results retain details that a simple name string or libc account record cannot express.

Before you start #

Prepare the client:

  • Link the runtime and matching headers or Rust wrapper as described in Using the Authentication Client.
  • Use the system authority or an explicitly trusted endpoint.

Look up an identity #

Follow these steps:

  1. Choose a name, binary security identifier (SID), or Unix identifier as the query key. Use the SID when your application already knows the identity and needs its display name.
  2. Request the identity kind and fields the application needs. Avoid requesting every field for a name-only display.
  3. Begin the lookup and drive its operation to completion using step and polling, or the blocking wait helper.
  4. Inspect the identity outcome as well as the operation state. A completed exchange can still report no matching identity or an unavailable source.
  5. Interpret each returned field's state. An empty value, a withheld value, and an absent field are not interchangeable.

In C, the begin function is peios_auth_identity_lookup_begin(). In Rust, use Client::lookup() and read Operation::identity() after completion. The public header documents the corresponding request and result types.

Enumerate a list #

Follow these steps:

  1. Start an enumeration for principals or groups with an empty cursor. Select a group only when requesting that group's members.
  2. Present or collect the returned records while preserving their SIDs.
  3. Retain the response's incomplete-source information. A partial list must not be presented as proof that omitted identities do not exist.
  4. If the next cursor is nonempty, pass its bytes back unchanged with the same query parameters. Continue even when a page contains no records.
  5. Stop only when the next cursor is empty or an error prevents progress.

Do not parse the cursor, derive one from the last name, or assume that every source supports complete enumeration.

Check the result #

Exercise the application's handling of an unknown identity, an unavailable authority, a withheld field, and an incomplete enumeration. The interface must preserve those differences instead of collapsing them into an empty list or an anonymous account.

C result views borrow the operation. Copy data needed after its next mutable call or destruction. The Rust wrapper returns owned result data.

Detect credential replacement #

CREDENTIAL_BINDINGS requests opaque reference and revision pairs owned by the source. Disclosure requires the existing Authenticate right. A missing, restricted, or unreported field means unknown; it does not establish deletion. References are scoped to the authoritative principal SID. Neither part is a credential, token, or proof of possession.

Local queries list eligible password bindings. Disabling the password credential policy omits that binding from a present list without destroying its stored revision. An explicitly empty list is authoritative; an unreported or restricted list is unknown. NT-storage policy alone does not remove the underlying password binding.

A successful Authenticate result can disclose the binding that actually verified. Retain it with the verified SID. Later SID lookups can detect a replacement; they cannot advance the revision that a session proved. Only fresh successful authentication can do that. Password, MSCHAPv2, and NTLMv2 refer to the same local password binding. Older sources can omit it.

C uses peios_auth_record_credential_binding_count() and peios_auth_record_credential_binding() with reference or revision parts; each borrowed part is 16 bytes. Rust exposes Field::CredentialBindings. These additive exports require matching libauth headers and runtime. Existing ABI 6 layouts are unchanged.

Registry Overview

Peios / Developing for Peios / The Registry

LCS — the Layered Configuration Subsystem — is Peios's registry: a kernel-mediated, hierarchical, secured configuration store. If you have used the Windows registry it will feel familiar — a tree of keys holding typed values — but LCS adds one defining idea: layers. This section teaches the client API; registry.h is the exhaustive reference.

Keys and values #

A key is a node in the tree. It has an immutable GUID identity, a KACS security descriptor that governs who can read or change it, and it holds values and child keys. You address a key by path and open it for specific KEY_* rights, getting back a key fd whose granted access is fixed for its lifetime.

A value is a named, typed piece of data on a key (REG_SZ, REG_DWORD, REG_BINARY, and the rest). An empty name is the key's default value.

Layers and precedence — the LCS idea #

Here is what makes LCS more than a key/value store. Every value write is tagged with a layer, and each layer has a precedence. When you read a value, LCS resolves the effective entry — the one from the highest-precedence layer that has something to say, or, among layers of equal precedence, the most recent write — and that's what you get back.

This is what lets configuration compose cleanly:

  • The base layer, at precedence 0, receives every write that names no layer.
  • Role layers also sit at precedence 0 and carry what an installed role adds.
  • Policy layers sit above precedence 0 and override both.

They all coexist on the same key. Reading gives you the winner; writing targets a specific layer (or the base layer by default). And because it's layers rather than destructive overwrites, removing a higher layer's entry lets the lower one re-emerge — you can override and then un-override without losing the original.

Tombstones are the tool for "hide, don't delete": a per-value tombstone masks lower layers for one value, and a blanket tombstone masks all lower values of a key on a layer at once. Keys have the same idea through hide.

Reads report where the answer came from #

Because a value can come from any layer, the read tells you which layer won and gives you a sequence number for the effective entry. That sequence number is the basis of safe updates: pass it back as a compare-and-swap guard on a write, and the write only lands if nothing changed underneath you.

Transactions #

Mutating operations can be grouped into a transaction and committed atomically: writing or deleting a value, setting or removing a blanket tombstone, creating, deleting, or hiding a key, and changing a security descriptor. A transaction covers one hive, so a multi-step configuration change either fully applies or not at all. Transactions are abort-by-default: close the transaction fd without committing and nothing happens. See watching and transactions.

Watches #

You can ask a key to notify you when it changes — values, subkeys, or its security — optionally across its whole subtree. The elegant part: once armed, the key fd itself becomes pollable, so a registry watch drops straight into an epoll loop with no side channel.

The client, not the source #

This SDK is the registry client — it reads and writes the store. It does not implement a registry source (a storage backend); that's a separate library, librsi. As a client you speak only the calls in registry.h.

Where to go in this section #

  • Reading and writing — open a key, read effective values, write to layers, do safe updates.
  • Watching and transactions — react to changes and apply atomic multi-step edits.
  • registry.h reference — every call in full.

Reading and Writing

Peios / Developing for Peios / The Registry

This guide covers the bread-and-butter registry operations. The full call signatures and error sets are in registry.h; here you string them together. Recall the registry's descriptor-struct buffer convention: reads fill *_cap/*_len fields and a zero-capacity buffer probes.

The code fragments elide some error checks for brevity — every call returns -1 with errno on failure, and real code must check each one (see Library conventions).

Opening a key #

Open a key for the rights you need:

int key = peios_reg_open_key(-1, "/System/MyApp", KEY_READ, 0);
if (key < 0) {
    if (errno == ENOENT) { /* not there */ }
    else if (errno == EACCES) { /* not allowed */ }
    return -1;
}

parent_fd == -1 means path is absolute. To open relative to a key you already hold, pass that key fd as the parent. Use peios_reg_create_key instead when the key might not exist yet — it opens-or-creates and reports which happened.

Reading the effective value #

Reading resolves layer precedence for you and hands back the winning value, its type, and which layer it came from:

struct peios_reg_value v = {0};
unsigned char data[256];
v.data = data;  v.data_cap = sizeof data;
/* leave v.layer NULL if you don't care which layer won */

if (peios_reg_query_value(key, "Timeout", 7, -1, &v) == 0) {
    /* v.type is REG_*, v.data_len bytes valid in `data`, v.sequence is
       the effective entry's sequence number. */
} else if (errno == ENOENT) {
    /* no effective value (or a tombstone masks it) */
} else if (errno == ERANGE) {
    /* data buffer too small; v.data_len holds the required size — grow & retry */
}

The name_len is explicit (value names are length-counted; 0 reads the key's default value). Pass a transaction fd as the fourth argument to read within a transaction, or -1 for none.

To read every value at once, use peios_reg_query_values_batch — one call fills a buffer with all effective values in a packed record format. To walk them one at a time, loop peios_reg_enum_value from index 0 until ENOENT.

Writing a value #

Writes target a specific layer. Pass NULL/0 for the layer to write the base layer:

uint32_t timeout = 30;
int rc = peios_reg_set_value(key, "Timeout", 7, REG_DWORD,
                             &timeout, sizeof timeout,
                             NULL, 0,      /* base layer */
                             -1,           /* auto-commit (no transaction) */
                             0);           /* no CAS guard */

Writing to a higher-precedence layer overrides lower ones without destroying them; deleting that layer's entry later lets the lower value re-emerge.

Safe updates with compare-and-swap #

To read-modify-write without clobbering a concurrent change, feed the sequence you read back as the expected_seq guard on the write. The write only lands if nothing changed underneath you; otherwise it fails with EAGAIN and you retry:

for (;;) {
    struct peios_reg_value v = {0};
    unsigned char buf[64]; v.data = buf; v.data_cap = sizeof buf;
    if (peios_reg_query_value(key, "Counter", 7, -1, &v) != 0)
        break;                                     /* real error — don't spin */

    uint32_t n; memcpy(&n, buf, sizeof n); n++;

    int rc = peios_reg_set_value(key, "Counter", 7, REG_DWORD,
                                 &n, sizeof n, NULL, 0, -1,
                                 v.sequence);          /* CAS on the sequence */
    if (rc == 0) break;                                /* success */
    if (errno != EAGAIN) { /* real error */ break; }   /* else: retry */
}

Passing expected_seq == 0 disables the guard (an unconditional write).

Cleaning up #

Close key fds with close() when done. Values you wrote with auto-commit (txn_fd == -1) are already durable to the layer; to force the source to persist a hive's pending writes at a known point, call peios_reg_flush.

Next #

  • Watching and transactions — react to changes and batch atomic edits.
  • registry.h reference — every call, field, and error.

Watching and Transactions

Peios / Developing for Peios / The Registry

Beyond simple reads and writes, LCS gives you two higher-order tools: watches to react to change, and transactions to apply several edits atomically. Both are in registry.h; this guide shows the shape of using them. To keep that shape visible, the fragments elide most error checks — every call returns -1 with errno on failure, and real code must check each one (see Library conventions).

Watching for changes #

Ask a key to notify you when it changes, then poll its fd. Because the armed key fd is itself pollable, a watch integrates directly into whatever event loop you already run:

int key = peios_reg_open_key(-1, "/System/MyApp", KEY_READ | KEY_NOTIFY, 0);

/* Watch values and subkeys, across the whole subtree. */
peios_reg_notify(key, REG_NOTIFY_VALUE | REG_NOTIFY_SUBKEY, 1 /* subtree */);

struct pollfd pfd = { .fd = key, .events = POLLIN };
for (;;) {
    poll(&pfd, 1, -1);
    if (pfd.revents & POLLIN) {
        /* read() the key fd to drain the change records, then re-read
           whatever you care about. */
        char records[512];
        ssize_t n = read(key, records, sizeof records);
        /* ... process change records ... */
    }
}

filter is a mask of REG_NOTIFY_VALUE, REG_NOTIFY_SUBKEY, and REG_NOTIFY_SD; REG_NOTIFY_ALL covers all three. The subtree flag extends the watch to descendants. Arming needs KEY_NOTIFY on the key. Call peios_reg_notify(key, 0, 0) to disarm.

Each read() drains as many complete change records as fit — every record starts [total_len: u32][event_type: u16][name_len: u16][name], so you step through the buffer by total_len. The full layout, the REG_WATCH_* event types, and the extra path fields a subtree watch appends are in the reference. Two practical notes: a buffer too small for even one record fails EINVAL, so size it generously rather than exactly; and a REG_WATCH_OVERFLOW record means events were dropped — re-read the key's state instead of trusting the stream.

This is how a service picks up configuration changes live — no polling loop re-reading values on a timer, a blocking poll that wakes when something actually changed.

Transactions #

When a configuration change spans several operations — create a key, set a few values, delete a stale one — you usually want it to be all-or-nothing. That's a transaction.

Begin one, pass its fd as the txn_fd argument to each operation you want enlisted, then commit:

int txn = peios_reg_begin_transaction();

int key = peios_reg_create_key(-1, "/System/MyApp/v2", KEY_WRITE, 0,
                               NULL /* base layer */, txn, NULL);
uint32_t one = 1;
peios_reg_set_value(key, "Enabled", 7, REG_DWORD, &one, sizeof one,
                    NULL, 0, txn, 0);
peios_reg_delete_value(key, "LegacyFlag", 10, NULL, 0, txn);

int rc = peios_reg_commit(txn);
if (rc == 0) {
    /* everything applied atomically; txn is terminal — close it */
} else if (errno == EBUSY || errno == EIO) {
    /* transient: the transaction is still active — retry the commit */
}
close(txn);
close(key);

Two things to keep in mind:

  • Abort is the default. If you close the transaction fd without committing — including on any early-return error path — nothing is applied. So you don't need explicit rollback logic; don't commit.
  • Commit can be retried. EBUSY (write-lock contention) and EIO (source failure) leave the transaction active, so you can retry peios_reg_commit. Only 0 (committed — the fd is now terminal) and EINVAL (already committed or never bound) are final. Check state at any point with peios_reg_txn_status.

Consistent reads #

peios_reg_begin_read_transaction() creates a bounded read-only transaction. Use its fd for every value read and enumeration, and use peios_reg_open_key_transacted() for key resolution. The first read fixes one hive's persistent and volatile data and its layer selection. A write transaction that has not yet written does not provide this guarantee.

Metadata and descriptor reads have matching peios_reg_query_key_info_transacted() and peios_reg_get_security_transacted() calls. Their final argument is the transaction fd, or -1 for a live read. Their buffer contracts match the ordinary calls. Close the transaction as soon as the configuration has been copied.

Mutations fail EROFS, another hive fails EXDEV, and lifetime expiry fails ETIMEDOUT. Capture overlapping Registry publication can return EAGAIN; discard the partial result and repeat the entire read with a fresh transaction. There is no fallback to ordinary reads.

Changing the caller's ordered private-layer or hive-scope attachments during the transaction fails EACCES. Start a fresh transaction for a different view.

Historical descriptors are data. A new transacted open checks the current descriptor of the resolved GUID against the actual caller. Existing handles keep their granted rights. Files named by Registry values are outside the snapshot: prepare immutable files first, switch their references atomically, and retain old files until readers have finished with them.

Backup and restore #

To snapshot a key and its whole subtree, or replace one from a snapshot, use peios_reg_backup and peios_reg_restore. They stream to and from an fd and are gated by SeBackupPrivilege / SeRestorePrivilege; restore applies in a single transaction.

Next #

  • registry.h reference — the notify filters, transaction states, and every error in full.
  • Reading and writing — the value operations you enlist in a transaction.

Registry Sources

Peios / Developing for Peios / Registry Sources

A registry source stores registry data and answers requests from the kernel. Use librsi when implementing that storage backend. Applications that only read or write registry keys use libpeios instead.

The Registry Source Interface (RSI) carries framed requests and responses on a source file descriptor. The libraries share a release and C calling conventions, but each exposes its own shared library.

Request flow #

A registry client reaches storage through the kernel:

flowchart LR
    client[Registry client: libpeios] --> kernel[Kernel registry service]
    kernel <-->|RSI requests and responses| source[Storage backend: librsi]

The source lifecycle has three stages:

  1. Register the hives that the source backs and receive a source descriptor.
  2. Read each request, decode it, perform the storage operation, and respond.
  3. Close the descriptor when the source stops serving requests.

Registration requires SeTcbPrivilege. The source supplies its highest persisted sequence number so that the kernel can continue sequence allocation without reusing older values.

Storage responsibilities #

The kernel mediates client access, checks security, resolves registry layers, and coordinates transactions. The source stores entries, key metadata, values, and transaction state.

A successful response means that the source performed the operation with the persistence semantics required by the registry protocol. librsi encodes and validates messages; it does not implement a database, transaction journal, or recovery policy for the backend.

Buffer lifetime #

Request decoders return pointers into the received frame. Process or copy those bytes before reusing the frame buffer. If storage work outlives the read loop iteration, keep the frame alive or make an owned copy first.

The source sends one response for each request. Preserve its request ID and operation code when constructing the response. Do not send a success status for an operation that the backend has not completed.

Start with registering a source, then serving requests and building responses.

Registering a Source

Peios / Developing for Peios / Registry Sources

Every source starts by registering. You tell the kernel which hives your process backs, and it hands you a source fd to serve on. The full detail is in rsi/source.h; this guide walks the decisions.

Declare your hives #

A hive is a registry subtree with its own root key. Fill in one struct rsi_hive per hive your source backs:

struct rsi_hive hive = {
    .name     = "MyStore",
    .name_len = 7,
    .flags    = 0,                    /* global hive */
    .root_guid = { /* 16-byte GUID of the hive root key */ },
    /* scope_guid left zero for a global hive */
};

The two decisions per hive:

  • Global or private? A global hive (flags = 0, scope_guid zero) is visible system-wide. A private hive (flags = RSI_HIVE_PRIVATE, scope_guid non-zero) is scoped — only tokens carrying that scope GUID in their LCS credentials can resolve it. Use a private hive for per-application or per-tenant state that shouldn't be system-visible.
  • The root GUID. Every hive is anchored at a root key identified by root_guid. This is the GUID paths in the hive resolve from, and it must match the root your storage actually holds.

Register #

Hand the kernel your hive array and the highest sequence number you've already persisted:

int src = rsi_register(&hive, 1, /*max_sequence=*/0);
if (src < 0) {
    perror("rsi_register");   /* EPERM if you lack SeTcbPrivilege */
    return -1;
}
/* `src` is the source fd — serve the RSI protocol on it. */

Two things to get right:

  • SeTcbPrivilege is required. Registration is a trusted operation; without the privilege you get EPERM. Sources run as trusted system components.
  • max_sequence is your durability contract. It is the highest sequence number this source has already persisted. The kernel resumes its global sequence counter past it, so it never hands out a number you've used. A brand-new source with no stored state passes 0; a source restarting with durable data must scan that data for the highest sequence it ever wrote and pass that. Getting this wrong risks sequence reuse, so make it the first thing your restart path computes.

You can register several hives in one call by passing an array and a count greater than one; the kernel enforces its configured MaxHivesPerSource limit (ENOSPC if you exceed it).

Optional transaction lifetime control #

The kernel also supports lifetime extension version 1. A source using it opens /dev/pkm_registry, calls REG_SRC_NEGOTIATE with version 1 and zero flags, retains the returned session identifier, and then calls REG_SRC_REGISTER. The current rsi_register convenience function uses the legacy registration sequence; negotiate through the explicit device/ioctl sequence when adopting this extension.

After reading each request, query REG_SRC_REQUEST_CONTEXT with its request id and the negotiated session. It returns the original request deadline and any transaction lifetime and cleanup-lease deadlines, all in CLOCK_MONOTONIC nanoseconds. Renew live transactions using REG_SRC_RENEW, independently of the normal request queue. Renewal cannot extend the transaction lifetime or revive an expired lease. Both read-write transactions and read-only snapshots use the same ownership rules. Serialize expiry cleanup with transaction operations and wait for an admitted commit's actual result before reclaiming its state.

The data-frame layout is unchanged. Sources without negotiation retain the legacy protocol. Current loregd requires the extension and must be deployed with a kernel that implements it. The PKM TRM, §5.8.3, specifies the control ioctls and their error and lifetime rules.

After registration #

The returned fd is your serve endpoint — you read(2) requests and write(2) responses on it directly (through the request and response helpers). Closing it deregisters the source and signals EOF to the kernel. Keep it open for the life of the source, and move on to the serve loop.

Next #

  • Serving requests — the loop that runs on the source fd.
  • rsi/source.h reference — every field and error.

Serving Requests

Peios / Developing for Peios / Registry Sources

With a source fd in hand, a source spends its life in one loop: read a request, decode it, do the work, reply. This guide builds that loop. The exhaustive per-op detail is in rsi/request.h and rsi/response.h.

The loop skeleton #

unsigned char buf[64 * 1024];   /* size generously — a short buffer is EMSGSIZE */

for (;;) {
    ssize_t n = rsi_read_request(src_fd, buf, sizeof buf);
    if (n == 0) break;                       /* EOF — the source is closing */
    if (n < 0) { perror("read_request"); break; }

    struct rsi_request req;
    if (rsi_parse_request(buf, n, &req) != 0) continue;   /* EBADMSG — skip */

    switch (req.op_code) {
        case RSI_LOOKUP:    handle_lookup(src_fd, &req);    break;
        case RSI_SET_VALUE: handle_set_value(src_fd, &req); break;
        /* … a case per op you support … */
        default:
            /* Unknown or unsupported op: reply with a non-OK status
             * (RSI_TXN_NOT_SUPPORTED for transaction ops you don't implement). */
            rsi_respond_status(src_fd, &req, RSI_INVALID);
            break;
    }
}

Three details in that skeleton matter:

  • rsi_read_request blocks until a request is queued, and returns 0 at EOF — that's your exit. Size buf generously; a frame larger than buf returns -1/EMSGSIZE.
  • rsi_parse_request gives you req.op_code to dispatch on, plus req.request_id (which every reply must echo — the helpers do this for you) and req.txn_id (nonzero when the request is inside a transaction).
  • Always reply. Every request expects exactly one response. If you can't handle an op, reply with a non-OK status rather than dropping it.

Decoding a request #

Inside a handler, decode the payload with the matching rsi_request_* parser. For a LOOKUP:

void handle_lookup(int fd, const struct rsi_request *req)
{
    struct rsi_lookup q;
    if (rsi_request_lookup(req, &q) != 0) {          /* EBADMSG */
        rsi_respond_status(fd, req, RSI_INVALID);
        return;
    }

    /* q.parent_guid (by value), q.child_name / q.child_name_len (borrowed).
       Resolve the child in your storage across its layers … */

    /* … then reply with the resolved path entries + metadata: */
    rsi_respond_lookup(fd, req, entries, entry_count, metadata, metadata_count);
}

And for a SET_VALUE, a status-only op:

void handle_set_value(int fd, const struct rsi_request *req)
{
    struct rsi_set_value v;
    if (rsi_request_set_value(req, &v) != 0) {
        rsi_respond_status(fd, req, RSI_INVALID);
        return;
    }

    /* Honour the CAS guard before storing. */
    if (v.expected_sequence != 0 && current_seq(&v) != v.expected_sequence) {
        rsi_respond_status(fd, req, RSI_CAS_FAILED);
        return;
    }
    store_value(&v);                                  /* your storage */
    rsi_respond_status(fd, req, RSI_OK);
}

The borrow rule #

Every decoded name and data field — q.child_name, v.value_name, v.data, and the rest — is a (ptr, len) pair that points into buf. Those pointers are valid only until the next rsi_read_request reuses the buffer. So:

  • Consume them within the handler (store the bytes, resolve the name) before the loop comes around again, or
  • Copy out anything you need to keep. Never stash a raw borrowed pointer across iterations.

GUIDs and scalars in the decoded struct are copied by value, so those are always safe to keep — it's only the borrowed (ptr, len) fields that have the lifetime.

Transactions #

When the kernel sends BEGIN_TRANSACTION, buffer subsequent writes tagged with that transaction_id instead of applying them; req.txn_id on each later request tells you which transaction it belongs to (0 = none). On COMMIT_TRANSACTION apply the buffered set atomically; on ABORT_TRANSACTION discard it. All three are status-only replies. The kernel coordinates transaction boundaries — your job is to buffer, then commit or discard on command.

Next #

  • Building responses — choosing and filling the right reply.
  • rsi/request.h reference — every op's decoder and struct.

Building Responses

Peios / Developing for Peios / Registry Sources

Every request gets exactly one response. Choosing the right one is simple once you know the rule; filling it in is a matter of handing librsi flat arrays and letting it encode the frame. The full contract is in rsi/response.h; this guide is the working version.

The rule #

On failure, always rsi_respond_status. On success, rsi_respond_status too — unless the op is one of the five that carry a payload.

Most operations (SET_VALUE, CREATE_KEY, the transaction ops, FLUSH, …) are status-only in both cases. And any op reports a non-OK outcome with rsi_respond_status, whatever it is:

/* Success for a status-only op: */
rsi_respond_status(fd, req, RSI_OK);

/* Any op reporting a problem: */
rsi_respond_status(fd, req, RSI_NOT_FOUND);   /* for example a missing key */
rsi_respond_status(fd, req, RSI_CAS_FAILED);  /* a failed CAS */

You never build the frame or echo the request id yourself — the helper reads what it needs from req and writes the framed reply to fd.

The five payload-bearing ops #

Exactly five ops return data on success, each with its own helper:

OpHelperYou supply
LOOKUPrsi_respond_lookuppath entries + the referenced keys' metadata
ENUM_CHILDRENrsi_respond_enum_childrenchildren (name + path entries) + metadata
READ_KEYrsi_respond_read_keyone key's non-layered metadata
QUERY_VALUESrsi_respond_query_valuesvalue entries + blanket tombstones
DELETE_LAYERrsi_respond_delete_layerthe orphaned keys' GUIDs

You pass the result as flat arrays; librsi validates and heap-encodes the wire frame. A QUERY_VALUES reply, for example:

struct rsi_value_entry values[] = {
    { .value_name = "Timeout", .value_name_len = 7,
      .layer_name = "base",    .layer_name_len = 4,
      .value_type = REG_DWORD, .data = &timeout, .data_len = 4,
      .sequence = 42 },
    /* … one per effective value you hold … */
};

rsi_respond_query_values(fd, req, values, 1, /*blankets=*/NULL, 0);

You report what you store, per layer; the kernel resolves precedence across the layers you return. (Note the (NULL, 0) for the empty blanket array — a NULL pointer is allowed only when its count is zero.)

The validation contract #

The helpers check their inputs before encoding and return -1/EINVAL if you break the contract — better a caught programming error than a malformed frame on the wire. The rules that apply across all of them:

  • (ptr, len) pairs: a pointer can be NULL only when its length/count is zero.
  • Booleans (volatile_key, symlink, target types) are strictly 0 or 1.
  • Hidden path targets (RSI_PATH_TARGET_HIDDEN) carry an all-zero target_guid.
  • LOOKUP / ENUM_CHILDREN metadata must exactly cover the GUID targets in your path entries — every referenced key present, none missing, no duplicates, nothing unreferenced.
  • DELETE_LAYER orphan GUIDs are nonzero and unique.

Beyond EINVAL, a helper can also fail with ENOMEM or EOVERFLOW (building the frame), EIO (a short write), or the raw write(2) errno — treat those as you would any I/O failure on the source fd.

Putting it together #

A source's handler for a payload-bearing op is: decode the request, gather the result from storage into the flat arrays the helper wants, call the helper. For a status-only op: decode, do the work, rsi_respond_status. On any error along the way — a decode failure, a missing key, an I/O problem — rsi_respond_status with the appropriate non-OK RSI_* code. That uniformity is what keeps a source's dispatch table readable no matter how many ops it supports.

Next #

  • rsi/response.h reference — every helper, struct, and error in full.
  • Serving requests — the loop these replies live in.

Events Overview

Peios / Developing for Peios / Events

KMES is Peios's event system, and it is the sole event path on the system. Audit records, subsystem events, and your own application events all travel the same way: the kernel stamps each event with trusted metadata and writes it into a per-CPU, lock-free ring buffer, and consumers drain those rings. This section teaches both sides — producing and consuming — through event.h and msgpack.h.

What an event is #

An event has two parts:

  1. Kernel-stamped metadata you cannot forge — a CLOCK_REALTIME timestamp, a per-CPU monotonic sequence number, the CPU id, an origin class, and identity GUIDs (the effective token, the true token, and the process). This is the trustworthy skeleton: when you consume an event, you know who emitted it and when, because the kernel wrote that, not the emitter.
  2. A payload — a single MessagePack value that you define. This is your event's actual content.

The event type names the kind of event. It's a dotted name made of your package name, what the event is about, and what happened, such as org.example.backup.snapshot.created. Its fields follow one vocabulary shared by every emitter on the system. Naming and Shaping Events explains how to choose both.

Payloads are MessagePack, and you own them #

The kernel does not build or interpret payloads — it only structurally validates them on emit (one well-formed MessagePack value, within size and nesting limits). So userspace owns encoding and decoding, and the SDK ships a MessagePack codec whose validator's acceptance is matched to the kernel's check. Build a payload with the writer, and a successful peios_mp_writer_bytes (or peios_mp_validate) establishes structural validity. Emission still checks size limits, permissions, rate limits, and the other requirements of the event interface.

Per-CPU rings and lost events #

Events live in per-CPU ring buffers — one ring per logical CPU, lock-free so producers never block on consumers. Two consequences shape how you consume:

  • You drain per CPU. To see everything, run a reader per CPU (discover the count by attaching upward from CPU 0 until it fails).
  • Rings can lap. If you don't drain fast enough, new events overwrite old ones you haven't read. The per-CPU sequence numbers are contiguous, so a gap in the sequence means events were lost — and the reader tracks that count for you.

Privileges #

The two sides are gated separately:

  • Emitting requires SeAuditPrivilege.
  • Consuming (attaching to a ring) requires SeSecurityPrivilege.

Two ways to consume #

The SDK offers a high-level reader that hides the entire lock-free drain — barriers, lapping recovery, lost-event accounting, buffer-resize handling, and the wait — behind a simple next/wait loop. That's what almost everyone should use. There is also a low-level ring API for callers who need to drive the drain inside their own event loop. Both are covered in consuming events.

Where to go in this section #

  • Naming and Shaping Events — design the type, fields, tier, and catalog entry before emitting it.
  • Emitting events — build a payload and emit individual events or batches.
  • Consuming events — drain the rings with the high-level reader (and, briefly, the low-level ring).
  • event.h and msgpack.h — the exhaustive reference.

Naming and Shaping Events

Peios / Developing for Peios / Events

Design an event around an occurrence an operator needs to identify, query, or investigate. A shared naming scheme and field vocabulary let the same filters and access policies work across components and language SDKs.

The example is a backup package named org.example.backup. It records each attempt to create a snapshot archive. The event specification owns the rules; this guide applies them to an emitter's design.

Before you start #

  • Identify the package that owns the event and the operation it describes.
  • Inspect the installed event catalog with evman from Peiosutils.
  • Identify which facts your component observes and which it receives as claims.

Choose an event rather than a log or metric #

  1. Ask whether an operator would act on the information. Developer narrative belongs in a log.
  2. Ask whether one occurrence matters by itself. If only the trend matters, publish a metric instead.

A failed snapshot matters individually, so the backup attempt is an event. The daily amount of backed-up data is a metric. A trace of internal function calls is developer logging. See Event Classification and Tiers.

Name the operation #

  1. Start with the owning package name.

  2. Add nouns from general to specific where the grouping supports a useful filter or policy boundary.

  3. End with a past-tense description of the operation:

    org.example.backup.snapshot.created
    

Use one type for success and failure. A failed creation still uses this type, with outcome.success = false; do not add a parallel snapshot.failed type. Use lowercase kebab-case segments, such as copied-up. Short platform roots, such as kacs, are reserved. Package-name roots and the remaining segments have their own grammar in Event Types.

Reuse the field vocabulary #

  1. Search existing definitions before adding fields:

    evman object.file
    evman -k snapshot
    
  2. Choose fields by their role: subject for who acted, object for what was acted on, source and destination for endpoints, and outcome for the result.

  3. If no existing field has the required meaning, define a field beneath the owning package name and its role.

The snapshot uses shared fields plus one package-owned identifier:

FieldMeaning in the snapshot event
object.kindfile
object.file.pathArchive path
object.file.sizeArchive size in bytes, present on success
object.org.example.backup.snapshot.idStable snapshot identifier
operation.durationElapsed nanoseconds
outcome.successWhether creation succeeded
outcome.reasonA declared reason when it failed
outcome.errnoNegative error number when applicable

The package owns object.org.example.backup.snapshot.id; it references the other definitions rather than redefining them. If many components need the same missing concept, propose a shared field instead of giving it several incompatible names.

Do not duplicate the timestamp, sequence, or identity fields already stamped in the event header. Use binary security identifiers for principals rather than account names. Omit a field for which no value is available; do not substitute nil, an empty string, or zero. A real zero, such as an empty file's size, remains a meaningful value.

Match the declared wire types #

Choose the encoding from the catalog definition, not from how a value is displayed:

ValueMessagePack encoding
Security identifier (SID)Binary SID bytes
Globally unique identifier (GUID)16 raw bytes
TimestampUnsigned nanoseconds since the Unix epoch
DurationUnsigned nanoseconds
BooleanBoolean value
String enumerationDeclared kebab-case string
Numeric enumerationDeclared unsigned numeric value
Error numberSigned negative integer

A numeric enumeration is not interchangeable with a string enumeration. Follow the declared field type and its list of values. See Values for the full encoding rules.

Represent dotted paths as nested maps. object.file.path means an object map containing a file map containing a path key. A literal key named object.file.path is not that hierarchy. The package-owned identifier has its own nested object → org → example → backup → snapshot → id path.

Record the outcome #

  1. Set outcome.success to the result of the operation.
  2. On failure, supply a declared outcome.reason, such as disk-full.
  3. Include outcome.errno only when an error number applies. Record its negative form, such as -ENOSPC.

The reason is a stable filtering value. Free-form explanation belongs in outcome.detail when the catalog allows it; consumers should not parse that text as a replacement for the reason. Describe required and conditional fields in the fragment so both successful and failed attempts remain valid. See Outcomes.

Choose the tier and apply policy #

Use standard for ordinary operational records, including this snapshot. Use verbose for investigation detail and debug for developer detail; those tiers are off by default. Reserve essential for rare, critical occurrences or events already governed by their own configuration, such as access auditing. Essential does not mean that every program's diagnostics are unconditionally important.

Emission policy is rooted at Machine\Generic\Events, with one key per segment. This package's subtree is Machine\Generic\Events\org\example\backup. Check policy before building and emitting a nonessential record. Consumer-side filtering does not replace that decision. Read Emission Policy for inheritance, failure handling, and interactions with other audit controls.

Publish the definition and check the result #

  1. Describe the event and package-owned field in an .evman fragment.
  2. Specify the tier and each field's required, optional, or conditional presence.
  3. Lint it with the intended catalog and test actual encoded events against it.
  4. Include the fragment in the package alongside the emitter.

Writing evman Pages contains the matching snapshot fragment and the validation workflow. Keep it as the format example rather than maintaining a second copy here. Emitting Events builds the corresponding payload with the C SDK and explains individual and batch submission.

A well-formed MessagePack value is not necessarily a catalog-conforming event. Check that successful and failed fixtures contain every required field with the declared type, that absent values are omitted, and that queries can reach the nested paths. A successful encoding or emission call does not prove those semantic properties.

If your daemon guards access to its own objects, pass an audit context to the kernel access check instead of inventing a competing access-denial event. Access Decisions explains how the descriptor and audit policy control those records.

Emitting Events

Peios / Developing for Peios / Events

Use the C SDK to encode an event payload and submit it to the kernel. Choose the type and its catalog definition first; the example follows Naming and Shaping Events. The event and MessagePack headers define the complete API.

Before you start #

  • Install matching Peios SDK headers and libraries.
  • Run emission calls on a Peios kernel with SeAuditPrivilege available as required by the access policy.
  • Install the matching .evman fragment and select the declared tier.
  • Include <peios.h>, <errno.h>, <stdint.h>, and <string.h> in the example's translation unit.

Check emission policy #

  1. Open a peios_event_policy handle at startup and handle allocation failure.
  2. Before constructing a payload, call peios_event_policy_enabled with its type name and declared tier.
  3. If the result is 0, skip the event. If it is -1, handle the failure according to the policy interface rather than treating it as permission.
  4. Close the handle when the emitter shuts down.

The handle caches decisions and watches registry changes. Its check does not make a later emit operation atomic with a policy update. Essential types are always on at this layer; their own audit or reporting controls still apply. See Emission Policy.

Build a complete payload #

The following helper builds a successful snapshot event matching the fragment in Writing evman Pages. Supply a valid UTF-8 archive path, a 16-byte snapshot identifier, the archive size, and the elapsed nanoseconds. The helper returns an owned writer that the caller must free.

static peios_mp_writer *snapshot_payload(
    const char *path, const uint8_t snapshot_id[16],
    uint64_t size_bytes, uint64_t elapsed_ns)
{
    if (path == NULL || snapshot_id == NULL) {
        errno = EINVAL;
        return NULL;
    }
    peios_mp_writer *writer = peios_mp_writer_new();
    if (writer == NULL) return NULL;

    peios_mp_write_map(writer, 3);
    peios_mp_write_str(writer, "object", 6);
    peios_mp_write_map(writer, 3);
    peios_mp_write_str(writer, "kind", 4);
    peios_mp_write_str(writer, "file", 4);
    peios_mp_write_str(writer, "file", 4);
    peios_mp_write_map(writer, 2);
    peios_mp_write_str(writer, "path", 4);
    peios_mp_write_str(writer, path, strlen(path));
    peios_mp_write_str(writer, "size", 4);
    peios_mp_write_uint(writer, size_bytes);
    peios_mp_write_str(writer, "org", 3);
    peios_mp_write_map(writer, 1);
    peios_mp_write_str(writer, "example", 7);
    peios_mp_write_map(writer, 1);
    peios_mp_write_str(writer, "backup", 6);
    peios_mp_write_map(writer, 1);
    peios_mp_write_str(writer, "snapshot", 8);
    peios_mp_write_map(writer, 1);
    peios_mp_write_str(writer, "id", 2);
    peios_mp_write_bin(writer, snapshot_id, 16);

    peios_mp_write_str(writer, "operation", 9);
    peios_mp_write_map(writer, 1);
    peios_mp_write_str(writer, "duration", 8);
    peios_mp_write_uint(writer, elapsed_ns);
    peios_mp_write_str(writer, "outcome", 7);
    peios_mp_write_map(writer, 1);
    peios_mp_write_str(writer, "success", 7);
    peios_mp_write_bool(writer, true);

    if (peios_mp_writer_bytes(writer, NULL) < 0) {
        int saved_errno = errno;
        peios_mp_writer_free(writer);
        errno = saved_errno;
        return NULL;
    }
    return writer;
}

A map count is the number of key/value pairs. A dotted catalog path becomes a chain of nested maps, including each segment of the package-owned field. Writer errors are sticky: check peios_mp_writer_bytes before using its result. Structural validation does not check catalog meaning or guarantee emission.

For a failed snapshot, keep the same type and identifier. Omit the unknown archive size, write outcome.success = false, and include a declared reason. Add a negative outcome.errno when one applies. Adjust the file and outcome map counts to match the fields actually written. Do not append a second outcome map or another top-level value to an already completed payload.

Submit and release the payload #

After a successful policy check, call the helper and submit its bytes:

static int emit_snapshot(const char *path, const uint8_t snapshot_id[16],
                         uint64_t size_bytes, uint64_t elapsed_ns)
{
    static const char type[] = "org.example.backup.snapshot.created";
    peios_mp_writer *writer = snapshot_payload(
        path, snapshot_id, size_bytes, elapsed_ns);
    if (writer == NULL) return -1;

    const void *payload = NULL;
    ssize_t length = peios_mp_writer_bytes(writer, &payload);
    int result = -1;
    if (length >= 0 && (uint64_t)length <= UINT32_MAX) {
        result = peios_event_emit(
            type, sizeof type - 1, payload, (uint32_t)length);
    } else if (length >= 0) {
        errno = EOVERFLOW;
    }
    int saved_errno = errno;
    peios_mp_writer_free(writer);
    errno = saved_errno;
    return result;
}

The bytes are borrowed from the writer until it is changed or freed. The submission copies them before returning. The length-counted UTF-8 type is nonempty; the terminating NUL is not part of the name on the wire.

Handle emission errors, including invalid input, insufficient privilege, oversized payloads, and rate limiting. A successful encoding does not bypass those checks. On success, the kernel supplies trusted header metadata and marks the origin as userspace. Your payload remains the emitter's assertion.

Batch high-rate events #

peios_event_emit_batch accepts an array of peios_event_entry values and reports the accepted prefix through its emitted output. Count is bounded by KMES_BATCH_MAX_ENTRIES and cannot be zero.

If an entry fails, earlier entries can already have been emitted. Do not replay that prefix as though the batch were a transaction. Rate-limit refusal is the special all-or-nothing case: EAGAIN accepts no entries in that batch. Keep all names and payload buffers valid until the call returns.

See Batch Emit for the complete signature and error contract. Shared timestamp capture and wakeup work make batching useful when the application naturally has multiple events ready; avoid delaying important events merely to fill a batch.

Check the result #

  1. Decode a portable fixture and verify its field paths and wire types against the catalog, including the required snapshot identifier.
  2. Test successful and failed operation payloads separately.
  3. In a permitted Peios test environment, confirm policy-controlled omission, emission results, and the record observed by a consumer.

Consuming Events explains the read side. A codec test on another kernel verifies encoding only, not Peios emission or identity stamping.

Consuming Events

Peios / Developing for Peios / Events

Consuming events means draining the per-CPU ring buffers. The SDK's high-level reader hides all the hard parts, so most consumers are a short loop. This guide shows that loop and how to parse what you read; event.h has the full API. Consuming requires SeSecurityPrivilege.

The reader loop #

Open a reader for a CPU, then loop next/wait:

peios_event_reader *r = peios_event_reader_open(cpu);
if (!r) { /* errno */ }

for (;;) {
    struct peios_event ev;
    int rc = peios_event_reader_next(r, &ev);
    if (rc == 1) {
        handle_event(&ev);                       /* got one */
    } else if (rc == 0) {
        peios_event_reader_wait(r, -1);          /* none right now — sleep */
    } else {
        break;                                   /* error */
    }
}
peios_event_reader_close(r);

peios_event_reader_next returns 1 (event filled), 0 (nothing available — call wait), or -1 (error). peios_event_reader_wait blocks until events arrive or the timeout elapses (negative = forever). The reader handles the memory barriers, lapping recovery, buffer-resize handling, and futex wait internally — you alternate the two calls.

Parsing an event #

Each struct peios_event gives you the trusted metadata by value and the payload as a MessagePack value. Parse it with a reader:

void handle_event(const struct peios_event *ev)
{
    /* Metadata is trustworthy — the kernel stamped it. */
    /* ev->timestamp, ev->sequence, ev->cpu_id, ev->origin_class,
       ev->process_guid, ev->effective_token_guid, ... */

    /* event_type and payload are NOT NUL-terminated — use the lengths. */
    static const char type[] = "org.example.backup.snapshot.created";

    if (ev->event_type_len == sizeof type - 1 &&
        memcmp(ev->event_type, type, sizeof type - 1) == 0) {

        struct peios_mp_reader mp;
        peios_mp_reader_init(&mp, ev->payload, ev->payload_len);

        ssize_t pairs = peios_mp_read_map(&mp);
        for (ssize_t i = 0; i < pairs; i++) {
            const char *key; ssize_t klen = peios_mp_read_str(&mp, &key);
            /* dispatch on key; read or peios_mp_skip(&mp) the value */
        }
    }
}

The lifetime rule #

In libpeios 0.5.12 and later, ev->event_type and ev->payload point into a private reader snapshot. Kernel overwrites cannot change those bytes. The pointers remain valid until the next read or reader closure. Copy anything you need to retain beyond that lifetime.

Draining every CPU #

Rings are per-CPU, so one reader sees only one CPU's events. To consume the whole machine, run a reader per CPU — typically one thread each. Discover the CPU count by attaching upward until it fails:

uint32_t ncpu = 0;
for (;;) {
    uint64_t cap;
    int fd = peios_event_attach(ncpu, &cap);   /* low-level probe */
    if (fd < 0) break;                          /* EINVAL past the last CPU */
    close(fd);
    ncpu++;
}
/* now spawn one peios_event_reader per cpu in [0, ncpu) */

Watching for loss #

If a consumer falls behind, the producer laps it and events are lost. Poll peios_event_reader_lost to see the cumulative count of lost events (derived from sequence gaps). A rising number means you aren't draining fast enough — process events more cheaply, hand off to a worker, or accept the loss deliberately.

The low-level ring #

If the reader's loop doesn't fit your event model — you want the ring integrated into an existing epoll/state-machine loop, driving the read position yourself — the low-level ring API exposes the mapping directly: peios_event_ring_map, the position accessors (write_pos/tail_pos/generation), peios_event_ring_event_at to parse a slot, and peios_event_ring_wait to sleep. It's more bookkeeping (you own the read position and the empty/lapping/generation checks) for more control. Reach for it only when you need to; the high-level reader is the right default.

Next #

  • event.h reference — the full reader and ring APIs, and every struct peios_event field.
  • Auditing — the operator-side view of the event and audit stream.

Rust Query Clients

Peios / Developing for Peios / Events

The eventd-client Rust crate provides query framing and client lifecycle handling. It shares access-right constants with the daemon so that clients can describe policy without implementing the authorization decision.

The default access feature includes the local access-policy helpers. Query-only consumers can turn off default features without changing the server's authorization of their queries.

Finite queries #

query returns the complete result after the server's terminal response. A server error discards the accumulated initial records. The call blocks, so a graphical client must keep it off its interface thread.

The result is a vector in client memory. Server resource limits do not make that client allocation a fixed-size buffer. Choose bounded queries or use the wire interface when an application needs a different storage strategy.

wire::Connection::bounded(stream, max_frame_bytes) rejects an oversized response-frame length before reserving its body. A rejected frame ends the connection. Reconnect instead of trying to skip the body. The bound applies to encoded frame bytes; decoded values and retained result collections need separate memory bounds. Connection::new retains its protocol-sized bound.

Streaming queries #

Tail reads a STREAM query on a worker thread. It reports the complete initial result, live batches, and the reason the stream ended. Dropping the handle shuts down the connection and releases the receiving channel.

The channel capacity bounds queued reports, not their total bytes. A client that stops consuming reports eventually stops reading the socket, and the server can disconnect it. A client must handle that end state; reconnecting does not provide a resume cursor.

Query text and policy #

Use the crate's text helpers to quote values when constructing queries. Do not concatenate untrusted strings as query syntax.

The access module can describe relevant registry policy to a person. Only eventd, using kernel access checks and the socket peer token, authorizes a query. A client's policy preview cannot replace that check.

See the manual's client library reference for lifecycle and wire details.

System Service Libraries

Peios / Developing for Peios / System Service Libraries

Peios system services publish C libraries so that your application can ask them for their state, or ask them to act, without starting a command and reading its output. Each library has a Rust crate that wraps the same shared library. For access control, the registry, and events, use the Peios SDK instead. For sign-in and account operations, use the authentication client.

Choosing a library #

Choose the library for the service or format you need:

LibraryUse it toRust crateGuide
libresolvdLook up names and addresses, read resolver status, and flush the cacheresolvd-clientUsing libresolvd
libtimedRead clock status and sources, follow clock changes, and request time changestimed-clientUsing libtimed
libtrustRead and follow the trusted root certificates, and add or distrust certificatestrust-clientUsing libtrust
libreg, libregman, libevmanParse registry documents, registry manuals, and event catalogspeios-reg, peios-regman, peios-evmanUtility Libraries

libresolvd, libtimed, and libtrust talk to a running service. The utility libraries work on documents and need no service.

What the service decides #

The service, not the library, decides what each call can do. It checks the caller's permissions for the operation, so a call can be refused even when the library loads and connects. A management call, such as adding a trusted certificate or flushing the resolver cache, uses your own rights; the library never raises them.

Each library's major version is part of its shared-library name, such as libresolvd.so.1. A new major version means an incompatible C interface, so link against the major version your code was written for.

Utility Libraries

Peios / Developing for Peios / System Service Libraries

The Peios utility libraries let your application work with the same document formats as the command-line tools. You can import a registry document, show configuration help, or look up an event description without starting another process or interpreting terminal output.

Choosing a library #

LibraryPurposeReference
libregParse, export, and apply registry batch documentslibreg(3)
libregmanParse and search registry manualslibregman(3)
libevmanParse, check, and search event catalogslibevman(3)

Each library has a C interface and a safe Rust wrapper. The runtime package provides a shared library; its matching development package provides headers and linking information. The libraries share Peiosutils release versions, while their ABI major identifies the compatible C interface.

Parsing a registry document doesn't change the registry. Applying it is a separate operation that uses the caller's access token. A document that parses successfully can still fail validation or access checks when applied.

Manual and event parsers can return usable records alongside diagnostics. Check both: a successful library operation doesn't mean every source record is valid. This lets an editor display the valid content and explain problems in the same view.

Ownership across language boundaries #

A C operation returns a handle that owns its result or its error. Check the error accessor, then read the result. Free the handle on either path. Views returned by the library borrow that handle, so copy anything you need to retain before freeing it.

The Rust wrappers manage these handles automatically. Registry-manual records and event-query matches are owned Rust values. A registry document keeps its library handle alive while you borrow its JSON representation.

The C interfaces accept pointer-and-length spans rather than terminated strings. This preserves the difference between an absent optional value and an explicitly empty one. Text is UTF-8; filesystem paths in the manual and event libraries retain their original Unix bytes.

Moving from the earlier Rust crates #

Use peios-reg, peios-regman, and peios-evman for application code. They call the corresponding shared library. The earlier Rust-only crates exposed implementation types directly; changing only a dependency name doesn't adapt those types to the new ownership model.

The implementation crates registry-docs, registry-manual, and event-catalogue are internal to Peiosutils. Keep application integrations on the public wrappers or C interfaces so an implementation change doesn't require a matching change in every consumer.

Using libresolvd

Peios / Developing for Peios / System Service Libraries

libresolvd.so.1 provides the public C interface for resolvd. The resolvd-client crate wraps the same shared library and returns owned Rust values. Internal implementation crates do not replace this public boundary.

Operations #

The library reads resolver status, looks up addresses, resolves DNS record types, performs reverse lookups, and flushes the cache. Replies retain their source, interface, and server information. A successful library exchange can still contain a DNS failure outcome; check the typed answer before using its records. Flushing requires the caller's existing control permission.

The shared library is libresolvd.so.1. It is separate from the platform's libresolv library and from libnss_peios_net.so.2, which provides the glibc name-service interface. Applications do not link the NSS module directly.

Linking and ownership #

Include <peios/resolvd.h> and use the resolvd pkg-config module. The installed header and libresolvd(3) describe individual functions and data layouts. peios_resolvd_abi_version() returns the ABI major version, 1.

Each operation returns an owned result, including failures. Check peios_resolvd_result_error() before reading a view, and release the result exactly once with peios_resolvd_result_free(). Error codes are POSIX numbers; human-readable diagnostic wording is not a stable identifier. Reading the stored error does not set thread-local errno.

Strings are UTF-8 spans with explicit byte lengths, without terminating NUL bytes. Input spans are borrowed for the call and must remain live, aligned, and initialized. A null pointer with zero length represents absent optional text; a non-null pointer with zero length represents present empty text. Returned strings, arrays, and nested views belong to the result. Copy what you need before freeing it. Handles from another library are not valid here.

Connections and failure #

Each ordinary daemon operation opens its own filesystem Unix socket. The system default is /run/resolvd/resolv.sock; clients can select another socket for a private service instance or a test.

A positive timeout in milliseconds bounds connection, sending, and receiving together. A full connection queue can fail immediately. A transport error does not establish whether a requested change was applied. The library does not automatically replay operations after an uncertain failure.

Rust access #

Use Client::system(Duration) for the installed daemon or Client::new(path, Duration) for an explicit socket. The wrapper copies result views into Rust values and releases C results through Drop. Select a matching source revision of resolvd-client and link the installed shared library; the crate is not a precompiled Rust ABI package.

Using libtimed

Peios / Developing for Peios / System Service Libraries

libtimed.so.1 provides the public C interface for timed. The timed-client crate wraps the same shared library and returns owned Rust values. Internal implementation crates do not replace this public boundary.

Operations #

The library reads status and sources, subscribes to clock snapshots, requests configuration reloads, and requests manual time changes. The daemon checks permissions and whether its operating mode allows a manual change.

Configuration helpers parse a server entry, check zone-name syntax, verify an installed zone, and read zone and country lists. Zone-name syntax alone does not establish that the zone is installed. Zone files and metadata must be regular files of at most 16 MiB; aliases to regular files are supported. Missing or unreadable metadata produces an empty list. These helpers do not change the registry or the system clock.

Linking and ownership #

Include <peios/timed.h> and use the timed pkg-config module. The installed header and libtimed(3) describe individual functions and data layouts. peios_timed_abi_version() returns the ABI major version, 1.

Each operation returns an owned result, including failures. Check peios_timed_result_error() before reading a view, and release the result exactly once with peios_timed_result_free(). Error codes are POSIX numbers; human-readable diagnostic wording is not a stable identifier. Reading the stored error does not set thread-local errno.

Strings are UTF-8 spans with explicit byte lengths, without terminating NUL bytes. Input spans are borrowed for the call and must remain live, aligned, and initialized. A null pointer with zero length represents absent optional text; a non-null pointer with zero length represents present empty text. Returned strings, arrays, and nested views belong to the result. Copy what you need before freeing it. Handles from another library are not valid here.

Connections and failure #

Each ordinary daemon operation opens its own filesystem Unix socket. The system default is /run/timed/time.sock; clients can select another socket for a private service instance or a test.

A positive timeout in milliseconds bounds connection, sending, and receiving together. A full connection queue can fail immediately. A transport error does not establish whether a requested change was applied. The library does not automatically replay operations after an uncertain failure.

Rust access #

Use Client::system(Duration) for the installed daemon or Client::new(path, Duration) for an explicit socket. The wrapper copies result views into Rust values and releases C results through Drop. Select a matching source revision of timed-client and link the installed shared library; the crate is not a precompiled Rust ABI package.

Subscriptions #

A subscription is owned separately from each returned snapshot. Calls and freeing on one subscription must not overlap. A receive timeout retains partial framing so a later call can continue. Other transport or protocol errors close the stream; create a new subscription explicitly if needed. The Rust wrapper requires mutable access to receive the next snapshot.

Using libtrust

Peios / Developing for Peios / System Service Libraries

libtrust.so.1 provides the public C interface for trustd. The trust-client crate wraps the same shared library and returns owned Rust values. Internal implementation crates do not replace this public boundary.

Operations #

The library reads status and complete root snapshots, subscribes to changes, and requests recomposition. Snapshot chunks must belong to one generation; the library rejects incomplete or mixed-generation results.

Certificate helpers decode, inspect, and vet candidate roots. Decoding or inspecting a certificate does not make it trusted. Other helpers need no daemon: they compute a certificate's SHA-256 fingerprint, convert between DER and PEM, normalize a fingerprint as typed, and resolve a whole fingerprint or an unambiguous prefix of at least eight digits against a list of fingerprints. peios_trust_default_control_security() returns the descriptor trustd checks against when the ControlSecurity value is absent. Management operations add or remove registry entries, record or remove distrust, and configure compatibility output using the caller's own rights. An access probe is not an authority token: the actual operation can still fail.

Registry writes and daemon recomposition are separate operations. Request a reload after management changes when immediate recomposition is required, and handle either operation's error. A failed reload does not roll back a completed registry write.

Linking and ownership #

Include <peios/trust.h> and use the trust pkg-config module. The installed header and libtrust(3) describe individual functions and data layouts. peios_trust_abi_version() returns the ABI major version, 1.

Each operation returns an owned result, including failures. Check peios_trust_result_error() before reading a view, and release the result exactly once with peios_trust_result_free(). Error codes are POSIX numbers; human-readable diagnostic wording is not a stable identifier. Reading the stored error does not set thread-local errno.

peios_trust_result_failure() gives the kind of failure, which is also stable:

ConstantFailure
PEIOS_TRUST_FAILURE_NONEThe operation succeeded
PEIOS_TRUST_FAILURE_OTHERAny other failure, such as an unreachable daemon or an ambiguous prefix
PEIOS_TRUST_FAILURE_DENIEDThe caller's rights refused the change
PEIOS_TRUST_FAILURE_NOT_FOUNDNo such root, addition, distrust entry, or matching fingerprint
PEIOS_TRUST_FAILURE_MALFORMEDThe bytes are not a certificate
PEIOS_TRUST_FAILURE_NOT_A_CAThe certificate is not a certificate authority's
PEIOS_TRUST_FAILURE_EXPIREDThe certificate has expired
PEIOS_TRUST_FAILURE_NO_CERTIFICATEPEM text holds no certificate block

Strings are UTF-8 spans with explicit byte lengths, without terminating NUL bytes. Input spans are borrowed for the call and must remain live, aligned, and initialized. A null pointer with zero length represents absent optional text; a non-null pointer with zero length represents present empty text. Returned strings, arrays, and nested views belong to the result. Copy what you need before freeing it. Handles from another library are not valid here.

Connections and failure #

Each ordinary daemon operation opens its own filesystem Unix socket. The system default is /run/trustd/trust.sock; clients can select another socket for a private service instance or a test.

A positive timeout in milliseconds bounds connection, sending, and receiving together. A full connection queue can fail immediately. A transport error does not establish whether a requested change was applied. The library does not automatically replay operations after an uncertain failure.

Rust access #

Use Client::system(Duration) for the installed daemon or Client::new(path, Duration) for an explicit socket. The wrapper copies result views into Rust values and releases C results through Drop. Its Error carries the POSIX code, the failure's kind as an ErrorKind, and the diagnostic message. The crate also exports the registry key and value names trustd reads, and the certificate Details and Parsed types. Select a matching source revision of trust-client and link the installed shared library; the crate is not a precompiled Rust ABI package.

Subscriptions #

A subscription is owned separately from each returned snapshot. Calls and freeing on one subscription must not overlap. A receive timeout retains partial framing so a later call can continue. Other transport or protocol errors close the stream; create a new subscription explicitly if needed. The Rust wrapper requires mutable access to receive the next snapshot.

Reading Registry Documents

Peios / Developing for Peios / System Service Libraries

Use libreg to read a registry batch document without applying it. This is useful for an importer that shows a document before asking the user to apply its changes.

Before you start #

  • Install matching libreg and libreg-devel packages.
  • Install a C compiler and pkg-config.
  • Supply a UTF-8 JSON document in the registry batch format.

Parse the document #

  1. Include peios/reg.h and create a span containing the JSON bytes. This example uses an empty batch, so it needs no live registry access:

    #include <peios/reg.h>
    #include <stdio.h>
    
    int main(void) {
        const char json[] = "{\"keys\":[]}";
        peios_reg_bytes input = {
            .data = (const uint8_t *)json,
            .len = sizeof(json) - 1,
        };
        peios_reg_document *document = peios_reg_document_parse(input);
        int error = peios_reg_document_error(document);
        if (error == 0) {
            peios_reg_bytes output = peios_reg_document_json(document);
            fwrite(output.data, 1, output.len, stdout);
            putchar('\n');
        }
        peios_reg_document_free(document);
        return error == 0 ? 0 : 1;
    }
    
  2. Save the example as read-document.c, then compile it against the installed library:

    cc read-document.c -o read-document $(pkg-config --cflags --libs reg)
    

Check the result #

Run ./read-document. It prints the empty batch and exits successfully:

{"keys":[]}

The handle owns the returned JSON bytes. The example writes them before freeing the handle. For an application that retains the document in another format, copy those bytes while the handle is still alive.

See libreg(3) for export, apply, errors, and lifetime requirements. Parsing alone doesn't check whether you have permission to apply a document.

Using Cryptography from Rust

Peios / Developing for Peios / Cryptography

Use the peios-crypto crate whenever Peios-authored Rust code needs cryptography. It offers keys, signatures, passphrase sealing for keys at rest, and the building blocks of random bytes, SHA-2 digests and HMAC.

The crate's choices are deliberately limited. You pick from a short list of key types and signature schemes rather than supplying parameters, so a weak or mismatched combination can't be expressed. Secret bytes are wiped from memory when dropped and never appear in Debug output.

Before you start #

  • Add peios-crypto from the peios-rs repository to your Cargo.toml.
  • Handle Error::PolicyRejected. Peios crypto policy can refuse an algorithm on a particular machine. peios-crypto 0.1 doesn't enforce the policy and never returns this error; versions that enforce it keep the same API.

Generate a key and sign #

  1. Generate a key with one of the KeyAlgorithm choices:

    use peios_crypto::{KeyAlgorithm, PrivateKey, Signer};
    
    let key = PrivateKey::generate(KeyAlgorithm::EcdsaP256)?;
    
  2. Sign with the key's default scheme. Each key type has one that suits it, so you don't need to choose a hash or padding:

    let scheme = key.algorithm().default_signature_scheme();
    let signature = key.sign(scheme, b"message")?;
    
  3. Give the public key to whoever verifies, as a DER SubjectPublicKeyInfo:

    let spki = key.public_key().spki();
    

Write code that signs against the Signer trait rather than PrivateKey. A key held in hardware implements the same trait, so the code works unchanged when the key moves out of process memory.

Verify a signature #

Load the public key and verify with the scheme the signer used:

use peios_crypto::{PublicKey, SignatureScheme};

let public = PublicKey::from_spki(&spki)?;
public.verify(SignatureScheme::EcdsaSha256, b"message", &signature)?;

PublicKey::from_spki accepts only the canonical DER encoding of a key type Peios offers. A bare RSA key, a raw EC point or a compressed point is refused with Error::InvalidKey.

Verify a signature made by other software #

Signatures from other software, such as the signature on a certificate request, come in more combinations than Peios makes itself. OpenSSL, for example, signs with SHA-256 whatever the curve. Use VerifyingKey for these:

use peios_crypto::digest::Algorithm as Hash;
use peios_crypto::{VerificationAlgorithm, VerifyingKey};

let key = VerifyingKey::from_spki(&spki)?;
key.verify(VerificationAlgorithm::Ecdsa(Hash::Sha256), message, &signature)?;

VerifyingKey accepts ECDSA P-256 and P-384 keys, with compressed points, and RSA keys from 2048 to 8192 bits. Any SHA-2 hash can be used with either curve. RSA-PSS signatures verify only when their salt is as long as their hash. SHA-1 isn't offered.

A VerifyingKey can only verify. To sign, use a PrivateKey.

Protect a private key at rest #

Seal the key's PKCS #8 encoding under a passphrase, and store the result:

use peios_crypto::{open_with_passphrase, seal_with_passphrase};

let pkcs8 = key.to_pkcs8()?;
let sealed = seal_with_passphrase(pkcs8.expose(), passphrase.expose())?;

To use the key again, open the blob and load it:

let pkcs8 = open_with_passphrase(&sealed, passphrase.expose())?;
let key = PrivateKey::from_pkcs8(pkcs8.expose())?;

Sealing derives a key from the passphrase with Argon2id, using 64 MiB of memory, and encrypts with AES-256-GCM. The work makes each guess of the passphrase expensive, but it can't make a weak passphrase strong. The crate sets no minimum, so check the passphrase's strength in your program before sealing anything valuable, such as a certificate authority's key.

Keep passphrases in a Secret too, as these examples do, so that they're wiped from memory when you're finished with them.

Export a key with its certificates #

To hand a key and its certificate chain to other software, such as a phone or a Windows machine, write them as a PKCS #12 file:

use peios_crypto::pkcs12;

let p12 = pkcs12::write(&key, &certificate, &[&issuer], Some("Jack's iPhone"), passphrase)?;

The file uses the format OpenSSL 3 writes by default: AES-256 encryption under keys derived with PBKDF2-HMAC-SHA256, and an HMAC-SHA256 check over the whole file. Current OpenSSL, Windows 10 version 1709 and later, Firefox, iOS 18 and later, and macOS 15 and later can import it. Older Apple systems need a weaker legacy format, which peios-crypto doesn't write.

The certificate has to be the key's own, and the passphrase can't be empty; otherwise pkcs12::write returns Error::InvalidInput.

Check the result #

Opening a sealed blob with the wrong passphrase fails with Error::WrongPassphraseOrDamaged. That error also covers a blob that was altered or damaged, deliberately: distinguishing the two would help someone guessing passphrases more than it helps you.

See also #

  • Using the SDK from Rust

Using the OpenSSL-Compatible Libraries

Peios / Developing for Peios / Cryptography

Peios provides cryptography and TLS through two libraries with OpenSSL's API: libpcrypto, for cryptography, and libpssl, for TLS. Software written for OpenSSL builds against them with its source unchanged, and Rust crates built on aws-lc-rs, such as rustls, can use them in place of a copy of their own.

Both libraries are built from AWS-LC, Amazon's cryptography library, and provide the API AWS-LC does. They link AWS-LC in and export each function under its OpenSSL name, so that every call a program makes passes through one place where Peios can apply its crypto policy.

For new Rust code written for Peios, use the peios-crypto crate instead; see Using Cryptography from Rust.

Before you start #

  • Build libpcrypto and libpssl from the peios-crypto repository with pekit build pcrypto, and install the tree it gives under /usr. Peios doesn't ship them as a package yet.
  • Install libpeios, which libpcrypto loads to read the machine's crypto policy. A static link needs -lpeios, which pkg-config's --static gives. A cross linker needs -Wl,-rpath-link to the directory holding libpeios.so.0.
  • Install a C compiler and pkg-config.
  • Expect Peios crypto policy to apply to these libraries' callers. The current libraries apply it when a program computes a digest or a MAC (HMAC, CMAC, Poly1305, or SipHash), starts or keys a cipher or an AEAD, derives a key, encrypts or decrypts a private key, PEM file, PKCS #12 file or PKCS #7 message, generates or uses a public key, verifies a signature in a certificate, OCSP response or PKCS #7 message, or finishes a TLS handshake. Data that names its own algorithm, such as an encrypted PKCS #12 file, is checked as it's read, before it's decrypted. Each process applies the machine's crypto policy, which it reads once, at its first call: its floor, which no machine can loosen, its thresholds, and the exceptions granted to the program. See How Crypto Policy Works. Two calls still go straight to AWS-LC: EVP_CIPHER_CTX_set_key_length and EVP_CIPHER_CTX_ctrl, which can change a cipher's key length or parameters after the cipher was checked.
  • Expect TLS to be checked once each handshake has negotiated, before any data is sent or received on it: its version, cipher suite, key-exchange group, keys, signatures, and the peer's certificate chain. If policy refuses any of them, the connection fails with an insufficient_security alert, as if the handshake itself had failed, and every later call on it fails too. A call such as SSL_write that runs the handshake itself checks it before sending anything. TLS 1.3's early data isn't checked: a client sends it before the handshake negotiates anything, using a session that an earlier handshake negotiated.

Build a C program #

  1. Include OpenSSL's headers as usual. This program prints the library's version and the SHA-256 digest of abc:

    #include <stdio.h>
    
    #include <openssl/crypto.h>
    #include <openssl/sha.h>
    
    int main(void) {
        unsigned char digest[SHA256_DIGEST_LENGTH];
        SHA256((const unsigned char *)"abc", 3, digest);
        printf("%s\n", OpenSSL_version(OPENSSL_VERSION));
        for (size_t i = 0; i < sizeof(digest); i++) {
            printf("%02x", digest[i]);
        }
        printf("\n");
        return 0;
    }
    
  2. Save it as digest.c, and compile it with the flags pkg-config gives for libcrypto:

    cc -o digest digest.c $(pkg-config --cflags --libs libcrypto)
    

    For a program that uses TLS, ask for openssl instead, which gives both libraries.

A build that links -lssl -lcrypto without asking pkg-config works too: libssl.so and libcrypto.so lead to libpssl and libpcrypto.

Check the result #

Run the program:

./digest

It prints AWS-LC's version and the digest:

AWS-LC 5.15.0
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad

Build a Rust crate that uses aws-lc-rs #

aws-lc-rs normally compiles its own copy of AWS-LC. Set AWS_LC_SYS_SYSTEM_DIR when you build, and it uses libpcrypto instead:

AWS_LC_SYS_SYSTEM_DIR=/usr cargo build

aws-lc-rs reads the Rust bindings that libpcrypto installs at /usr/share/rust/aws_lc_bindings.rs, and links libcrypto.so. The program it builds loads libpcrypto when it runs, and contains no AWS-LC of its own.

Differences from OpenSSL #

AWS-LC provides OpenSSL 1.1.1's API, with some of OpenSSL 3's functions, not all of OpenSSL 3. Expect to change a program that needs:

  • OpenSSL 3's providers, or engines loaded by name. AWS-LC has no providers, and its algorithms are built in. Its ENGINE can only stand in for RSA and EC key operations, with methods the program supplies.
  • A newer OpenSSL version. libpcrypto reports version 1.1.1 to pkg-config and in OPENSSL_VERSION_NUMBER, so a build that insists on OpenSSL 3 refuses it.
  • Elliptic curves of your own. A key on a curve given by its parameters is accepted only if the curve is one of the named curves AWS-LC provides, such as P-256; any other curve is refused.
  • PKCS12_create's defaults. AWS-LC encrypts a PKCS #12 file's certificates with 40-bit RC2 unless told otherwise, and Peios crypto policy refuses it. Pass -1 as cert_nid to leave the certificates, which are public, unencrypted. Files that other software encrypted this way still read.

AWS-LC's porting documents, in its repository's docs/porting directory, list the functions it leaves out and those that behave differently.

A call that Peios crypto policy refuses fails as any failed OpenSSL call does, and leaves an error on the thread's error queue whose library is ERR_LIB_USER and whose reason is 1000. Reading the policy and reporting to cryptod leave errno as they found it.

A few functions can't report failure, or have callers that never check: the low-level digest functions, such as SHA256 and MD5_Init, the low-level cipher keying functions, such as AES_set_encrypt_key, and Poly1305's and SipHash's. When policy refuses one of those, the program ends with a message naming the function, rather than carry on with a digest or key that was never computed. Use the EVP_ functions where a refusal should be handled.

The libraries export only the API AWS-LC's headers declare. Functions AWS-LC exports only for its own tests, such as its ML-KEM internals, aren't available. Use only OpenSSL's names: libpcrypto also exports names beginning peios_awslc_, which libpssl uses internally. They aren't part of the API, and a program that calls them won't pass Peios crypto policy.

The GXWI Application Model

Peios / Developing for Peios / GXWI Applications

A GXWI application runs on the Peios machine and presents surfaces through the desktop. It connects to the display named by GXWI_DISPLAY; it does not expose an independent public listening port.

Three layers #

The SDK has distinct responsibilities:

LayerResponsibility
libgxwi.soC interface for desktop connections and surface requests
Rust gxwi crateApplication HTTP service, rendering, and settings helpers
CompositorDesktop layout, browser presentation, and shell authorization

Use the C interface when integrating another language or a custom runtime. Use the Rust rendering layer for process-owned HTML surfaces. The shared library does not implement the Rust rendering helpers.

State belongs to the application #

A live surface owns its application state and named input fields in the process. Browsers receive renderings of that state. Multiple browsers can interact with the same surface, and reconnecting browsers receive its latest state.

This is not automatic persistence across application failure or session shutdown. Save durable data explicitly. Keep focus, viewport geometry, and other device-specific presentation out of shared application state.

Surfaces and requests #

An application can present windows and dialogs. Shell programs can also use panels, backgrounds, and overlay surfaces where the compositor permits those roles. Merely requesting a role or obtaining an SDK shell handle does not grant shell authority.

Closing a live surface is a request to the application. The application can ask about unsaved work before allowing the close. Closing the last surface ends the application's desktop loop.

Trust the operation, not the markup #

Treat events and field values as untrusted input. Validate actions in the process and rely on the backend's authorization checks. Escape untrusted text before placing it in HTML. The Rust escape helper handles text escaping; it does not validate URLs or authorize operations.

Launching files #

Application::command returns a result when adding a file argument. The desktop startup protocol carries UTF-8 text, so a native filename that is not valid UTF-8 cannot be represented in that request. The SDK returns an error instead of replacing bytes and opening a different path. Show the error and keep the original native path intact.

Application declarations #

The application catalog accepts regular declaration files up to 64 KiB. It checks the opened descriptor and bounds the actual read, so a file that grows beyond the limit is rejected. A declaration at the exact limit is accepted if its content is valid. Special files are not declarations.

Executable icon probes also require an opened regular file. These checks prevent catalog discovery from treating a pipe or device as a normal file. They do not replace validation of the declaration's fields.

Live Surfaces and Input

Peios / Developing for Peios / GXWI Applications

Implement the Rust Live trait to draw a surface from application state. render returns HTML. event handles named actions, input responds to field changes, and closing decides whether a close request can proceed.

Rendering and actions #

App::live creates a window and returns a Surface handle. Use Surface::update to change state from a worker and request another render. Use Surface::look to inspect the application, fields, and surface facts under their shared state lock.

An element's fx-click attribute names an action. Attributes beginning with fx-value- provide action data. A form with fx-submit names its submission action. The browser protocol is implemented by the compositor; adding arbitrary HTML event attributes does not create a Rust callback.

Keep rendering free of irreversible effects. A browser reconnect or field change can cause another render. Put effects in explicit action handlers and background operations.

Named fields #

Fields stores values for named inputs. Fields::get returns an empty string for an absent field. Fields::set changes a field from the process and updates connected views, including a view editing that field.

The browser input path accepts at most 256 fields. Each value is limited to 1 MiB, their total to 4 MiB, and each name to 256 bytes. These are transport limits, not application-specific validation rules. Validate lengths and formats required by the operation itself.

Do not use the field transport for files larger than its limits. A custom bounded HTTP route can serve a different data-transfer requirement.

Shared edits #

Multiple views share field values. They do not form an independent draft per browser. Design conflict-sensitive operations around explicit state, revisions, or confirmation rather than assuming only one viewer edits a surface.

The surface state lock serializes its callbacks. Avoid blocking operations inside rendering or a callback that must keep the interface responsive. Move long work to a worker and publish progress through the surface handle.

Closing #

Return false from closing to keep a surface while asking about unsaved work. Once the user confirms, use the surface or closer handle to close it. A process failure or ended desktop session is not an interactive close request, so save durable data independently of this callback.

Building a Settings Application

Peios / Developing for Peios / GXWI Applications

The Rust gxwi::settings module builds settings interfaces from HTML helpers. It supplies layout and controls; your application owns state, validation, backend calls, and authorization.

Before you start #

Create an application using App and implement Live for its page state. Choose the backend operation and permissions each control needs. Use the SDK's checked example and Rust API documentation for complete signatures.

Build the page #

  1. Register settings::stylesheet with the application before adding your own stylesheet.
  2. Choose settings::window for a page with navigation or settings::single for one section without navigation.
  3. Build navigation with stable section identifiers. Handle the section event by validating the requested identifier and selecting its page.
  4. Assemble controls with settings helpers and named fields. Escape text that comes from users, files, or services before embedding it in HTML.
  5. Show the effective backend state and an actionable error when an operation fails.

The kit adapts navigation to narrow views. It does not require the process to track a browser's viewport.

Apply changes deliberately #

Use immediate application for controls such as a switch when the operation is reversible and failure can be shown clearly. Restore the displayed field if the backend refuses the change.

Use an explicit Apply action for a group of typed values that must be validated together. Validate the complete proposed state before submitting it. Rendering a success message before the backend accepts the operation misrepresents the effective configuration.

For a destructive operation, ask for confirmation and focus the safe choice. A confirmation is not authorization: the backend still checks the caller's rights.

Verify the result #

Exercise successful changes, refused access, invalid values, and backend failure. Open the same surface in two browser views and check that both reflect accepted state. Verify keyboard operation and a narrow viewport.

Custom HTTP Pages

Peios / Developing for Peios / GXWI Applications

Use a custom HTTP page when a live surface cannot represent the interface, such as a terminal renderer. The application still serves through the desktop's connection; it does not need its own public network listener.

Routes and resources #

App::routes adds application HTTP routes. App::file serves a resource, and App::stylesheet registers a stylesheet for live surfaces. Paths are relative to the application's routing space. Do not assume that the application owns the browser's root path.

App::raw_page presents a scripted page. The compositor keeps that page apart from other applications. Its browser-owned state does not automatically reach another device or survive a tab being closed.

Isolation and keyboard access #

A raw page has no ordinary access to the desktop's cookies or browser storage. Worker code uses a blob where required by the isolated page's origin. Do not use the absence of storage as a substitute for validating requests in the application.

Include the compositor's key-forwarding module from .fx/keys.js within the application's path space. Without it, desktop keyboard shortcuts can be unavailable while focus is inside the page. The SDK's hello raw-page example demonstrates the expected resource layout.

Lifecycle #

Closing a raw window allows it to close without the live surface's closing decision. Keep important state in the process and implement an explicit save or stop flow where the interface requires it.

Limit request bodies, pending work, and output queues according to the application's needs. The shared transport cannot choose an appropriate memory or cancellation policy for every application protocol.

The C Client Lifecycle

Peios / Developing for Peios / GXWI Applications

libgxwi.so.1 exposes the desktop control interface to C and other languages with a C foreign-function interface. Include peios/gxwi.h and link with libgxwi. The header and libgxwi(3) define exact types, function signatures, errors, and concurrency requirements.

Connect and serve #

peios_gxwi_connect uses GXWI_DISPLAY and returns an owned opaque display handle. The library sets Identification before connecting. It does not adopt arbitrary caller-supplied display descriptors.

peios_gxwi_serve transfers one end of a socket to the desktop and returns the other as a close-on-exec descriptor. Your application owns that descriptor and serves HTTP/2 on it. Start serving before asking the desktop to present routes from that connection.

Create live or raw surfaces with application-chosen identifiers. The C library sends the surface description; it does not implement rendering, HTTP handling, or the live-surface WebSocket protocol for you. The Rust gxwi framework supplies those higher layers.

Receive and release events #

peios_gxwi_receive blocks and returns one of three results:

ResultMeaning
1An independently owned event is available
0End of file, with a null event output
-1Failure reported through errno

Inspect an event's kind before using its typed getters. A close event identifies an application surface. A surface-list event describes the desktop surfaces visible to an authorized shell connection. Unknown or malformed messages become PEIOS_GXWI_EVENT_OTHER. Truncated packet data or descriptor control data also produces that event rather than a parsed partial message.

Destroy each event after use. Text returned by an event getter borrows storage from that event and becomes invalid when the event is destroyed. An event remains valid after its display handle is destroyed.

Text and output ownership #

Text is UTF-8 with explicit byte lengths. No NUL terminator is required, and embedded NUL bytes are supported. A null pointer is valid for an empty span or array, not a nonempty one.

Input storage is borrowed only for the duration of the call. Output parameters remain unchanged on failure. Supply writable outputs that do not alias inputs. The library cannot make an invalid non-null pointer safe.

Shutdown and concurrent calls #

Display operations can run concurrently. Concurrent receivers consume different packets without a promised completion order. Use one receiver when your application requires a single ordered event-processing loop.

peios_gxwi_stop_listening wakes receivers with end of file and leaves sending available. Wait until all calls using a display finish before destroying it. Events can be read concurrently, but destruction cannot race a reader.

Shell authority #

Program startup, desktop-surface close, and sign-out calls send requests. Successful transmission does not acknowledge that the desktop accepted or completed the action. The compositor decides whether the connection has shell authority. Observe subsequent desktop state rather than inventing a completion guarantee.

Interaction Markup

Peios / Developing for Peios / GXWI Applications

Live-surface HTML describes actions for the compositor to dispatch. Attributes do not replace validation in the application. The Rust Live API documentation gives the complete markup contract.

Actions and forms #

The common action attributes serve these purposes:

AttributePurpose
fx-clickNamed activation action
fx-dblclickNamed repeated activation action
fx-value-*Values associated with an action
fx-submitNamed form submission action
fx-autofocusFocus target when a control appears
fx-keySurface-local keyboard activation

Named input fields belong to the surface. Validate form and action values in the process before calling a backend. Escape text when generating HTML attributes as well as element content.

Keyboard and menus #

A keyboard chord uses modifiers such as Ctrl, Alt, Shift, and Meta with a key name. Field-editing shortcuts remain field operations where appropriate. The desktop reserves its own chords, so an application cannot assume every chord reaches its handler.

fx-menu identifies a hidden menu element. Its action items provide labels and values; the compositor presents the menu. A disabled item cannot be selected through the normal interface, but its handler must still enforce operation validity and access.

Device-local presentation #

fx-copy copies the named value to the activating device's clipboard. This is distinct from an application-owned clipboard shared through a session file or service.

fx-columns lets a view resize columns. fx-reorder reports a requested reordering with a destination position. The next process rendering remains the authority for the accepted application order.

Shell presentation #

Authorized shell surfaces can describe desktop focus, workspace, and overlay actions. fx-focus, fx-workspace, and fx-overlay affect the presenting device where the compositor implements them. They do not make focus into shared process state.

fx-global-key names a desktop-wide chord for a shell control. Requesting that attribute does not make an ordinary application a shell. The compositor determines which program connections have that authority.

GXWI Process Boundaries

Peios / Developing for Peios / GXWI Architecture

GXWI separates privileged machine operations from network parsing. gxwid owns the listener, certificate state, authentication connections, and session jobs. gxwi-server handles browser traffic with a restricted token and descriptors supplied by the daemon.

Browser to desktop #

The network worker accepts TLS and HTTP requests. It communicates with the daemon over private channels for authentication and overlay state. The daemon starts session jobs with the access token returned by authd.

A compositor receives a session socket and serves HTTP/2 over it. The network worker forwards requests for the authenticated browser session to that connection. The compositor then routes desktop and application requests inside the session.

The externally served protocol and internal transport differ. Browser connections use HTTP/1.1 over TLS. The worker-to-session connection uses HTTP/2 over a local socket.

Session credentials #

The network worker owns its session cookies. It strips GXWI authentication cookies before forwarding requests to a session and prevents application responses from replacing them. A compositor or application does not need the browser's session cookie to serve its connection.

The worker also keeps application-origin routing separate from ordinary session paths. Application-provided labels do not establish another application's authority.

Failure boundaries #

The daemon restarts a failed network worker with a bounded retry delay. Keeping the listener and desktop jobs outside that worker allows them to outlive its failure. This does not make in-flight browser requests transactional or preserve the worker's in-memory cookie table.

Session startup waits for the compositor to accept its connection within 10 seconds. A program that cannot become ready fails startup rather than leaving authentication waiting indefinitely.

Restricted and development execution #

Normal execution relies on Peios access tokens, registry access control, authd, peinit jobs, and local token transfer. A host-only unrestricted run omits those security mechanisms. It can exercise HTTP and browser code, but it cannot qualify native authentication or sandbox behavior.

The Session Environment

Peios / Developing for Peios / GXWI Architecture

GXWI starts a compositor with environment values chosen for the authenticated principal. Those values describe the session, not the browser device that happens to display it.

Identity and runtime #

The session receives these values:

ValuePurpose
HOMEHome directory from the account profile
SHELLAccount shell
PATHProgram search path for the session
GXWI_RUNTIME_DIRSession runtime directory
GXWI_DISPLAY_NAMEDisplay label from the first logon profile

The compositor exposes GXWI_DISPLAY to applications it starts. An application should connect to that display rather than guessing a socket path. The session runtime directory and socket are not public network addresses.

Locale #

GXWI reads machine locale settings and the authenticated user's locale preferences before starting the session. It clears inherited locale overrides and falls back to C.UTF-8 where needed.

Rejoining an existing session does not restart its processes or replace their environment. Changes to locale, home, display label, or shell apply when another session is created, according to the relevant service policy.

Separate overlay runtime #

A machine overlay receives its own runtime and job. It is not the overlay account's ordinary desktop session. Its lifecycle follows the configured overlay rather than a browser visitor's sign-in.

Fenesh Implementation Boundaries

Peios / Developing for Peios / GXWI Architecture

Fenesh is a Rust application built on the gxwi crate. It renders shell surfaces and companion windows, while the desktop service and compositor provide session transport, authorization, and window management.

Source layout #

The implementation separates shell state from companion applications:

SourceResponsibility
src/main.rsConnect the shell, register surfaces, and wire shared state
src/dock.rs and src/launcher.rsApplication selection, window actions, and pins
src/settings.rs, src/looks.rs, and src/pinned.rsRead settings, resolve defaults, and maintain shell state
src/watch.rsFollow registry notifications and refresh settings
src/wallpaper.rsValidate image paths and bound reads shared by the shell and Settings
src/topbar.rs, src/person.rs, and src/power.rsClock, display identity, and session or power controls
src/welcome.rsFirst-session welcome attempt and marker
src/bin/fenesh-welcome.rsGet started application
src/bin/fenesh-settings/Settings controls, validation, and registry writes

The source repository contains these files and the manual pages under docs/man. docs/fenesh.regman owns the Fenesh registry reference. Build and contributor instructions live in docs/building.md, outside the published Learn tree.

Authority and untrusted input #

Fenesh runs with the desktop account's identity. Its shell role comes from Fenestra's configuration, not from a user-interface claim. Launcher and dock events resolve application IDs against the catalog before asking the desktop to start a program. Display names provide presentation only; they are not an authorization decision.

The shared wallpaper loader opens paths without waiting on named pipes and accepts only regular files, including symlinks to regular files. It checks the opened object before reading, then bounds the read to 16 MiB plus one byte for detecting overflow. It rejects oversized content, including growth after the metadata check. File extensions select the content type; this is not image decoding or sanitization.

Gallery image URLs encode each filename as one path segment before HTML attribute escaping. Spaces, non-ASCII text, and characters such as #, ?, and % remain part of the filename instead of changing the URL.

Desktop Settings tests registry access through the registry API. It does not infer write access from group names. Writes for a single key use a transaction. Advanced changes across GXWI and Fenestra keys use separate transactions, so a later failure can leave an earlier key changed.

The power menu asks the session service to end the session and asks peinit to restart or power off the machine. Those services retain the authority to accept or refuse the request. The shell shows a refusal rather than presenting the action as completed.

Updates and defaults #

Personal settings take precedence over machine defaults where the setting supports them. Registry watchers follow the nearest existing ancestor so a missing settings key can be created later. A failed watch stops that watcher and reports the failure; it does not silently poll as a fallback. Desktop Settings separately polls every four seconds to refresh controls.

Wallpaper refresh compares the selected path, file size, and modification time after a registry notification. It does not monitor the image file. Clock and pin updates share state across shell surfaces. Focus and overlay visibility belong to each connected display, so one display's focus does not need to match another's.

The first-session marker records that the automatic welcome launch was attempted. It does not prove that the user saw or completed the window.

Fenestra Implementation Boundaries

Peios / Developing for Peios / GXWI Architecture

Fenestra separates session state from browser layout. The Rust process owns application connections and surfaces. Each desktop page receives that state and applies its window manager locally.

Source layout #

The implementation assigns these responsibilities:

SourceResponsibility
src/main.rsInherited listener, session startup, and compositor routes
src/apps.rs and src/apps/shell_child.rsApplication transport, shell supervision, and peer checks
src/surface.rsSurface ownership, workspace assignments, and changes
src/desktop.rsBrowser snapshots, requests, and session termination
src/forward.rsForward application HTTP and WebSocket traffic
src/live.rsServe the shared live-page runtime and icons
src/settings.rsRead and validate the shell selection
page/fenestra.js and page/wm/tiling.jsBrowser composition and local window layout
page/sdk.js and page/keys.jsLive application interaction and raw-page keyboard forwarding
src/bin/Companion taskbar and launcher

The source repository contains the implementation and its tests. Contributor instructions belong in docs/building.md; installed references belong in docs/man and docs/fenestra.regman.

Session and application boundaries #

GXWI passes a listening descriptor to Fenestra and controls access to it. Fenestra restamps the listener to the session identity. The compositor assumes that incoming session traffic has passed GXWI's authentication and routing boundary; it is not a standalone public web server.

Application connections use a Unix sequenced-packet socket in the session runtime directory. Fenestra compares the connecting account's security identifier with its own and obtains the process identity from the kernel. Shell authority is assigned only to a tracked configured child connection. Requesting a panel, background, or dialog role does not itself confer shell authority. Reaping a shell child and revoking its tracked process ID share the same admission lock, so a recycled ID cannot retain that authority.

The application supplies an HTTP/2 connection for its content. Fenestra associates it with that application connection and a generated origin label. GXWI's origin routing keeps pages separated. Fenestra strips cookies from forwarded requests and Set-Cookie from application responses. Application-origin requests cannot fall through to compositor routes.

These rules rely on the kernel, GXWI, and browser protections as well as Fenestra. Host unit tests do not establish that those boundaries work in an installed Peios session.

Live and raw pages #

A live surface uses Fenestra's page runtime to display content from the application process and return user actions. Its content security policy permits the runtime script through a response-specific nonce. The application's own scripts are not part of that live-page execution model.

A raw surface serves the application's page and scripts. Its state can be local to one browser page. The shared keyboard-forwarding helper allows that page to participate in desktop shortcuts. Fenestra treats messages from a frame according to the surface and its shell authority.

Resource bounds and failure handling #

An application connection can create at most 64 simultaneous surfaces. Application messages are limited to 64 KiB, and titles are retained up to 128 characters. A truncated application message closes the connection and removes its surfaces.

Surface resource paths start with a single /, exclude the reserved /.fx/ prefix, and fit a total limit of 1024 UTF-8 bytes. Fenestra rejects ASCII control characters anywhere in the supplied path. In the pathname before the first ? or #, it also rejects literal backslashes and segments that browsers interpret as . or ... This includes case-insensitive %2e dots and combinations of literal and encoded dots.

Unicode names, ordinary spaces, query strings, and fragments are retained. Dots or backslashes in a query or fragment do not count as pathname traversal. The check does not recursively decode percent escapes or reject dots within longer names. A rejected resource path prevents the surface from being created and is reported without closing the app connection.

Workspace selection, renumbering, moves, and initial surface placement share one session-state lock. Concurrent browser pages cannot split those updates across inconsistent workspace states.

The desktop has up to 16 workspaces. Its change channel retains 256 messages; a lagging browser reconnects for a snapshot. A shell is sent a complete surface list on each change, so a later successful update repairs a missed list. A failed send is reported rather than treated as delivery.

Closing a surface requests cooperation from the application. Fenestra does not claim that a close request has saved work or forced a process to exit. Disconnecting the application removes its surfaces and releases their compositor state.

Animation lifetime #

The arrival animation releases its resize listener when it finishes. A canceled departure animation stops its frame loop, cancels pending timers, aborts its availability request, and releases its resize listener. Each attempt has a generation marker, so callbacks from an earlier attempt cannot update a later attempt's state or redirect its page.

A shell announcement can arrive while the compositor page is checking an address after its socket closes. The page rechecks departure ownership when that probe completes, so the active departure receives the closure instead of starting a competing reconnect path.

Writing regman Pages

Peios / Developing for Peios / Documenting Configuration

Ship a .regman fragment with your component so an operator can look up its registry keys and values with regman. Keep the fragment beside the code that reads those values, and update both together.

Before you start #

  • Install regman from Peiosutils.
  • Identify the keys your component owns and the values it reads.
  • Follow regman and evman prose style.

Document another component's key by referring to its full path in your record's body. Do not publish a second definition of that key.

Write a fragment #

  1. Create a file named for your component, such as exampled.regman.
  2. Add a key record explaining the subtree, then a record for each value.
  3. Write a standalone summary as the first nonempty body line. Explain the effect, trade-offs, dependencies, and unusual cases in the remaining body.

This example describes an illustrative spooler and its queue limit:

--- machine\system\exampled
canonical: Machine\System\Exampled

Tuning parameters for the Exampled spooler.

--- machine\system\exampled maxqueuedepth
canonical: Machine\System\Exampled MaxQueueDepth
type: REG_DWORD
default: 1024
valid: 16–65536
applies: restart

Maximum number of jobs held in the spool queue before submissions are rejected.

Increase the limit to absorb longer bursts. Each queued job consumes memory.
The spooler reads this value when it starts.

The fence starts a record. Header lines continue until the first blank line, and the body continues until the next fence. canonical supplies the human-readable registry path and, for a value, its name after a space. regman fmt derives the anchor from this header through Unicode simple case folding. Do not maintain the folded anchor by hand.

A record with any type, default, valid, or applies header is a value record. Supply all four for a useful value description. A record without those headers describes a key. deprecated adds a deprecation notice; explain the replacement and its limitations in the body.

Header names are case-insensitive, and surrounding whitespace is trimmed. Unknown headers are ignored, so a typo can silently remove information. A record without canonical is invalid and cannot provide a lookup result. Check the rendered record as well as the lint result.

Format and check #

  1. Format and lint the fragment:

    regman fmt exampled.regman
    regman lint exampled.regman
    
  2. Preview it from the directory containing only the fragments under review:

    REGMAN_DIR="$PWD" regman 'Machine\System\Exampled'
    REGMAN_DIR="$PWD" regman 'Machine\System\Exampled' MaxQueueDepth
    
  3. Compare every header with the implementation. Confirm the allowed type, bounds, behavior when absent, and point at which a changed value takes effect.

Formatting updates anchors without rewriting the body, preamble, or line endings. Running it twice should produce the same file. Lint checks record structure and anchors; it cannot prove that the program implements the prose.

default describes the component's behavior, not the value on the machine running regman. Use live, restart, or reboot for applies, with a short parenthetical qualification when needed.

Package the fragment #

  1. Include exampled.regman in the package payload as usr/share/regman/exampled.regman.
  2. Install it with the component that owns the documented keys.
  3. Check the installed lookup before releasing the package.

The filename stem identifies the provider in lookup results. Installation requires no registration hook. An absent documentation directory means no fragments, not a broken registry. If an installation mechanism replaces files in place, use atomic replacement so readers do not see a partial fragment.

An index is an optional lookup optimization. The reader can scan fragments when the index is absent, stale, or invalid. Do not make correctness depend on generating an index during installation.

Check the result #

The key lookup shows the subtree summary and its values. The value lookup shows its headers and body under the expected provider. A second provider for the same record indicates overlapping ownership; resolve that overlap before shipping.

For dynamic names, use Registry Documentation Patterns.

Registry Documentation Patterns

Peios / Developing for Peios / Documenting Configuration

Registry documentation patterns describe families of keys without publishing one record for every instance. Use a pattern only where the implementation accepts dynamic names; a literal record makes a fixed name easier to verify.

Match dynamic names #

In a canonical path, <name> matches one path component. <name...> matches one or more components separated by backslashes. The label inside the brackets explains the role to a reader; it does not constrain the matched text. Neither pattern matches a space. The format has no escape for a literal name that itself has this placeholder shape.

For example, Machine\Software\Example\Profiles\<profile> describes one profile key. A pattern ending in <path...> also reaches its descendants. Use the narrower form when the documented behavior applies to one level.

Literal matches take precedence over patterns. Among patterns, more specific matches take precedence over broader ones. Key and value lookup remain separate: a matching key record does not define all its values.

Dots do not split registry components. A value pattern such as Local.<op> can match Local.User.Equal as well as Local.Equal. If those names have different meanings, document the operators explicitly instead of relying on placeholder labels to separate them.

Overlapping records from different providers remain visible. Provider order is not a mechanism for overriding another package's documentation.

Write terminal prose #

Use paragraphs, headings, bullet lists, bold, and code spans. The renderer rewraps paragraphs to terminal width. Follow the shared prose style and avoid relying on emphasis styling that a plain-text terminal cannot represent. Unmatched markup remains literal; whitespace inside an emphasis marker can prevent it from being recognized.

A line beginning with --- starts another record, even in body text. Use *** or ___ for a horizontal separator if one is needed. Keep examples of record fences out of a fragment's prose.

Piped output and NO_COLOR suppress terminal styling. Review both styled and plain output when presentation carries meaning. State a warning in words; color alone cannot communicate it.

Keep format and meaning separate #

Headers such as access or since do not extend the parser's schema. Put required access and relevant constraints in the body, and omit historical narrative. Unknown headers being ignored does not make them supported.

Regman does not read the live registry to validate a documented default or range. Review those claims against the consuming code, including how that code handles a missing or malformed value.

Writing evman Pages

Peios / Developing for Peios / Documenting Events

Ship an .evman fragment with each component that emits events. The fragment defines its event types and fields so operators and consumers can interpret the stream. The event catalog specification owns the format and its requirements.

Before you start #

  • Install evman from Peiosutils.
  • Identify the event types, tiers, and fields your component emits.
  • Obtain the catalog fragments that define the fields your events reference.
  • Follow regman and evman prose style.

Choose field definitions #

  1. Search the existing vocabulary before defining a field:

    evman object.file
    evman -k snapshot
    
  2. Reuse a field when its meaning fits. Define a package-owned field under its role and package name only when the shared vocabulary lacks that meaning.

  3. Keep each definition in its owning component's fragment. Other fragments carry the field by reference rather than defining it again.

A --- field record defines a field. A field: line in an event describes its presence in that event. Two definitions of one field are an error. Related fields can be collected in a group record with include: lines; an event can then include the group.

Describe an event #

Create org.example.backup.evman for this illustrative backup component:

--- field object.org.example.backup.snapshot.id
type: bin.guid

The snapshot an event concerns, by the GUID the backup tool assigned it.
Stable for the life of the snapshot, including verification and deletion.

--- event org.example.backup.snapshot.created
tier: standard

A snapshot was written, or an attempt to write one failed.

field: object.kind                            required
  Always `file`.
field: object.file.path                       required
  The snapshot archive.
field: object.file.size                       when outcome.success == true
field: object.org.example.backup.snapshot.id  required
field: operation.duration                     required
field: outcome.success                        required
field: outcome.reason                         when outcome.success == false
  values: disk-full | source-unreadable | cancelled
  closed: false
  Why the snapshot was not written.
field: outcome.errno                          optional

The first sentence of each body is its summary. Explain when an event is emitted, when it is not, and how to interpret its fields. Use **bold** and code spans for emphasis and literal names.

Presence is required, optional, or when followed by a condition. An indented paragraph after a field is its event-specific explanation. That explanation can narrow the general definition but cannot contradict it. Use gating to describe selection of occurrences and cardinality when one occurrence produces multiple records; follow the specification for the full header set, including asserted and carried.

Enumeration definitions declare values and closed. String enumeration values use kebab case. Integer enumerations pair each number with its display name, such as 0 None | 512 Protected. Event-specific enumerations, including outcome.reason, declare their values on the event's field entry.

Set closed: true only when consumers can rely on the set being complete. Check the emitted values against the declaration; a parser cannot establish that runtime behavior matches the catalog.

Validate and preview #

  1. Create a disposable directory and copy the candidate fragment plus the fragments it references into it. Include kernel.evman for the shared fields in this example. Do not also copy an installed version of your candidate fragment.

    preview_dir=$(mktemp -d)
    cp /usr/share/evman/kernel.evman "$preview_dir/"
    cp org.example.backup.evman "$preview_dir/"
    
  2. Check the combined definitions and inspect the event:

    evman lint "$preview_dir"/*.evman
    EVMAN_DIR="$preview_dir" evman org.example.backup.snapshot.created
    rm -r -- "$preview_dir"
    
  3. Repeat lint against the full intended package set before release, replacing the installed version of your fragment with the candidate. This catches duplicate definitions and incompatible names across components.

A successful lint run prints no findings. Findings identify the file, line, and catalog rule. Lint checks the declared catalog; separately test actual events for presence conditions, value ranges, tiers, and emission behavior.

Package the fragment #

Include the fragment at usr/share/evman/org.example.backup.evman in the component's package payload. No central registration or installation hook is needed. Removing the package removes its fragment.

The package owns the definitions throughout their lifetime. Renaming or changing their meaning can affect filters and consumers; review such changes against the event specification before publishing them.

Writing a Feature

Peios / Developing for Peios / Writing Features

A feature gives feat a repeatable way to configure installed software. Its package supplies scripts and metadata; the operator decides when to install, turn on, turn off, or uninstall that configuration.

Before you start #

  • Install feat and the tools your scripts call.
  • Identify the state each phase changes and how to recover from a partial run.
  • Arrange a disposable Peios test environment with the required permissions.

Define the feature #

  1. Choose a name containing only ASCII letters, digits, dots, underscores, and hyphens. It must be one path component and cannot be . or ...

  2. Stage a directory at usr/libexec/features/<name> in the package. The runtime view is /libexec/features/<name>.

  3. Add the applicable scripts and make them executable:

    ScriptPurpose
    install.shPrepare the feature's persistent configuration
    enable.shMake the prepared feature active
    disable.shStop using the feature while retaining prepared state
    uninstall.shRemove the feature's configuration

A missing phase script is a successful no-op. Do not omit a script if that would leave state that the reverse phase needs to remove. Each script needs a shebang naming an interpreter available in its execution environment.

Make phases repeatable #

feat executes each script directly, with its working directory set to the feature directory. FEAT_NAME, FEAT_DIR, and FEAT_PHASE identify the invocation. Scripts run with the caller's authority; feat does not grant them extra privileges.

A failed phase can leave some of its changes applied. A retry starts the script again, and feat does not roll back those earlier changes. Check the existing state before each operation and tolerate already completed work. Reverse phases also need to handle partially completed forward phases.

Keep output brief and identify the operation that is progressing. Write errors to standard error and return a nonzero status on failure. A failed or interrupted phase is not a completed transition.

In driven operation, standard input is closed and output is forwarded from both streams. Do not require interactive prompts. In ordinary operation, scripts inherit the terminal streams, but the same noninteractive contract keeps the feature usable through graphical clients.

Add descriptive metadata #

Create an optional feature.toml beside the scripts:

title = "Example Service"
description = """
Prepares the Example service and makes it available at boot.
Turning the feature off retains its configuration.
"""

The title falls back to the directory name. The description can contain paragraphs. Unknown keys do not run code or add lifecycle behavior. Invalid metadata produces a warning without making the feature disappear from the list, so check its presentation before shipping.

Package and check #

  1. Include the directory, metadata, and executable scripts in the package. A feat-<name> package name is a convention, not the runtime lookup key.
  2. Declare dependencies on feat, the script interpreters, and invoked tools.
  3. In the disposable environment, exercise the lifecycle and repeat each applicable phase. Inject failures between operations and verify recovery.
  4. Check that turning the feature off and uninstalling it also work after a partial attempt.

Installing the package makes the feature available; it does not activate the feature. For operator commands and state handling, see Managing Features.

Identity and Service Adapters

Peios / Developing for Peios / Porting Software

A familiar library interface does not imply the same configuration source as another Linux distribution. Peios connects account lookup, hostname lookup, and certificate trust to their owning services.

Account lookup and authentication #

The authd NSS adapter translates POSIX account queries into the authority's identity protocol. Peios' libc package fixes the account providers; it does not use an /etc/passwd fallback or an independently configured source order. Shadow queries do not expose credential verifiers.

UID 0 is the numeric projection of SYSTEM, not an account named root that must be looked up before boot can proceed. Native authorization uses tokens and security identifiers. A numeric name-service record is a compatibility view rather than the complete security state.

Authentication uses authd conversations. Applications integrate with that interface instead of configuring a PAM stack. Account lookup and credential verification remain separate operations.

Hostname lookup #

The network name-service provider sends hostname queries to resolvd. Static names and resolver policy belong to that service's configuration. Editing a separate /etc/hosts file or a files dns provider chain does not configure Peios' fixed host lookup path.

This does not make every libc database fixed. Consult the libc package for databases outside the account and hostname integration before assuming the same behavior.

Certificate trust #

trustd combines supplied certificate roots with machine trust decisions and produces the compatibility files consumed by TLS libraries. Those files are generated output, even where their paths match another distribution.

Use the trust service's supported configuration for an enduring change. Adding a certificate directly to a generated file can be undone by the next refresh. Permission to modify trust policy is separate from permission to read the resulting certificate bundle.

Porting Identity and IPC

Peios / Developing for Peios / Porting Software

Review authority decisions separately from compatibility display. Peios exposes Linux UIDs, GIDs, mode bits, and capability interfaces so programs can operate, but those values do not describe the full security token or descriptor.

Replace credential assumptions #

Do not authorize a request solely because geteuid() or SO_PEERCRED reports zero. A numeric projection omits claims, groups, privileges, restrictions, impersonation level, and process trust. Cosmetic credentials can also differ from the token. Name-service lookup helps display identities; it does not create or authenticate them.

Do not treat successful setuid() as a privilege drop. Without the relevant Peios privilege it is a silent no-op; the privileged identity-swap path is unimplemented and fails. Setuid-bit exec has different cosmetic behavior. Use a correctly scoped service token or the supported token API, and verify the effective identity. The setuid reference also covers setfsuid, access, exec, and the absence of a general uid0 helper.

The kernel neutralizes conflicting Linux DAC decisions through its capability switchboard. Some capabilities are allowed for compatibility, some map to Peios privileges, and some are denied. The displayed capability mask is not an independent source of authority. Removing Linux capabilities or assigning file capability xattrs is not a substitute for controlling Peios token privileges.

Filesystem-facing projected identity also matters to quotas, remote servers, and stacking filesystems. Preserve that distinction when diagnosing a local success followed by a remote refusal. Peios does not make a remote server understand a local descriptor automatically.

Choose a channel with the required identity #

ChannelIdentity and authority boundary
Unix stream or seqpacket socketNative peer-token transport can bind local identity to the connection and conveyed requests.
Unix datagramIdentity is conveyed per message; do not use a connection register as its substitute.
TCP, UDP, or VSOCKNo local kernel attestation of the remote principal, including loopback IP traffic. Use an explicit authentication protocol.
Pipe or FIFOBytes and descriptor/file authority; no per-request token identity.
System V or POSIX queueObject permissions protect use; payload and projected notification identity do not authenticate a principal.
Shared memoryMapping and handle permissions; no identity attached to each memory write.
NetlinkKernel-bound operations use the kernel's sender/opener checks; this is not a generic peer-token channel.

A FIFO cannot replace an identity-carrying request/response named-pipe API. Use a Unix socket with the native token protocol. SCM_RIGHTS delegates a handle; token attestation is a different contract. Bind a received request to its received token before concurrent work changes the socket's latest peer state. The SDK token guide and socket identity reference define capture, impersonation, and transport limits.

Protect objects and their names #

System V objects carry descriptors, and mode changes do not replace those descriptors. Their numeric keys, abstract socket names, and shared-memory names remain claim-on-create namespaces. Create exclusively where appropriate and treat a pre-existing name as a condition to investigate, not proof of the expected server. Prefer service-owned directories and authenticate the peer.

The System V reference defines creation policy and descriptor operations by object kind and ID. A restricted caller is not categorically refused every object created by its parent: the complete descriptor and restricting identity determine the result.

Existing descriptors and mappings can retain authority after a policy change. Replacing a name or tightening a descriptor does not remove another process's old mapping. Design revocation and shutdown explicitly rather than promising that a permissions edit retracts already-delivered data.

Keep diagnostic provenance #

Linux process accounting remains a compatibility facility, gated through its capability-to-privilege mapping. Native KMES/eventd records carry Peios identity and process correlation, subject to each producer's schema and delivery limits. Do not promise that every Linux accounting field has a native event counterpart. Audit metadata and signal sender crumbs are observations, not credentials to reuse for authorization.

The MSIP Rust Library

Peios / Developing for Peios / Installer and Setup Conversations

The multi-surface interaction protocol (MSIP) lets one daemon drive terminal, graphical, and automated interfaces. The msip Rust crate provides wire framing, message structures, answer checks, and page state. It doesn't open listeners or run an operation for you.

Use the protocol specification for the complete contract. The library is a set of helpers, not a conformance claim for an application that embeds it.

Library boundaries #

The modules divide responsibilities as follows:

ModuleResponsibility
frameVersion-one framing, a 1 MiB total limit, and JSON object bodies
msgTyped message bodies and protocol enum encodings
elementCommon element fields and open type-specific state
daemonTurn sequencing, atomic updates, and structural answer checks
surfaceThe outstanding page after accepted updates

Your application owns socket permissions, peer verification, authorization, HELLO negotiation, binding order, listings, and conversation lifetime. It also owns timeouts, write serialization, bounded queues, and broadcast to attached peers. A frame's direction bit doesn't establish a valid connection state.

Daemon state #

Create a Conversation for an application-defined kind. Creation reads 128 random bits from /dev/urandom; failure returns an I/O error. The identifier names the conversation and does not authorize attachment.

Supply a TurnSpec to issue. It assigns the next sequence number and replaces the outstanding turn. Provide unique refs, valid state and defaults, and only element types supported by every attached surface.

Call handle_answer for a decoded Answer. It returns stale, protocol-error, missing-required-value, or valid results. It checks built-in value encodings and select/table choices. Your application validates domain rules, including string length, patterns, and whether referenced resources still exist. Negotiated extension types also need application-specific checks.

A valid result doesn't consume the answer. Serialize checking, domain validation, and acceptance across attached surfaces. Accept by issuing the next turn or ending the conversation before processing another competing answer. Reject domain validation with reject, then broadcast its Update.

Updates and attachment #

update stages an entire sparse batch before changing the stored turn. Unknown refs or malformed fields reject the batch without partial changes. Repeated refs fold in order, and log append entries accumulate in lines. If a log patch also supplies lines, that explicit value replaces the accumulated lines. Prefer one operation per patch.

update_full replaces the element list. Neither operation changes the turn sequence. Send current_turn after a successful attachment so the surface receives folded state without replaying earlier updates.

end marks the conversation ended and returns End for broadcast. The embedding daemon removes it from listings and handles connection cleanup. The library retains its final turn until the conversation is dropped.

Surface state #

Pass decoded daemon messages to Session::handle. Turn replaces the page; Update changes it atomically. Updates for other sequence numbers are ignored. Malformed updates and End bodies preserve the page. A valid End clears it. The last Bound identifier remains available for displaying the result.

The session doesn't enforce greeting or binding order. Apply those checks in your connection handler before calling it. Treat names, help, and messages as text; don't execute instructions inferred from display content.

Secrets and failure handling #

Mark secret inputs, collect them without echo, and avoid retaining their values after submission. Never put collected secrets in turn state, updates, errors, or logs. Message and element Debug implementations do not redact values. The library does not wipe caller-owned buffers.

A framing error can leave the stream between messages. Close the connection instead of attempting to resume decoding. A failed write can have sent a partial frame; don't retry that frame on the same stream. Configure read and write deadlines in the transport layer.

Presentation across surfaces #

Turn and element classes are optional presentation hints. The protocol carries typed content and state; it does not prescribe a daemon-controlled layout. Keep actions, required values, and validation correct when a surface ignores every class.

The installer owns its terminal renderer's presentation behavior. Those conventions describe msip-tui, not guarantees made by the Rust library or by all MSIP surfaces.

Conversation Lifetime

Peios / Developing for Peios / Installer and Setup Conversations

An installer daemon keeps one live conversation in memory. A frontend connects to that conversation to show its current questions and progress. The conversation belongs to the daemon rather than to a browser tab.

flowchart LR
    T[Terminal] --> D[Installer daemon]
    B[Browser frontend] --> D
    A[Scripted driver] --> D
    D --> J[Installation or setup job]

A second client can attach to the same live conversation. Its answers affect the same state, so multiple clients are collaborators rather than isolated sessions. Starting a client is not proof that it created a fresh operation.

Disconnects and restarts #

Closing a frontend does not stop an active job. A reconnect can show the current turn while the daemon remains alive. Restarting the daemon loses the conversation; the protocol does not make an interrupted disk operation transactional or provide durable recovery.

Completed and failed conversations are cleared so a later start can create another conversation. Read and preserve a failure result before retrying. Starting again is an additional operation, not an automatic rollback.

Progress and completion #

A successful installation job reaches a result page that offers restart. The restart request and the actual disk boot are separate events. A daemon can accept a restart request without proving the firmware booted the target.

The graphical frontend retains a failed job's result until you request a new conversation. Its log download records the job's output. msip-drive prints a trace, but its abbreviated log display is not a complete audit journal. See msip-drive(1) for automation constraints.

Slow clients and completion #

Each daemon connection has one writer, so complete messages remain in order. The daemon disconnects a client if queued output, including the frame being written, exceeds 4 MiB or writes make no progress for 10 seconds. A client that stops reading does not hold the conversation lock indefinitely.

At conversation completion, final messages drain outside that lock with a shared 10-second deadline. A start request during retirement receives an unavailable result. After retirement finishes, a fresh start can create the next conversation. A disconnected client must not assume that its last action failed or replay it without checking the daemon's state.

Browser input and reconnection #

The graphical frontend limits each incoming browser message and the input it admits to its shared queue. When the queue is full, submission waits for space while the browser continues receiving state updates. An oversized submission is refused with a message on the supplied page.

A stalled write to the daemon ends that connection. The page shows the lost connection while the frontend tries again. Actions queued for the old daemon connection are discarded, and browsers reconnect to fresh state. They are not automatically replayed against another conversation.

An action sent before disconnection can already have taken effect. Check the recovered page and any job result before submitting it again. Closing a tab also does not guarantee that an earlier submission was canceled. If a form is refused for exceeding the message limit, shorten its input before retrying.

The queue limit is not a limit on total process memory or the number of connected browsers. installer-gxwi(1) and oobe-gxwi(1) specify the message limits, queue accounting, and connection timeout.

Service Lifecycle

Peios / Developing for Peios / Installer and Setup Conversations

Installer packages carry registry seeds that define service startup. A seed is inert until an image or administrator applies it. Installing a package alone does not select the machine's setup lifecycle.

The installerd-service seed starts installerd as SYSTEM and restarts it after failure. A restart restores a listening service, but does not recover its previous in-memory conversation.

The oobe-service seed is intended for the installed system. It starts oobed after the local account service and waits for its readiness signal before starting the terminal frontend. oobed sends readiness after its socket is bound and its browser setup has been prepared.

The terminal frontend takes /dev/console ahead of the normal sign-in prompt. It also runs as SYSTEM in the supplied seed because the first administrator has not yet been created. Splitting the frontend from the engine separates responsibilities; the seed still determines authority.

On successful setup, oobed removes its service definition and the terminal setup definition. On failure, it keeps them so another boot can retry. Releasing the console lets the normal prompt appear even if setup failed.

Socket access #

The intended installation socket descriptor admits SYSTEM and Administrators. Setup additionally admits its temporary browser account when browser setup is offered.

Applying the descriptor is best effort: if sd is unavailable or fails, the daemon warns and retains inherited access. A listening message does not prove that the intended descriptor was applied. Verify the service's runtime environment and socket protection before granting access.

Console output #

While a conversation is active, the privileged service suppresses routine kernel console messages and restores the prior setting afterward. Emergency kernel messages remain visible. Other services can still write to the console; Ctrl+L asks the terminal frontend to repaint if those messages disturb the form.

Terminal geometry #

The terminal frontend discovers its size at startup. A render area with zero width or height draws no content and leaves the conversation intact. This does not add size reporting to a serial connection: a terminal that does not report later size changes still needs its size set explicitly.

Use the nonzero dimensions accepted by the frontend's --size option when starting with known geometry. See install-tui(1) or oobe-tui(1) for the size-discovery fallback and repaint controls.

Rehearsing Installer Conversations

Peios / Developing for Peios / Installer and Setup Conversations

Dry-run mode exercises the installation or setup conversation without performing its disk or account operations. It helps check frontend behavior and error handling, but it does not qualify a boot medium or installed operating system.

Use a private directory reserved for the rehearsal and an explicit socket path. Daemon startup removes the existing entry at that path, binds its socket, and attempts to apply its access descriptor even in dry-run mode. Do not point a rehearsal at a production service socket.

For installation, supply a synthetic inventory as well as --dry-run. Without an inventory, the daemon still probes the host's disk inventory. The checked-in frontend fixtures describe invented machines; the developer harness selects them explicitly.

A simulated phase failure can exercise an error page without damaging a filesystem. A simulated restart acknowledges the request without restarting the machine. Neither checks the real executor's cleanup, disk state, or boot behavior.

msip-drive can answer named inputs and queue actions, but it does not guard against joining an existing conversation. It waits on progress and consumes actions on new turns. It has no built-in deadline, and a rejected answer or same-turn update can leave it waiting. Stopping the driver does not stop the daemon's job.

Keep synthetic inputs and captured output in the disposable fixture. Credentials passed through --set are exposed in process arguments; the --set-file option avoids that exposure but still requires a protected input file. Do not use real credentials in a rehearsal.

The repository's build guide describes its host and VM harnesses. For the complete command interfaces, read installerd(8), oobed(8), and msip-drive(1).

Terminal Presentation

Peios / Developing for Peios / Installer and Setup Conversations

The installer's msip-tui renderer draws pages for install-tui and oobe-tui. Daemons supply typed elements through the multi-surface interaction protocol (MSIP); the renderer chooses their arrangement and appearance. A page still needs to work when another surface ignores its presentation hints.

Page arrangement #

Without a recognized turn class, the renderer places the heading and elements in a column, with actions together below them. The menu class moves actions into the body as a list. The confirm class marks the heading as a confirmation. Neither class changes the daemon's validation or makes an action safe to run.

The renderer checks these classes independently. Prefer one clear purpose for a turn rather than assuming that combinations define another layout. Unknown classes do not acquire behavior merely by being sent.

Progress elements render as a phase list. The first unfinished progress element is active, and a log can use the remaining height. This follows the element types and state; it does not require a progress turn class.

Element presentation #

Element informationTerminal behavior
An action's primary stateAccent color and bold text
An action's destructive stateDestructive coloring, including focus
A string's secret flagMasked entered text
A string's placeholder stateDim text while the empty field is unfocused
A table column's align: rightRight-aligned cells
A table row's enabled: falseDimmed row, skipped during selection
A table row's noteA remark after its cells
A table's empty stateText shown when it has no rows
An element's helpContext explaining the element or why it is unavailable
An element's errorAn error below the element until cleared

Masking is a display property. It does not make logging, debug formatting, or retaining a submitted secret safe. Follow the MSIP library's secret handling guidance and keep secrets out of turn updates and diagnostics.

A primary action's appearance does not authorize unattended execution. Choose explicit actions in automation. A destructive action is not given extra validation by its color; the daemon owns confirmation and authorization.

Focus and narrow terminals #

Unavailable input elements can take focus, allowing a person to discover why they cannot answer them. Supply useful help, such as the missing prerequisite. Initial focus favors the first answerable element, with the primary action used where appropriate.

Fields reserve space for their note so moving focus does not shift the page. Errors remain visible. Help appears when the element is focused or unavailable. Table selection skips unavailable rows, and the answer validator also rejects them; dimming alone is not the enforcement mechanism.

Tables drop columns from the right when space is limited. Put the column needed to identify a row first, and test narrow terminal widths.

Leaving and automation #

Esc opens the surface's leave question. Its wording depends on the frontend: leaving an ongoing installation differs from leaving initial account setup. A daemon page cannot override that lifecycle meaning with a presentation class.

msip-drive does not draw the terminal layout. Its scripted answers rely on refs, values, and actions rather than color or class hints. Use Installer Conversation Rehearsals to check that the same conversation remains usable through automation.

Packages

Peios / Developing for Peios / Packaging Software

A package is how software is shipped on Peios: a set of files, symbolic links, and directories with a name, a version, and an architecture. ppk stores a package as a list of its paths and the content of each file, and names every piece by a hash of its content. That design explains why a packed version can never change and why files shared between packages take no extra space.

Manifests and blobs #

A package has two kinds of part:

  • Blobs. A blob is the content of one file, named by its SHA-256 hash. It doesn't record the file's path or name.
  • The manifest. A manifest names the package and lists every path in it. Each path is a file, given by its blob and whether it is executable; a symbolic link, given by its target; or an empty directory.

A directory that contains anything is implied by its contents, so the manifest lists only empty ones, and those with security metadata of their own. Of a file's permissions, the manifest keeps only whether it is executable.

The manifest for a package holding one program and one document looks like this:

name = "dev.peios.hello"
version = "1.0-1"
arch = "noarch"

[files]
"bin/hello" = { blob = "sha256:de7a5d81f4ab0680f55966b56e7bebfd5da26f4f45d8cd6e2e22c6a0e523c37f", exec = true }
"share/doc/hello/README" = { blob = "sha256:c90139667a35e240080ae250c1f99a5df3a6d509b0aa65b3d5550f87e20cb3a4" }

Paths are relative to /usr, where everything Peios ships lives, including the configuration it ships in /usr/etc. This package's bin/hello is /usr/bin/hello. A package can't ship anything outside /usr: a machine's own configuration and state live outside it, and stay the machine's. An absolute symbolic link target is read from the root of the system, so a link to /usr/lib/libz.so.1 names a file in the same or another package.

A package's identity #

A package's identity is the SHA-256 hash of its manifest, written as sha256: followed by the hash in hexadecimal. The manifest names every blob by its hash, so the identity covers the content of every file as well as the paths, names, and versions.

ppk writes a manifest in exactly one way: entries in a fixed order, with fixed spacing and quoting. The same directory therefore always produces the same manifest and the same identity. You can rebuild a package and compare identities to check that the result is identical.

Package identifiers #

You name a package with an identifier of this form:

<name>@<version>[?arch=<arch>]

<name> and <version> are the package's name and version. <arch> is the processor architecture its content is built for, such as x86_64 or aarch64. Use noarch for a package whose content runs anywhere, such as documentation or scripts.

If you leave out ?arch=, the architecture is the one ppk itself was built for. Give it explicitly for any package built for another machine, and always for noarch packages. The characters an architecture can contain are listed in ppk(1).

Package names #

A package's name is reverse-DNS: the domain of whoever owns the software, backwards, then the product. ppk refuses any other name, wherever one reaches it, including in a fetched manifest.

SoftwareNameExample
Peios's owndev.peios.<product>dev.peios.hello
A testing-only Peios productdev.peios.testing.<product>dev.peios.testing.fixture
Anyone else'sThe upstream project's domainorg.gnu.bash, io.github.eudev-project.eudev
Part of a split packageThe complete name of the base, with a suffixorg.gnu.glibc-devel

Use the upstream project's own domain for software that Peios only packages. A name doesn't rename anything: a program keeps its own executable, service, and other externally defined names.

A name has at least three labels, separated by dots, and at most 64 characters. Each label holds lowercase ASCII letters, digits, +, and -, starts with a letter or digit, ends with a letter, digit, or +, and has no --. The first label holds only letters, as a top-level domain does, and neither of the first two holds a +.

ppk can only check a name's form. It can't tell whether a domain is the right one for the software, or whether a split keeps its base's name, so those are for whoever writes the package.

Package versions #

A version has three parts, written [<epoch>:]<upstream>-<revision>:

  • Upstream version. The version the software's own project gave it, such as 2.44 or 1.0-rc.1. It holds ASCII letters, digits, ., +, -, and ~, and starts with a letter or digit.
  • Revision. Which packaging of that upstream version this is, starting at 1. Pack a new revision when the package changes but the software doesn't. Every version has one: 2.44-1, never 2.44.
  • Epoch. An optional number before a colon, as in 1:0.5-1, that's raised only when an upstream project's versions go backwards, so that the new ones sort after the old.

Versions sort by epoch, then upstream version, then revision. Upstream versions compare a run of digits or letters at a time, with digits as numbers, so 2.10 comes after 2.9. A pre-release sorts before its release: anything after a ~, and dev, alpha or a, beta or b, pre, and rc, in that order, so 1.0~rc1-1 and 1.0-rc.1-1 both come before 1.0-1. This is the order of PSPU 5.6, the same as the earlier Peios package tools used.

What else a manifest says #

Besides its files, a manifest can record what the package needs and offers, and describe it:

PartWhat it records
[dependencies]Other packages this one needs, each with the versions it can use
[requires]Capabilities this one needs, such as the library libc.so.6 or a shell, sh
[provides]Capabilities this one offers, each at a version or none
[claims]Links this package provides besides its files, such as /usr/bin/sh
description, homepage, license, license_class, source_licenseWhat the package is and its terms
sourceThe package holding the source it was built from

They're part of the manifest, so they're part of the package's identity, and like the files they have one spelling each. A package that records none of them has the same manifest it would have had without them. To record them, see Recording Dependencies and Metadata.

Security metadata #

A file or directory can carry security metadata in its manifest entry:

  • A security descriptor, which replaces the one it would otherwise get, so that, for example, only one service can run a program or write a directory.
  • A signature, for a file. The kernel reads it from the file's security.peios.sig attribute and checks it before it gives the file to a device as firmware. The signature is stored as a blob, and the entry names it by its hash.

These entries, with the descriptor shortened, are from a package that gives one content both ways:

"bin/server" = { blob = "sha256:07f7ab476bc3a83fad639d34a012cb4a5f859441f0d24c11627ca96696839012", descriptor = "0100048014000000…" }
"lib/firmware/acme/fw.bin" = { blob = "sha256:07f7ab476bc3a83fad639d34a012cb4a5f859441f0d24c11627ca96696839012", signature = "sha256:ec87928fa1c24dacf5ebe2eaf8f7adf473de9ef65f8b7648ead92e9f7672155b" }

The metadata is part of the entry, so it's part of the package's identity. A file with security metadata is stored as a file of its own that carries it, and every hard link to that file carries it too. Two files with the same content and different metadata are two stored files, and two packages can't give one path different metadata. A package with no security metadata has the manifest it would have had without it.

On Peios, ppk gives each file and directory its metadata as it creates it. On another system, such as a Linux host that builds packages, it writes the attributes only where that system lets it, which usually needs privilege, and otherwise warns that it couldn't. The manifest records the metadata either way. To give files security metadata, see Giving Files Security Metadata.

The artifact directory #

ppk stores packages in an artifact directory, which is /system/artifacts unless you name another. It holds these kinds of file:

PathContents
blobs/sha256/<hash>The content of one file that isn't executable
blobs/sha256/<hash>.execThe content of one executable file
blobs/sha256/<hash>.<entry>The content of one file with security metadata, which it carries
manifests/sha256/<hash>One manifest, named by its hash
refs/<name>/<version>/<arch>The identity of the package with that name, version, and architecture

A blob is stored in the form its manifest entries need: plain, executable, or both if the same content is shipped both ways. A file with security metadata has a form of its own, named by the SHA-256 hash of its entry as the manifest writes it. The form is part of the stored file, not of the blob's name, so a package's identity doesn't depend on it.

A ref is an index. It lets you find a package by name, but every manifest records its own name, version, and architecture, so the manifests remain the authority.

Because a blob is named by its content, a file that appears in several packages, or in several versions of one package, is stored once. Packing a new version adds blobs only for the files that changed.

An artifact directory is also where other machines get packages from. ppk fetch copies a package out of one artifact directory into another, checking every hash on the way; see Fetching a Package.

Packed versions never change #

Once a package is packed, its name, version, and architecture always mean the same content. Packing the same version again with identical content succeeds and changes nothing. Packing it with any change to its files is refused, so that a version means one thing everywhere it is used. To ship a change, give it a new version.

Every file in the artifact directory is read-only for the same reason: a blob, manifest, or ref that changed after it was written would stop matching what refers to it.

Who can read a package #

Everyone on a machine can read and run what's in its artifact directory. ppk gives every file it stores a security descriptor that grants Everyone read and execute, and SYSTEM and Administrators full control. The directories it creates there grant the same, so any user can reach the packages. A file or directory that a package gives a descriptor of its own has that one instead, wherever it's placed.

A package is the same on every machine it's installed on, because its content is named by hash. It can't hold anything that belongs to one machine or one user, and anything in it is readable by every user of every machine that stores it.

Important

Never put a secret, such as a key or a password, in a package. Keep secrets in the machine's own configuration instead.

Closures

Peios / Developing for Peios / Packaging Software

A closure is a set of packages composed into one directory tree: the contents of a /usr. Mounted at /usr, each package's files are at their ordinary paths, such as /usr/bin/hello, so software runs from a closure without any changes to where it looks for its files. Different closures can hold different versions of the same package side by side.

A tree of hardlinks #

Unless you ask for copies, every package file in a closure is a hardlink to its blob in the artifact directory: the same file on disk, not a copy. Building a closure therefore copies no file content, and a file that several closures share is stored once.

A hardlink shares everything about the file except its name, including whether it is executable. That's why the artifact directory stores an executable form of each executable blob, as described in Packages. For the same reason, everything in the artifact directory is read-only: a change made through one closure would change the file in every closure that links it.

Symbolic links and directories aren't shared. ppk closure creates them afresh in each tree. The root of the tree grants everyone read and execute, and the directories and links inside it inherit that, so any user can reach and run what a closure holds. Its files have the access their blobs grant, described in Packages.

Why each package is there #

Each closure records why it holds each package, in its inventory: a file at the top of its tree, visible as /usr/inventory when it's mounted. ppk compose-env writes the same file in the root's usr. It's a line format:

closure sha256:9c41…
org.openssl.libssl@3.5.8-1?arch=x86_64 sha256:… [se.curl.curl libssl.so.3]
se.curl.curl@8.22.0-1?arch=x86_64 sha256:… [* >=8.22]

The first line names the closure. Each other line is a package: its full ID, its identity, and a bracket for each thing that wants it.

  • Who wants it: * for a request made of the closure itself, such as a package named after ppk run -p or in a profile, or the name of another package in the closure.
  • What it asked for: a capability, such as a library's soname, if the package wasn't asked for by name.
  • Where from: # and an index or channel, such as #stable, for a request that named one.
  • Which versions would do: one token per expression of the constraint, such as >=8.22, or none for any version.

A package is wanted by every request, dependency or requirement it satisfies. Every package in a closure must be wanted by something, and every request satisfied. Lines are sorted by package ID, and brackets by who wants the package, * first.

This generated file has mode 0444 and inherits the tree's security descriptor, like directories without manifest metadata.

Naming a closure #

A closure's identity is the SHA-256 hash of its inventory without the first line. So the same packages, asked for the same way, always make the same closure, whatever order you name them in. The same packages asked for differently, such as * asking for curl exactly in one and only through another package in the other, are two closures.

Closures are kept in the closures directory of the artifact directory unless you name another. The tree is closures/<hash>/, and its manifest, the same lines as the inventory without the first, is closures/<hash>.manifest.

Because the name is known before anything is built, ppk closure reuses a closure that already exists. It builds a new tree in a temporary directory and moves it into place only when it's complete, so a closure that exists is never half-built.

A closure can also be given a name of your own with ppk name:

ppk name SYSTEM sha256:9c41…   # SYSTEM now names that closure
ppk name SYSTEM                # print the closure SYSTEM names
ppk name                       # list every name
ppk name --remove SYSTEM       # remove the name; the closure stays

A name is a symbolic link beside the closures, replaced by renaming, so it always names one closure or another. An installed system names the closure that is its /usr SYSTEM, and the one its initramfs is built from INITRAMFS.

Identifying the mounted closure #

ppk list checks that the inventory's identity is the hash of its other lines before printing the packages. This checks the recorded packages and requests; it doesn't authenticate the package IDs or verify the files in the tree.

Run ppk list to print the current closure's full package IDs in byte order, one per line. No artifact directory is needed. Run ppk list --all to list every package indexed by the store's refs, also sorted by full ID. A package whose ID and identity are both in the current closure has * before its ID; other packages have a space there, so every ID starts in the same column.

A missing inventory makes ppk list fail with an explanation. With --all, a missing inventory leaves every package unmarked. A malformed inventory or mismatched closure identity makes either command fail.

An existing closure without an inventory is reused unchanged as a closure built by an older ppk. To obtain an inventory, compose a fresh root or use a separate closure directory. Reusing a closure keeps requiring only read access to its tree.

Conflicts #

Packages in a closure share one tree, so they have to agree about every path in it. Building a closure fails, before anything is written, when:

  • Two packages give one path different contents. Two packages can ship the same file only if it is identical, such as a shared license text.
  • A path lies beneath another package's file or symbolic link. One package can't put files inside something another package ships as a file. This also means a closure is never written through a symbolic link to somewhere outside it.

A package can put files in an empty directory that another package ships.

The same mount #

A hardlink can't cross from one mount to another, even between two mounts of one filesystem, as the bind mounts of a build sandbox often are. So the closure directory must be on the same mount as the artifact directory, and ppk closure fails with nothing left behind if it isn't.

Copied files #

To build a closure on another mount, ask for copies with --copy-files. The tree then has the same paths, content, and permissions, and the same identity, but each file is a file of its own. ppk copies a file only when you ask, rather than whenever a link fails, because a copy differs from a hardlink in ways you should choose:

  • It takes space. A copy is stored once per closure, not once per store.
  • It has a security descriptor of its own. A hardlink has its blob's one descriptor, so the store controls access to every closure that links it. A copy gets the store's descriptor when it's made, so it grants what a hardlink would, but a later change to the store's descriptors doesn't reach it.
  • It is checked. A copy has to read the blob, so ppk hashes it as ppk fetch does, and a blob that doesn't match its hash stops the build. Hardlinking reads no content, and checks none.

A closure is named by its packages, not by how its files got there, so ppk closure reuses an existing closure whichever way it was built.

Environments

Peios / Developing for Peios / Packaging Software

An environment is a view of the filesystem in which a closure is /usr. Everything Peios ships lives under /usr, so a program in an environment finds the exact set of packages the closure holds, while everything else, such as the machine's own configuration, its state, and your home directory, stays where it was. Different programs can run side by side with different closures as their /usr.

What changes and what doesn't #

An environment starts from the filesystem as the process that creates it sees it, and replaces only /usr with the closure. Directories such as /lcl, /var, /home, and /run are the same ones, so a program in an environment reads the machine's configuration and shares /run with the rest of the machine.

Packages are laid out relative to /usr for this reason: a package's bin/hello is /usr/bin/hello in any environment that includes it, and a package can't place anything outside /usr.

Kept to its own processes #

An environment is a mount namespace: a private copy of the table that says which filesystem is mounted where. ppk run creates one, mounts the closure at /usr in it, and starts the command there. The command and every process it starts see the closure; nothing outside sees any change, and when the last of them ends, the environment ends with it.

Each ppk run creates a new environment, even for the same closure. The closure itself is built once and reused.

Laid out as files #

An environment can also be laid out as a directory, as the whole root of a filesystem, for a tool such as an image builder to take. ppk compose-env does this. There is no running system around such a root to borrow the rest of the filesystem from, so what lies outside /usr, such as links and mount points, is given when the root is composed. It belongs to the environment, not to any package.

Described by a profile #

An environment profile is a TOML file that describes an environment, so that it can be named and reused rather than spelt out on the command line each time:

dirs = ["proc", "sys", "tmp"]

[packages]
"net.busybox.busybox" = "1.37.0-1"
"dev.peios.prelude" = ">= 0.0.7"

[symlinks]
"init" = ":sbin/prelude"

packages maps each package the environment asks for to the versions that will do, as a constraint. A bare version asks for exactly that version, and "" for any. "#stable" asks for the version a repository's stable channel holds, and "#stable >= 1.36" for that version if it satisfies the constraint; see Publishing a Repository. A profile holds the requests, not their answer: composing it resolves them, choosing a version of each package they need, and the closure's inventory records what was chosen. The same requests against the same packages always resolve the same way. A profile that asks for exact versions of everything, as ppk resolve writes one, always describes the same environment. symlinks and dirs are what the root holds outside /usr, besides any links its packages claim there, and a leading : in a link's target stands for usr. include_artifacts = true gives a composed root its packages in an artifact directory of its own. Every key is optional. arch sets the architecture of every package, the one ppk was built for by default.

A profile can include other profiles, called fragments, so that what several environments share, such as the layout of a root, is written once:

include = ["root-layout.toml"]

[packages]
"net.busybox.busybox" = "1.37.0-1"

Each path is relative to the file that names it, and a fragment can include others. The profile holds everything its fragments hold. Where two of them hold the same thing, it's held once, and where they disagree, as with two versions of one package or two targets for one link, it's an error naming both files. Nothing decides which one wins: you change one of them.

ppk compose-env and ppk run both take profiles, and several given together merge as fragments do. A run keeps the rest of the filesystem as it is, so it uses only the profiles' packages.

Who can create one #

Any process can create a mount namespace of its own and mount a closure in it, so ppk run needs no privilege. Building a closure needs write access to the closure directory, but running one that already exists only reads the store, so an ordinary user can run any closure an administrator has built.

The closure is mounted as it is, not read-only: making a mount read-only needs a privilege that ordinary users don't hold. Its files are protected by their security descriptors instead, which grant everyone read and execute and nothing more.

Creating a Package

Peios / Developing for Peios / Packaging Software

Packing turns a directory of files into a package in an artifact directory. Do this when you have built software and want to ship it as a named, versioned package. For what a package contains, see Packages.

Before you start #

The top-level name inventory is reserved for ppk's closure inventory. Do not include a file, directory, or symbolic link with that name in the package's input tree, or claim /usr/inventory or a path beneath it. ppk pack refuses these paths before writing to the store.

  • Install ppk.
  • Choose the package's version, the architecture its content is built for, and its name, which must follow the rules for package names.
  • Have write access to the artifact directory. The default is /system/artifacts; to use a directory of your own, pass --artifact-dir.

Pack a directory #

  1. Stage the package's files in a directory, laid out as they will appear under /usr. For example, a program installed as /usr/bin/hello goes at hello/bin/hello.

  2. Make sure each program in the directory is marked executable. The package records which files are executable and nothing else about their permissions.

  3. Run ppk pack with the package's identifier and the directory:

    ppk pack 'dev.peios.hello@1.0-1?arch=noarch' hello --artifact-dir artifacts
    

    Quote the identifier, because some shells treat ? as a wildcard. ppk prints the package's identity:

    sha256:73a137f612f39b8ee1ffcbb7f51b7b9dc370b8662323d72b9e6b73b9d54413f8
    

Check the result #

Read the package's ref, which is named by its name, version, and architecture:

cat artifacts/refs/dev.peios.hello/1.0-1/noarch

It holds the identity that ppk pack printed:

sha256:73a137f612f39b8ee1ffcbb7f51b7b9dc370b8662323d72b9e6b73b9d54413f8

The manifest is artifacts/manifests/sha256/ followed by the same hash. It lists every path in the package.

Packing for another architecture #

If the content is built for a particular processor, name its architecture in the identifier:

ppk pack 'dev.peios.hello@1.0-1?arch=aarch64' hello-aarch64 --artifact-dir artifacts

Without ?arch=, ppk uses the architecture it was built for itself. The same name and version can be packed once for each architecture.

Shipping a change #

A packed version never changes. If you pack the same version again with different files, ppk refuses and exits with status 1:

ppk: dev.peios.hello@1.0-1?arch=noarch: already packed as sha256:73a137f612f39b8ee1ffcbb7f51b7b9dc370b8662323d72b9e6b73b9d54413f8; a packed version cannot be replaced

Pack the changed files as a new version instead, such as dev.peios.hello@1.1-1?arch=noarch. Only the files that changed are stored again. Packing a version again with identical files succeeds and prints the same identity.

Recording Dependencies and Metadata

Peios / Developing for Peios / Packaging Software

A package's manifest can say what the package needs, what it offers, and what it is, as well as listing its files. Record these when you pack it, so that whatever builds an environment from packages can choose the ones that work together. For what a manifest holds, see Packages.

Before you start #

  • Be able to pack the package, as Creating a Package describes.
  • Know what the package needs at run time that isn't in its own files and that its programs don't link: the packages and commands it runs by name or loads itself. ppk pack finds the libraries its programs link, as What ppk pack finds in the files describes.

Record what the package needs and offers #

Give ppk pack an option for each thing to record. The options that take two values take them as two separate arguments, so neither value needs a separator. An empty value means "any version" for a dependency or requirement, and "no particular version" for something provided:

ppk pack 'org.git.kernel.dash@0.5.13.5-1?arch=x86_64' dash --artifact-dir artifacts \
  --depends org.gnu.glibc '>= 2.44' \
  --provides sh '' \
  --claims /usr/bin/sh dash
  • --depends <name> <constraint> records a dependency on another package, by its name.
  • --requires <name> <constraint> records a need for a capability rather than a particular package: a name such as the shell sh, or pkgconfig(zlib), which any package can provide. A library that a program links is found for you.
  • --provides <name> <version> records a capability this package offers.
  • --claims <path> <target> records a link at an absolute path that the package provides besides its files, with the link's target. Use it for a name that one of several packages answers, such as /usr/bin/sh.

Give each option once for each package, capability or path. A name given twice is an error.

What ppk pack finds in the files #

ppk pack reads each ELF program and library in the files, and adds what they need and offer to what the options give:

  • Each library a program or library links (its DT_NEEDED) becomes a requirement, such as libtinfo.so.6. A library the package itself provides isn't required.
  • Each library's own name (its DT_SONAME) becomes a capability the package provides.
  • For glibc's libraries and libgcc_s.so.1, the requirement has a floor: the newest symbol version the programs use. A program using GLIBC_2.38 requires libc.so.6 >= 2.38. The package providing the library provides it at its own version, such as 2.44-1.
  • For libstdc++.so.6, each symbol version is a capability of its own, such as elfver(libstdc++.so.6:GLIBCXX_3.4.21).

Files under src/ and symbolic links aren't read, nor is anything that isn't ELF.

Where an option names a capability that the files also give, the option's entry is kept. The floors are the exception: they come only from the files, so don't write them yourself. A floor written by hand tends to record what the package was built against, not what it needs, and it would keep the package off a system with an older glibc that would run it. To require a newer glibc for a reason the symbols don't show, depend on the glibc package with --depends and say why in the recipe.

The rules in full are under DERIVATION in ppk(1).

Write a constraint #

A constraint is one or more expressions, separated by commas, that a version must all satisfy:

ConstraintSatisfied by
>= 2.442.44 and later, whatever the revision: 2.44-1, 2.44-3, 2.45-1
>= 2.44-32.44-3 and later, but not 2.44-2
>= 1.0, < 2.01.0 and later, before 2.0
= 2.44-1 or 2.44-1Exactly 2.44-1
!= 2.43Anything but upstream version 2.43
EmptyAny version

The operators are =, >, >=, <, <=, and !=, and a version without one means =. A version in a constraint can leave out its revision, and the revision then isn't compared. That's usually what you want: repackaging the same upstream version shouldn't change whether a dependency is met. Versions compare as Package Versions describes.

Describe the package #

Add the descriptive options to the same command:

  --description 'POSIX-compliant shell' \
  --homepage https://git.kernel.org/pub/scm/utils/dash/dash.git \
  --license BSD-3-Clause \
  --license-class free
  • --description is one line of printable ASCII.
  • --homepage is an http or https URL.
  • --license is the package's license, conventionally an SPDX expression, and --source-license the license of the source it was built from, where that differs.
  • --license-class is free, firmware, proprietary, or unknown, the default.
  • --source names the package holding the corresponding source the package was built from, as a package ID with its architecture, such as org.git.kernel.dash-source@0.5.13.5-1?arch=noarch. A package built from no source of its own, such as device firmware, leaves it out.

Check the result #

ppk pack prints the package's identity. Its manifest, in artifacts/manifests/sha256/ followed by that hash, records everything you gave and everything found in the files, in one fixed order:

name = "org.git.kernel.dash"
version = "0.5.13.5-1"
arch = "x86_64"
description = "POSIX-compliant shell"
homepage = "https://git.kernel.org/pub/scm/utils/dash/dash.git"
license = "BSD-3-Clause"
license_class = "free"

[claims]
"/usr/bin/sh" = "dash"

[dependencies]
"org.gnu.glibc" = ">= 2.44"

[provides]
"sh" = ""

[requires]
"libc.so.6" = ">= 2.38"

[files]
"bin/dash" = { blob = "sha256:e4a76dc6517a94c9f1abde8582aa3909a1315e28a66a5c9f304c5a697b74c638", exec = true }

The requirement on libc.so.6 comes from bin/dash, which uses symbols as new as GLIBC_2.38. Each constraint is written in one form, whatever spacing you gave it, and anything that wasn't given or found is left out.

When an option is refused #

ppk pack checks everything before it writes anything. Anything that breaks a rule is a usage error, with exit status 2, and nothing is packed. A dependency must name a package, so a capability given to --depends is refused:

ppk: dependencies: invalid package name 'sh': use a reverse-DNS name such as dev.peios.hello, of at most 64 characters, with at least 3 dot-separated labels of lowercase ASCII letters, digits, - and +

Use --requires for it instead. A constraint that doesn't parse names its option:

ppk: --depends org.gnu.glibc: constraint '>=2.44,' has an empty expression

A floor on one of glibc's libraries or libgcc_s.so.1 fails, with exit status 1, because only the files can say what it is. The message names what you wrote and what the files need:

ppk: requires libc.so.6: the written floor '>= 2.44' is refused, and the payload needs '>= 2.38' (bin/dash); a floor on libc.so.6 comes only from the payload's symbol versions

An ELF file that ppk pack can't read fails in the same way, naming the file.

The full rules for each value are in ppk(1).

What ppk does with them #

The dependencies, requirements, capabilities and claims you record are part of the package and its identity, and ppk checks them when it reads a manifest.

  • ppk resolve follows dependencies and requirements to choose the packages an environment needs, as Choosing Packages for an Environment describes. A requirement is met by a package of that name or one that provides the capability; a dependency only by a package of that name.
  • Composing creates each claimed link: under /usr in the closure, and elsewhere, such as /init, in a composed root. Two packages in one environment can't claim the same path. A closure is only /usr, so ppk run creates only the links claimed there.

Changing any of them changes the package, so it needs a new version, as a change to its files does.

Giving Files Security Metadata

Peios / Developing for Peios / Packaging Software

Most files in a package get the security descriptor that ppk gives everything it stores. Some need one of their own: a program that only one service can run, or a directory that only one service can write. Firmware needs a signature, which the kernel checks before it gives the firmware to a device. Record both when you pack the package, and ppk gives each file and directory its metadata wherever it places it. For what a manifest holds, see Security metadata.

Before you start #

  • Be able to pack the package, as Creating a Package describes.
  • Have each descriptor as a self-relative security descriptor in hexadecimal, with an owner, a group, and a DACL. ppk takes the descriptor's bytes, not SDDL.
  • Have each firmware file's signature: the 3310-byte file that a signer writes beside the file, named with .peios.sig added.

Give a file or directory a descriptor #

Give ppk pack the --descriptor option with the path, as the manifest lists it, and the descriptor. The two values are separate arguments:

ppk pack 'dev.peios.gxwi@1.0-1?arch=x86_64' gxwi --artifact-dir artifacts \
  --descriptor bin/gxwi-server 010004801400000020000000000000002c000000...

The descriptor is shortened here. Give the option once for each path. The path is relative to /usr, so bin/gxwi-server is /usr/bin/gxwi-server.

  • A file keeps its descriptor in every closure and environment, because each placed file is a hard link to a stored file that has it, or a copy given it.
  • A directory with a descriptor is listed in the manifest even if it has contents. It's created with its descriptor before anything inside it, so what's created in it inherits from that descriptor.
  • A symbolic link can't have a descriptor of its own.

Sign a file #

Put each signature in the directory you pack, beside the file it signs, with .peios.sig added to the file's name:

gxwi/lib/firmware/acme/fw.bin
gxwi/lib/firmware/acme/fw.bin.peios.sig

ppk pack doesn't pack the signature as a file. It records it in the signed file's entry, and the file gets it as its security.peios.sig attribute wherever it's placed. A signature must be exactly 3310 bytes and start with the version byte, 1. The file it signs must be a regular file in the same package, and not an ELF file: an ELF file carries its signature in its own .peios.sig section. No other path can end in .peios.sig.

ppk doesn't check what a signature signs. That's the kernel's job, when it loads the file.

Check the result #

ppk pack prints the package's identity. In its manifest, in artifacts/manifests/sha256/ followed by that hash, each file and directory with security metadata has it in its entry, after its blob or dir:

"bin/gxwi-server" = { blob = "sha256:07f7ab476bc3a83fad639d34a012cb4a5f859441f0d24c11627ca96696839012", exec = true, descriptor = "010004801400000020000000000000002c000000..." }
"lib/firmware/acme/fw.bin" = { blob = "sha256:07f7ab476bc3a83fad639d34a012cb4a5f859441f0d24c11627ca96696839012", signature = "sha256:ec87928fa1c24dacf5ebe2eaf8f7adf473de9ef65f8b7648ead92e9f7672155b" }

The descriptor is written in lowercase, whatever case you gave it, and is shortened here. The signature is named by its hash, and stored as a blob.

Packing on a system other than Peios #

On Peios, ppk gives each stored file, copy, and directory its metadata as it creates it, and fails if it can't. On another system, such as the Linux host that builds packages, it writes the security.peios.sd and security.peios.sig attributes only where that system lets it, which usually needs privilege. Where it can't, it packs the files without them and warns:

ppk: warning: 2 files and directories lack security metadata this system would not let ppk give; their manifests record it

The package is still complete: its manifest records the metadata, and ppk fetch on Peios gives each stored file what its entry records. ppk closure, ppk compose-env, and ppk run warn in the same way when they place files that lack it.

Note

On Peios, a stored file's descriptor can't be read back as it was given, so ppk doesn't give a descriptor to a stored file that was stored elsewhere without one. Fetch the package on Peios, or copy its files with --copy-files, so that each gets its descriptor as it's created. A missing signature is given whenever the file is placed.

When something is refused #

ppk pack checks everything before it writes anything. A descriptor that isn't hexadecimal, or isn't a whole self-relative descriptor, is a usage error, with exit status 2:

ppk: --descriptor bin/gxwi-server: security descriptor has no owner or no group

These fail with exit status 1, and nothing is packed:

  • A descriptor for a path that isn't a file or directory of the package, or for a symbolic link.

  • A signature that isn't 3310 bytes, or doesn't start with version 1.

  • A signature beside nothing, or beside a symbolic link, or an ELF file:

    ppk: "bin/tool.peios.sig": signs "bin/tool", an ELF file, which carries its signature in its .peios.sig section
    
  • Anything else whose name ends in .peios.sig.

ppk closure and ppk compose-env refuse two packages that give one path entries that differ only in their security metadata, as they refuse any other two different entries. A stored file whose signature attribute isn't the one its entry names is an error, because it isn't the file its name says. The full rules are under SECURITY METADATA in ppk(1).

Fetching a Package

Peios / Developing for Peios / Packaging Software

Fetching resolves a package and everything it needs from another artifact directory, or from a repository served over HTTP, then copies the chosen packages into yours and checks them on the way. Do this to use a package that was packed somewhere else, such as on a build machine whose artifact directory you can read, or one a repository publishes.

Before you start #

  • Install ppk.
  • Have read access to the source: an artifact directory, as a local path, or a repository's URL.
  • Have write access to your artifact directory. The default is /system/artifacts; to use a directory of your own, pass --artifact-dir.
  • Know the package's name, such as org.figlet.figlet.

Fetch the package #

Run ppk fetch with the name and the source:

ppk fetch org.figlet.figlet --from shared --artifact-dir artifacts

ppk chooses the newest version that satisfies the request, follows its dependencies and requirements, and fetches every chosen package. It prints one identity per package fetched, in package-name order:

sha256:73a137f612f39b8ee1ffcbb7f51b7b9dc370b8662323d72b9e6b73b9d54413f8

To constrain the version, quote the name and constraint, for example 'org.figlet.figlet >= 2.2'. A full ID such as 'org.figlet.figlet@2.2.5-1?arch=x86_64' pins that exact package, including the version's spelling. Its dependencies are still resolved. Unqualified requests choose for ppk's own architecture; --arch selects another. All packages in one resolution must be for the same architecture. A full ID with an explicit architecture can select that architecture on its own.

Resolution is greedy, as ppk resolve is. Missing dependencies, missing capability providers and conflicting constraints fail with an error naming what is needed, before copying starts.

To copy exactly one package without resolving anything it needs, pass --no-deps and a full ID. This mode accepts IDs, with an optional ?arch=…, rather than bare names or constraints:

ppk fetch --no-deps 'dev.peios.hello@1.0-1?arch=noarch' --from shared --artifact-dir artifacts

--from also takes the URL of a repository served over HTTP, such as https://pkgs.peios.org/. --from takes no identity, so ppk checks every file against its hash but can't check who signed the repository. To check that too, add the repository with its identity, using ppk repo add.

Check the result #

Compare the identity with the one ppk pack printed where the package was made. Because the identity is the hash of the manifest, and the manifest names every file by its hash, the same identity means the same package, byte for byte.

Fetch from configured repositories #

A machine keeps a list of the repositories it fetches from, each a file in /conf/ppk/repositories/. Add one with ppk repo add, giving the identity its pointer file must be signed under, and the channel it follows:

ppk repo add peios /mnt/peios-repo --identity pkgs.peios.org --track stable

ppk accepts the signature only if a root it was built with vouches for the chain that made it. A repository whose publisher has no such chain signs under a top-level certificate of its own, which you enable on the machine first. Add that repository with --unrooted, and optionally with --anchor and the top-level's hash, to accept that top-level and no other:

ppk repo add tools https://pkgs.example.com/ --identity pkgs.example.com --unrooted

That writes /lcl/conf/ppk/repositories/peios.toml, which /conf/ppk merges with whatever the system ships. Then fetch without --from:

ppk fetch se.curl.curl

A repository served over HTTP is added by its URL instead of a path. Give more than one URL to try them in order, such as a cache on your network first and the repository's own server after it:

ppk repo add peios http://cache.lan/peios/ https://pkgs.peios.org/ \
    --identity pkgs.peios.org --track stable

If a URL can't be reached or doesn't have a file, ppk tries the next one. ppk keeps the tree nodes and manifests it reads from a repository served over HTTP in /var/cache/ppk, so it reads each of them only once. Pass --cache-dir to keep them somewhere else.

A request for a bare name, or a name with a constraint, follows the channel its repository tracks, so this fetches the version stable holds, and what it needs from stable too. Naming an index, as in se.curl.curl#leading, or an exact version, takes that instead.

Each package name belongs to one repository. If two of them publish one, for something you asked for or something it needs, ppk refuses rather than choose. A repository's pointer file goes up in sequence each time it's published, and ppk keeps the highest it has seen of each in /var/state/ppk, refusing a repository that offers an older one. A mirror might still be behind; ppk repo list shows when each was signed:

peios /mnt/peios-repo #stable (sequence 42, signed 2026-11-13T13:11:46Z, signature checked)

What fetch checks #

ppk fetch trusts nothing it reads from the source:

  • The manifest must hash to the identity in the source's ref.
  • Its form must be exactly what ppk pack writes, naming the package you asked for, with every path relative and inside the package's root.
  • Each file's content must hash to the name the manifest gives it.

If a check fails, ppk fetch stops with an error and doesn't record the package. Only the files missing from your artifact directory are copied, so fetching a new version transfers only what changed.

These checks prove that the package is the one the source's ref names. They don't prove who published it, so fetch only from sources you trust. A configured repository with an identity proves that too: a package must be in the catalog its signed pointer file leads to, at the identity the catalog gives, so a package it didn't publish, or a ref changed since, is refused.

A repository served over HTTP has no refs that ppk can list, so its catalog says which packages it has. To choose packages, ppk reads only the catalog's entries for the names it needs and each version's summary: the start of its manifest, which says what the package needs and provides but not what files it holds. A catalog also lists what provides each capability, so finding a library by its soname reads no more than that. ppk reads a manifest only when it fetches the package, and refuses one that doesn't begin with the summary it chose the package by.

ppk checks every file it reads from the repository against its hash before using it, and checks the pointer file's signature. A file that fails its check is an error: ppk doesn't try the next URL, because a server that sends the wrong file is broken or hostile. A file that fails its check is never stored.

A repository can keep its blobs compressed, as an export does, and its pointer file says so. ppk decompresses each blob as it fetches it and checks what it decompresses to, so your artifact directory always holds the files uncompressed.

When the package is already present #

By default, a chosen package already present with the same identity is skipped without writes or output. Its dependencies are still resolved and fetched if missing. With --no-deps, fetching it checks the package, copies any missing files, and prints its identity as before. If your artifact directory has a different package under the same name, version, and architecture, ppk fetch refuses to replace it:

ppk: dev.peios.hello@1.0-1?arch=noarch: already present as sha256:73a137f612f39b8ee1ffcbb7f51b7b9dc370b8662323d72b9e6b73b9d54413f8, but other has sha256:453a10dad4cb1902912919527452fa61c6420ae9152c1f02b57c1421a6d9d57b

A packed version never changes, so two different packages under one version mean the two artifact directories disagree. Find out which one is right before you use the package.

Replace a package in a bootstrap's directory #

A bootstrap builds its first packages with another system's tools, then rebuilds them with its own at the same versions. Its artifact directory isn't published until every package has been rebuilt, so nothing relies on the first builds yet. To replace one, pass --replace --no-deps with its ID:

ppk fetch 'dev.peios.hello@1.0-1?arch=noarch' --from rebuilt --artifact-dir bootstrap --replace --no-deps

The ref then names the fetched package. The replaced manifest and its files stay in the directory. Replacement requires --no-deps so that it affects only the named package. Every check above still applies. Don't use --replace on an artifact directory anything has fetched from: that breaks the rule that a version never changes.

Building a Closure

Peios / Developing for Peios / Packaging Software

Building a closure composes packages into one directory tree, the contents of a /usr. Do this when you want a set of packages together in one place, for example to check that they fit together without conflicts. For how closures work, see Closures.

Before you start #

  • Install ppk.
  • Have every package in your artifact directory, by packing it with ppk pack or fetching it with ppk fetch.
  • Have write access to the artifact directory. The default is /system/artifacts; to use a directory of your own, pass --artifact-dir.

Build the closure #

Run ppk closure with the identifier of each package:

ppk closure 'dev.peios.hello@1.0-1?arch=noarch' 'dev.peios.greetings@2.0-1?arch=noarch' --artifact-dir artifacts

ppk prints the closure's identity:

sha256:fe5cf307f0b70379e1ec36b0d8dca659782446b0d13e7140c1257cd855ba61c4

Check the result #

The closure's tree is in the closures directory of the artifact directory, named by the hash in the identity:

ls artifacts/closures/fe5cf307f0b70379e1ec36b0d8dca659782446b0d13e7140c1257cd855ba61c4/bin

The tree holds the files of every package, laid out as they appear under /usr:

hello

The closure's manifest, which lists its packages and what wants each, is beside the tree with the same name and a .manifest suffix. Running the same command again reuses the closure and prints the same identity. ppk closure asks for each package you name exactly.

The tree also holds inventory, the same lines with the closure's identity first. When mounted at /usr, this file lets ppk list identify the closure without an artifact directory. For its format, see Why each package is there.

Resolving a conflict #

If two packages give the same path different contents, ppk closure refuses and names both packages:

ppk: "bin/hello": dev.peios.hello@1.0-1?arch=noarch and dev.peios.clash@1.0-1?arch=noarch provide different entries

Nothing is written. Decide which package should provide the path, and build the closure without the other one, or change one of the packages so that the two don't overlap and pack it as a new version.

Using another closure directory #

To keep closures somewhere other than the artifact directory, pass --closure-dir. The directory must be on the same mount as the artifact directory, because the closure's files are hardlinks to its blobs. If it isn't, ppk closure refuses and leaves nothing behind:

ppk: closures: not on the same mount as the artifact directory artifacts; use --copy-files

To build the closure there anyway, such as in a sandboxed build step that has the artifact directory as a read-only input, copy its files:

ppk closure 'dev.peios.hello@1.0-1?arch=noarch' --artifact-dir artifacts --closure-dir closures --copy-files

ppk checks each blob against its hash as it copies. To see what a copy changes, including for security descriptors, see Copied files.

Running a Command in an Environment

Peios / Developing for Peios / Packaging Software

ppk run runs a command in an environment whose /usr is the closure of the packages you request and everything they need. Do this to use a set of packages without changing /usr for anything else on the machine. For how environments work, see Environments.

Before you start #

  • Install ppk.
  • Have every package in the artifact directory. If their closure doesn't exist yet, you also need write access to the closure directory; to run an existing closure you need only read access.

Run the command #

Run ppk run with the packages after -p, then --, then the command and its arguments:

ppk run -p org.figlet.figlet -- /usr/bin/figlet Peios

One -p takes every request after it, up to the next option. Requests accept bare names, quoted names with constraints such as 'org.figlet.figlet >= 2.2', and exact IDs such as 'org.figlet.figlet@2.2.5-1?arch=x86_64'. ppk resolves them against the artifact directory, including dependencies and capability requirements. It does not fetch missing packages: use ppk fetch first. Unqualified requests use ppk's own architecture, or --arch if given. An explicit architecture in a full ID selects that architecture when all requests are qualified. One resolution holds one architecture.

To use the packages of an environment profile, give the profile first. Its requests are resolved together with any after -p, with what they need, and a request the others can't satisfy fails before composition. The closure's inventory records every request, so ppk list and /usr/inventory show what was asked for as well as what was chosen. A run keeps the rest of the filesystem as it is, so a profile's links and directories don't apply:

ppk run env.toml -p dev.peios.extra -- /usr/bin/hello

The command runs with the chosen packages at /usr.

To compose exactly the IDs you name, pass --no-deps. This mode accepts full IDs with an optional architecture, as before; names and constraints are not accepted. A profile used with it must ask for one exact version of each package:

ppk run --no-deps -p org.figlet.figlet@2.2.5-1 -- /usr/bin/figlet Peios

If the named packages omit the program's loader or libraries, execution can fail with No such file or directory even when the program itself exists. The default resolution includes providers for the package's requirements.

Everything after -- is the command, so its own options aren't read as ppk's. A command without a / is looked up through PATH inside the environment.

Start a shell instead #

Leave out -- and the command, and ppk run starts /usr/bin/sh in the environment:

ppk run -p net.busybox.busybox@1.37.0-1

The shell is the closure's own, not yours, so one of the packages must provide bin/sh. Commands you run from it share its environment.

Check the result #

ppk run exits with the command's own exit status. If the command can't be started, the status is 127 when it isn't found and 126 when it isn't executable, and ppk says why:

ppk: /usr/bin/nothing: No such file or directory

Outside the command, /usr hasn't changed.

The mounted closure includes its own /usr/inventory, so ppk list inside the command reports that closure's packages. Include ppk and its runtime packages if you want to run it there. ppk list --all reads the store in the caller's root and marks membership in the mounted closure. A closure is named by its requests as well as its packages, so a closure built by an older ppk, named by its packages alone, is never mistaken for a new one.

Choosing Packages for an Environment

Peios / Developing for Peios / Packaging Software

ppk resolve chooses an exact version of every package an environment needs, from what you ask for and the packages in one or more artifact directories, and writes them as a profile. It follows each package's dependencies and requirements, as Recording Dependencies and Metadata records them. Composing a profile resolves its requests anyway, so use ppk resolve when you want the answer fixed: a profile of exact versions always composes the same environment, whatever else the artifact directories come to hold. Compose it as Composing an Environment describes.

Before you start #

  • Install ppk.
  • Have every package the environment could need in one or more artifact directories. ppk resolve only reads them.

Write the profile #

Name the packages you need after -p, and the capabilities after -c. Each request is one argument: a name, then optionally a constraint. Quote a request with a constraint, so that the shell passes it whole. Give the artifact directories after --from:

ppk resolve -p org.gnu.make 'org.gnu.gcc >= 16' -c sh --from stage1 --out root.toml

root.toml then holds one version of each package chosen:

arch = "x86_64"

[packages]
"org.git.kernel.dash" = "0.5.13.5-1"
"org.gnu.gcc" = "16.1.0-1"
"org.gnu.glibc" = "2.44-1"
"org.gnu.make" = "4.4.1-1"

Without --out, the profile goes to standard output. Like -p, -c and --from take every argument after them, up to the next option. The packages are for the architecture ppk was built for unless you give --arch.

The profile holds only packages. To give it a root layout, include a fragment that has one, or give both to ppk compose-env, as Share a layout between profiles shows:

ppk compose-env root.toml layout.toml --artifact-dir stage1 --out root

How it chooses #

  • A package you name, or that a chosen package depends on, is chosen by its name, at the newest version that satisfies the constraint.
  • A capability, requested or required, is met by a package of that name, at its own version, or by one that provides it, at the version it provides. A capability provided without a version meets any constraint.
  • Packages are settled before capabilities, at every step. So if you name a package that provides a capability, it's the one that meets it, wherever the request appears.
  • Once chosen, a package is never reconsidered. Everything later that needs it must accept the version chosen.

Because nothing is reconsidered, the order matters when two things need different versions of one package. A constraint you give on the command line is settled before what the packages need, so naming the package with a tighter constraint is how you steer the choice.

If ppk refuses #

ppk resolve writes nothing when it refuses. When something needs a version of a package other than the one already chosen, it names both, and says whether another version would have satisfied both:

ppk: org.example.b@1.0-1 depends on org.example.c < 2, but org.example.c@2.0-1 was chosen for org.example.a@1.0-1 depends on org.example.c >= 1; org.example.c@1.5-1 would satisfy both, but finding it needs backtracking, which ppk doesn't do

Request the version that would satisfy both, here -p 'org.example.c < 2', or change a constraint.

When packages of several names provide a capability, ppk doesn't pick one for you. Request the one you want by name:

ppk: org.gnu.make@4.4.1-1 requires sh, but net.busybox.busybox, org.git.kernel.dash all provide it; request one of them by name

It also refuses when no version satisfies a request, when no package provides a capability, and when one package is different in two of the directories. A version can be spelt two ways, such as 1.0~a-1 and 1.0~alpha-1. No constraint can tell those apart, so if the version it would choose has both, it refuses and asks you to remove one.

Composing an Environment

Peios / Developing for Peios / Packaging Software

ppk compose-env lays out an environment's whole root in a new directory: the closure of the packages you name as its usr, and whatever else you give it outside usr. Do this when a tool needs the environment as files, such as an image builder making an initramfs from it. For how environments work, see Environments.

Before you start #

  • Install ppk.
  • Have every package in your artifact directory.
  • Choose a directory for the root that doesn't exist yet. Every file in the root is a hard link to its blob, so the directory must be on the same mount as the artifact directory, unless you compose on another mount.

Compose the root #

  1. Describe the environment in a profile, such as env.toml. For the format, see Environments:

    arch = "noarch"
    
    [packages]
    "dev.peios.hello" = "1.0-1"
    "dev.peios.greetings" = "2.0-1"
    
  2. Run ppk compose-env with the profile and --out:

    ppk compose-env env.toml --artifact-dir artifacts --out root
    

ppk resolves the profile's requests against the artifact directory, with the packages they depend on or require, and prints the identity of the closure of the packages chosen:

sha256:fe5cf307f0b70379e1ec36b0d8dca659782446b0d13e7140c1257cd855ba61c4

root/usr holds the packages' files, and the links they claim under /usr, such as dash's /usr/bin/sh. Nothing is written to the artifact directory.

root/usr/inventory records the closure identity, and each package's full ID and identity and what wants it. List them without a store:

ppk list --root root

To list a store and mark the packages in this root, run:

ppk list --all --root root --artifact-dir artifacts

Each line has * for a package whose ID and identity are in this root, or a space otherwise, then a space and the full ID. Both commands sort by full ID. For validation and missing-inventory behavior, see Identifying the mounted closure.

To add packages to the profile's, or to compose without a profile, name them after -p. One -p takes every package after it, up to the next option, so the profile must come first:

ppk compose-env env.toml -p dev.peios.extra@1.0-1 --artifact-dir artifacts --out root
ppk compose-env -p dev.peios.hello@1.0-1 dev.peios.greetings@2.0-1 --artifact-dir artifacts --out root

These packages are all for the architecture ppk was built for. To name another, give it in the package, as dev.peios.hello@1.0-1?arch=noarch, or give arch in the profile.

Add what lies outside usr #

A package can only place files under /usr. The one exception is a link it claims elsewhere, such as /init, which the root holds because the package is in it. Anything else the root needs comes from the profile or the command line:

  • A link, from the profile's symlinks or --symlink <path>:<target>. The target is written as given, unless it starts with a colon in the profile, or a second colon on the command line, which stands for /usr: "bin" = ":bin" and bin::bin both link bin to usr/bin.
  • An empty directory, such as a mount point, from the profile's dirs or --dir <path>.
  • The packages themselves, from the profile's include_artifacts = true or --include-artifacts, in the root's own artifact directory, system/artifacts, as hard links, so that ppk inside the environment finds them.
  • --copy-artifacts does the same with copies, checking every manifest and blob as ppk fetch does, and wins over hard links.

Paths are relative to the root. The options add to what the profile gives:

ppk compose-env env.toml --artifact-dir artifacts --out root --symlink bin::bin --dir tmp --include-artifacts

The root then holds bin, a link to usr/bin, an empty tmp, the packages' artifacts in system/artifacts, and usr.

For a live image, ppk-live-root composes the root from the medium's profile and store, then runs skeleton apply on it. That applies the root skeleton file in the root's own /usr/share/skeleton, which dev.peios.fsbase ships, so the root gets its directories outside /usr and the /lib64 link. Without the file the hook warns and continues. It then copies the medium's /lcl tree into the root if present. The copy preserves modes and a copy failure fails the boot. This carries image policy, including registry seed queues and executable autorun scripts, outside /usr. peinit applies the common and live seed queues after registryd starts; an installer owns promotion of the install queue.

Share a layout between profiles #

When several environments need the same root layout, write it once as a fragment, such as layout.toml:

dirs = ["proc", "sys", "dev", "tmp"]

[symlinks]
"bin" = ":bin"
"lib64" = ":lib"

Then include it from each profile. The path is relative to the profile's own directory:

include = ["layout.toml"]

[packages]
"dev.peios.hello" = "1.0-1"

You can also give several profiles to ppk compose-env, which merges them in the same way, so a profile that names only packages can be composed with a layout:

ppk compose-env packages.toml layout.toml --artifact-dir artifacts --out root

If two of them disagree, ppk names both files and composes nothing:

ppk: other.toml links "bin" to "usr/sbin", but layout.toml links it to "usr/bin"

Compose on another mount #

A hard link can't cross a mount, even between two mounts of one filesystem. To compose a root on another mount than the artifact directory, such as a fresh tmpfs, or in a sandboxed build step that has the artifact directory as a read-only input, copy what would be linked:

  • If the root has no artifact directory of its own, pass --copy-files. root/usr then holds a copy of each file, checked against its hash, and the root holds nothing else from the store:

    ppk compose-env env.toml --artifact-dir artifacts --out root --copy-files
    
  • If it needs one, pass --copy-artifacts, which copies the packages into the root's system/artifacts. usr then hard links to that.

To see what a copy changes, including for security descriptors, see Copied files.

If ppk refuses #

ppk compose-env leaves nothing behind when it refuses. It checks all but the hard links before it writes anything. It refuses a root that already exists:

ppk: root: already exists

It refuses a path under a link you also gave, because creating it would follow the link out of the root:

ppk: "bin/extra": under "bin", which is a symlink

It refuses another version of a package the profile holds, since an environment holds one version of each:

ppk: dev.peios.hello@2.0-1?arch=x86_64: the environment holds dev.peios.hello@1.0-1?arch=x86_64 already

It refuses two packages that claim one path, even as links to one target, since a claim says which package provides the name. Choose one of them:

ppk: "/usr/bin/sh": claimed by both org.git.kernel.dash@0.5.13.5-1?arch=x86_64 and net.busybox.busybox@1.37.0-1?arch=x86_64

It refuses a claimed link outside usr that the profile or the options also give as a link or a directory, or that a path given lies under:

ppk: "init": claimed by org.git.kernel.dash@0.5.13.5-1?arch=x86_64, but the environment links it

It also refuses packages that conflict, in the same way as ppk closure, including a claimed link that is a path in a package's files, and any path that is usr or lies under it.

Publishing a Repository

Peios / Developing for Peios / Packaging Software

A repository is an artifact directory that says what it publishes. Its catalog lists every version it holds. Its indexes each hold one version of each package for each architecture: leading always holds the newest, and a snapshot holds a release, unchanged for ever. Its channels, such as stable, each follow an index or another channel.

One file, the pointer file, says what the catalog, each index and each channel are, and it is the only file that is signed. Everything else is named by its hash, from there.

Before you start #

  • Have the packages in an artifact directory, as Creating a Package and Fetching a Package describe.

  • Have a signing certificate that holds the Repository warrant, and its secret key. The pso command issues both. The certificate's Name warrant has to cover the name your repository signs as, its identity, such as pkgs.example.com.

  • Write a signer file that names them:

    identity = "pkgs.example.com"
    certificate = "signer.cert"
    key = "signer.key"
    carry = ["intermediate.cert"]
    

    A path that isn't absolute is beside the signer file. carry lists the certificates above the signing certificate, in order upward, so that a machine reading your repository for the first time has the whole chain. Leave it out if the signing certificate was issued by a top-level.

    If the key is sealed under a passphrase, as pso makes keys unless told otherwise, add passphrase-file, a file whose first line is the passphrase. Without it, ppk asks for the passphrase on the terminal, and fails if there isn't one. Keep the passphrase file with the same care as the key: together they sign.

    Keep the key out of the repository and out of version control. Every ppk repo command that publishes reads the signer file from --signer, or from $PPK_REPO_SIGNER.

Publish #

Run ppk repo update:

ppk repo update --artifact-dir artifacts --signer signer.toml

It writes the catalog and leading, signs the pointer file, and prints it:

sequence 1
signed 2026-11-13T13:11:46Z
catalog sha256:09cc9d05541917d9894cb2fc71a05373509789c0218b9ca5b7284ed6cca28619
provides sha256:f6ca384d90eb3223b077a93785c13ea3a9fb5ee53957f489e93cbd3b959e8015
index leading sha256:f5e090f9de6441810fab9e15909770d071687375e9f35c35d73244302c877ab6

The sequence goes up by one each time you publish. Run ppk repo update again after adding packages.

Besides the catalog, ppk repo update writes each version's summary, the part of its manifest that says what it needs and provides, and the catalog's provides tree, which lists what provides each capability. A machine choosing packages from the repository over HTTP reads those for the names it needs, not every manifest the repository holds. A repository published by an earlier ppk gets them the next time you run ppk repo update, with the same packages.

leading holds only what can be installed from it. A package whose dependencies or requirements leading can't satisfy is left out, with a warning naming what it lacks, and so is anything that then lacks it. To make that an error instead, pass --strict.

Make a release #

Take a snapshot of leading as the release's index, then point channels at it:

ppk repo snapshot 2026.10.0 --artifact-dir artifacts --signer signer.toml
ppk repo channel 2026.10 2026.10.0 --artifact-dir artifacts --signer signer.toml
ppk repo channel stable 2026.10 --artifact-dir artifacts --signer signer.toml
ppk repo channel unstable leading --artifact-dir artifacts --signer signer.toml

A snapshot never changes, so its name must be new. To fix a release, take a new snapshot, 2026.10.1, and move the release's channel to it. When a release gets no more fixes, mark its channel ended, so that a machine following it can tell:

ppk repo channel 2026.10 2026.10.1 --ended --artifact-dir artifacts --signer signer.toml

Take a version back #

To stop new resolutions choosing a version, yank it. Anything that asks for exactly that version still gets it:

ppk repo yank 'org.example.tool@1.2-1?arch=x86_64' --artifact-dir artifacts --signer signer.toml

--undo restores it. To remove a version altogether, delete it, giving a reason:

ppk repo delete 'org.example.tool@1.2-1?arch=x86_64' --reason 'legal takedown' \
    --artifact-dir artifacts --signer signer.toml

That removes its ref, its manifest, and every file of it that no other package shares. The catalog keeps a tombstone with the reason, so that anything still asking for it can say why it's gone. Snapshots that hold it aren't changed; publish a new one without it to keep a release installable.

Install from a repository #

Anything that resolves packages from a repository can ask for what an index or channel holds, with # after the name:

ppk fetch 'se.curl.curl#stable' --from artifacts
ppk run -p 'se.curl.curl#2026.10.0' -- /usr/bin/curl --version

The version the index holds is chosen, and so is everything it depends on or requires: a request for a release takes the release's versions of what it needs too. A constraint after the index, as in 'se.curl.curl#stable >= 8', must also hold. A closure records the index of each request that named one, so its inventory shows what it was asked for from where.

A yanked version is chosen only by a request for exactly it, such as 'org.example.tool = 1.2-1'. A request that only a deleted version would satisfy fails, giving the reason it was deleted.

Export a compressed copy #

Most of a repository is its blobs, the content of its packages' files. The repository itself keeps them uncompressed, because machines and builds that read it directly link them into closures. To serve it, export a copy whose blobs are compressed:

ppk repo export --artifact-dir artifacts --to export --signer signer.toml

ppk repo export writes export as the repository as it was last published, with each blob compressed with zstd under its own name, and prints the pointer file it signed, which says blobs zstd. Nothing else is compressed, and every package keeps its identity. ppk decompresses each blob as it fetches it and checks it against its hash before storing it.

Run ppk repo export again after each ppk repo update. It compresses only the blobs the export doesn't hold yet, and removes anything you deleted from the repository. Compression uses zstd level 12 unless you pass --level, from 1, the fastest, to 22, the smallest.

Serve the repository over HTTP #

Every file of a repository but repository and repository.pso is named by its hash and never changes. A static web server can serve the repository's directory, or its export, as it is, with no other software. Machines then fetch from it by its URL, the URL of that directory:

ppk repo add peios https://pkgs.peios.org/ --identity pkgs.peios.org --track stable

ppk reads each file at the URL followed by the file's path in the directory, such as https://pkgs.peios.org/repository for the pointer file. It doesn't need the server to list directories or answer range requests.

A copy of the repository on another server, such as a cache on your own network, serves machines the same way. A cache can keep every file but repository and repository.pso for ever. A machine given the cache's URL before the repository's own tries the cache first and falls back to the repository for anything the cache can't serve. Because every file is checked against its signature or its hash, a cache never has to be trusted for what it sends.

Check what a repository publishes #

ppk repo show prints the pointer file. Give the repository's identity to check its signature too:

ppk repo show --artifact-dir artifacts --identity pkgs.example.com

The check succeeds only if a root this build of ppk holds vouches for the chain that signed the repository. For a repository whose top-level you enabled yourself, add --unrooted.

--artifact-dir also takes the URL of a repository served over HTTP, to check what a server is publishing.

For the files a repository holds, see ppk(1).

Peios ISOs

Peios / Developing for Peios / Building ISOs

A Peios ISO is a disc image that boots a live Peios system under UEFI, on a virtual machine or on a computer it is written to as a USB stick. peiso builds one from Peios packages, as a spec describes. For what a package is, see Packages.

What an ISO holds #

An ISO holds six things:

  • A unified kernel image (UKI). One EFI program holding the kernel, its command line, and the initramfs, the small filesystem the kernel starts from. It sits in an EFI system partition image, where UEFI firmware looks for the loader of a removable medium, so the firmware starts it directly.
  • A package store, at /artifacts. It holds every package the spec names and every package those depend on or require, laid out as ppk stores them.
  • The live system's image, at /live.sqfs. It is the live system's /usr as a read-only squashfs image: the packages the spec places in the live system and everything they need, with the inventory a composed /usr has. Each file and directory carries its security descriptor, and each signed file its signature, which the store's plain files on the medium can't, because ISO9660 holds no extended attributes.
  • The live system's profile and layout. /live.toml is the environment profile the image is the closure of: it asks for the packages the spec places in the live system, each at exactly the version peiso chose. peiso checks, when it builds the ISO, that resolving it from the store gives exactly those packages. /live.layout lists the links and empty directories the spec gives the live system's root outside /usr. For profiles, see Environments.
  • What an installer composes an installed system from, if the spec can be installed: /install/system.toml and /install/initramfs.toml, the requests of its /usr and its initramfs, each pinned to the version peiso chose, and checked as /live.toml is.
  • The medium's identifier, at /peios-medium. It is the SHA-256 hash of the packages, the profiles and the image, so the same spec and packages always make the same medium.

Where each package goes #

A spec places each package in one or more of these places:

  • The live system, whose /usr is the medium's image.
  • The initramfs, which prelude, Peios's early-boot init, runs from. Anything that runs before the live system exists belongs here: prelude itself, the live-boot hook that mounts the live system, and what the hook runs, such as a shell. The initramfs is held in memory, so it holds only what boot needs.
  • The installed system, which an installer composes from the medium, and its initramfs, which mounts the installed system's disk. A spec that places nothing there can't be installed.
  • The medium only, carried in the store and nowhere else. Such a package can be fetched from the medium later, which makes an ISO a library of packages for a machine with no network.

By default, a package goes in the live system and the installed system. Every package is in the store, wherever else it goes.

A package comes with what it needs. peiso resolves the packages the spec names together, with ppk's resolver, and carries one version of each package that they depend on or require. Each place then holds the packages placed there and everything they need, at the versions the store holds.

A dependency goes where the package that needs it goes. A package meant for the initramfs, such as a boot hook, must be placed there by the spec, even when a package of the live system depends on it. For the details, see ISO Specs.

How it boots #

  1. UEFI firmware starts the UKI from the medium's EFI system partition, and the kernel starts prelude from the initramfs.
  2. prelude runs the live-boot hook, which finds the medium: it tries each disc, disk and stick with an ISO9660 filesystem, waiting a few seconds for a USB stick to appear, and keeps the one whose /peios-medium matches the identifier the initramfs holds. Another Peios medium attached alongside is never taken for it.
  3. The hook checks the medium's image against the SHA-256 hash the initramfs holds, and mounts it read-only as the system's /usr, under a root on a fresh tmpfs. The system's /usr/inventory records what the spec asked for and what was chosen. The hook makes what /live.layout lists, and applies the system's root skeleton file, which gives the system its directories outside /usr and the /lib64 link. It moves the medium's mount to /media/peios in the system, where the image is read from and an installer reads the store.
  4. prelude switches to the live system and starts its init.

If the hook can't find the medium, or the image isn't the one the initramfs names, prelude opens its recovery shell when the kernel command line holds rd.shell.

The live system reads its /usr from the medium, so the medium must stay attached while it runs. Everything else lives in memory, so nothing the system writes survives a restart.

Building an ISO

Peios / Developing for Peios / Building ISOs

peiso build builds a bootable Peios ISO from packages you have built. Do this to try a set of packages as a whole system, or to make a medium to boot a machine from. For what an ISO holds, see Peios ISOs.

Before you start #

  • Install peiso, and mkirf and mkuki from peiosutils, or know where they are.
  • Install mkfs.vfat, mtools, xorriso, and mksquashfs from squashfs-tools 4.6 or later. peiso runs them, without any privilege.
  • Have the packages in an artifact directory, such as one that pekit packs into. The live system needs a shell and an init, and the initramfs needs prelude, the live-boot hook, and a shell. Packages bring what they depend on or require, so the artifact directory needs those packages too.
  • Have the kernel package, dev.peios.kernel, in the artifact directory too, or a Peios kernel image built with its EFI stub.

Write the spec #

Write the spec, such as peios.toml, beside the artifact directory. Paths in it are relative to the spec:

disable_default_repos = true

[[repository]]
filepath = "artifacts"

[kernel]
package = "dev.peios.kernel"
cmdline = "console=ttyS0 rd.shell"

[[package]]
name = "net.busybox.busybox"
initramfs = true

[[package]]
name = "dev.peios.ppk"

[[package]]
name = "dev.peios.prelude"
liveboot = false
initramfs = true

[[package]]
name = "dev.peios.live-root"
liveboot = false
initramfs = true

The kernel comes from its package, which the ISO carries in its store. The live system is busybox and ppk, and the initramfs holds busybox, whose shell the live-boot hook runs, with prelude and the hook itself. Each place also holds every package its packages depend on or require, and each package is carried at the newest version the artifact directory holds, unless the spec gives a version. For every key, see ISO Specs.

Check what the spec brings #

Run peiso resolve to list every package the ISO would carry, without building it:

peiso resolve peios.toml

Each line is a package, the places that hold it, and what first asked for it. A package in neither place is in the store only:

dev.peios.kernel@0.25.0-indev-1?arch=x86_64 store (the request for dev.peios.kernel)
dev.peios.prelude@0.0.7-1?arch=x86_64 initramfs (the request for dev.peios.prelude)
org.gnu.glibc@2.44-1?arch=x86_64 liveboot,initramfs (net.busybox.busybox@1.37.0-1 requires libc.so.6)

Build the ISO #

Run peiso build with the spec and where to write the ISO:

peiso build peios.toml --out peios.iso

Give --mkirf, --mkuki and --mksquashfs with their paths if they aren't on PATH. peiso says what it is doing, and prints the ISO's path when it is done:

peiso: fetching net.busybox.busybox@1.37.0-1?arch=x86_64
peiso: fetching dev.peios.ppk@0.1.0-1?arch=x86_64
peiso: fetching dev.peios.prelude@0.0.7-1?arch=x86_64
peiso: fetching dev.peios.live-root@0.1.0-1?arch=x86_64
peiso: fetching dev.peios.kernel@0.25.0-indev-1?arch=x86_64
peiso: writing the live system's image
peiso: composing the initramfs
peiso: building the UKI
peiso: writing the ISO
peios.iso

Boot it #

Boot the ISO in QEMU with OVMF, its UEFI firmware. OVMF writes to its variables, so give it a copy of them:

cp /usr/share/OVMF/OVMF_VARS_4M.fd vars.fd
qemu-system-x86_64 -enable-kvm -m 1G -machine q35 -nographic \
    -drive if=pflash,format=raw,readonly=on,file=/usr/share/OVMF/OVMF_CODE_4M.fd \
    -drive if=pflash,format=raw,file=vars.fd \
    -cdrom peios.iso

prelude reports each step of boot on the console, and starts the live system's init. The live-boot hook says where it found the medium, and checks the live system's image before it mounts it:

ppk-live-root: found the medium on /dev/sr0
ppk-live-root: checking the live system's image

To boot a computer, write the ISO to a USB stick and start the computer from it. The ISO is also a disk with an EFI system partition, so it boots from a stick as it does from a disc.

If peiso refuses #

peiso checks the spec and resolves every package before it builds anything. It refuses a package, or a dependency, that no repository holds at a version that will do, and says what needed it:

peiso: dev.peios.peios-experimental@2026.8-11 depends on dev.peios.bootconfig >= 0.21.0-alpha11-1, but no artifact directory holds dev.peios.bootconfig for x86_64: artifacts

It refuses a spec with no package in the live system, or none in the initramfs, since such an ISO couldn't boot. It also refuses what a spec can say but Peios can't do yet, such as a repository on the network, and says why.

If a tool it runs fails, peiso stops and shows what the tool said.

ISO Specs

Peios / Developing for Peios / Building ISOs

An ISO spec is a TOML file that says which packages an ISO carries, where they come from, and where each goes. Paths in it are relative to the spec's directory. Any key not listed here is an error, so that a misspelt key can't silently change nothing.

Top-level keys #

KeyDefaultMeaning
editionThe Peios edition the live system is, such as "Experimental". Its package is dev.peios.peios- followed by the edition in lowercase, such as dev.peios.peios-experimental, and the live system holds it and everything it needs.
edition_packageThe package of an edition that isn't one of Peios's own, such as com.example.peios-inhouse, in place of edition. Give one or the other.
versionthe newestThe edition package's version, as for a [[package]].
disable_default_reposfalseLeave out the default repository, pkgs.peios.org. It isn't available yet, so a spec must set this to true and give a [[repository]].

Repositories #

Each [[repository]] is a place packages come from. A package is taken from the first repository, in the order given, that holds the version chosen. If two hold the same version of a package, they must agree on what it is.

KeyMeaning
filepathAn artifact directory. Required.

Kernel #

[kernel] is the kernel the ISO boots: a package, such as dev.peios.kernel, or a file. Give one or the other.

KeyDefaultMeaning
packageThe package holding the kernel, at usr/lib/modules/vmlinuz. The ISO carries it in its store, with what it needs, and a [[package]] naming it says where else it goes.
versionthe newestThe kernel package's version, as for a [[package]].
fileA kernel image on this machine, built with its EFI stub.
cmdlineemptyThe kernel command line. rd.shell makes prelude open its recovery shell if boot fails.

Packages #

Each [[package]] is a package the ISO carries, and says where it goes. There are four places: the live system's /usr, an installed system's /usr, the live medium's initramfs, and an installed system's initramfs. Every package is in the ISO's store wherever else it goes, so a package in none of them is carried for fetching from later. An edition's package can't also be given as a [[package]].

KeyDefaultMeaning
nameThe package's name. Required, and given once.
versionthe newestThe versions that will do, as a version constraint, such as ">= 1.2". A version on its own, such as "1.2.0-1", is that version exactly. The newest version that will do is carried.
roottrueShorthand for liveboot and installed together.
livebootrootWhether the live system holds the package and everything it needs.
installedrootWhether an installed system's /usr, its SYSTEM closure, holds it.
initramfsfalseShorthand for liveboot_initramfs and installed_initramfs together.
liveboot_initramfsinitramfsWhether the live medium's initramfs holds it.
installed_initramfsinitramfsWhether an installed system's initramfs, its INITRAMFS closure, holds it.

A place named on its own overrides its shorthand. So most packages need none of these, a package only for the live medium has installed = false, and one only for the initramfses has initramfs = true and root = false. The live medium's boot hook has liveboot_initramfs = true and an installed system's installed_initramfs = true, each with root = false.

At least one package must be in the live system, and at least one in the live medium's initramfs. A spec with no package in an installed system can't be installed from; one with packages there must also have one in an installed system's initramfs.

What packages bring #

A package brings every package it depends on, and a package providing each capability it requires, such as sh or libc.so.6. peiso chooses them with ppk's resolver, from the edition's package, the kernel package, and every [[package]] together:

  • Each package name is chosen once, at the newest version that satisfies what asks for it first. Anything that asks for another version is an error, which names both.
  • A capability is satisfied by a package already chosen if one provides it. Otherwise, the package providing it is chosen. If several packages provide it, name the one to carry with a [[package]].

The ISO's store holds every package chosen. The live system holds the edition, each package with liveboot = true, and everything they need, and each other place likewise holds its packages and everything they need. An installed system holds the edition too. A place takes the versions and providers the store holds, so the live system and the initramfs never hold two versions of a package.

A dependency goes where the package that needs it goes, and nowhere else. A package of the live system can depend on one meant for the initramfs, such as dev.peios.live-boot on its boot hook, dev.peios.live-boot-irf. The live system then holds the hook as well, and the initramfs holds it only if the spec places it there.

To see what a spec brings before building it, run peiso resolve. See Building an ISO.

Registry seeds #

Packages ship seed masters under /usr/share/regim, but the spec chooses which the image applies. No release metadata is read for this policy.

[seeds]
apply = ["base-service"]
live = ["seeds/console-shell.reg"]
install = ["first-boot"]

All three lists default to empty. A bare seed name selects usr/share/regim/<name>.reg from the composed live closure, including dependencies. A package carried only in the store or initramfs cannot supply it. A relative path ending in .reg selects a file beside the spec, staged using its filename. Names use ASCII letters, digits, dots, underscores, and hyphens. Absolute file paths, unknown keys, and duplicate destination names, within or across queues, are errors.

ListMedium directoryApplied on
apply/lcl/policy/autoapply.dThe live medium and an installed system.
live/lcl/policy/autoapply.live.dThe live medium only.
install/lcl/policy/autoapply.install.dAn installed system, after an installer promotes it.

When any seed is named, peiso also stages the executable /lcl/policy/autorun.d/10-apply-seeds.sh. The live-root hook copies the medium's /lcl into the live system's root, preserving modes. After registryd starts, peinit runs the script, applying the common queue and then the live queue with reg apply --once-delete. The install queue remains untouched. An installer must remove the live queue and promote the install queue into the target's common queue.

Seed files have mode 0644 and the script has mode 0755. Their paths, contents, and modes contribute to the medium identifier. With no seeds, peiso stages no /lcl tree.

Layouts #

[initramfs] and [liveboot] give what the initramfs and the live system hold outside /usr, written as an environment profile's keys are. For the format, see Environments.

KeyMeaning
symlinksEach link's path and target. A target that starts with : is in usr.
dirsEmpty directories.
includeProfile fragments whose links and directories the layout holds as well, each relative to the spec's directory. A fragment that names packages is refused, since the spec chooses those.

A table replaces the default, rather than adding to it. The defaults are:

[initramfs]
dirs = ["proc", "sys", "tmp"]

[liveboot]
symlinks = { "bin" = ":bin", "sbin" = ":sbin" }

The initramfs's /init isn't in its layout: prelude's package claims it, and composing the initramfs creates the link. A layout can't also give a path that a package claims.

A layout needs no directories or links that fsbase's skeleton gives, such as /var, /lcl, /tmp or /lib64. Each root gets those from the root skeleton file its own closure holds, at /usr/share/skeleton. Carry dev.peios.fsbase in the live system and dev.peios.fsbase-irf in the initramfs. peiso applies the initramfs's file after composing it, and the live-boot hook applies the live system's at boot, with each directory's security descriptor. An initramfs can't hold descriptors, so its directories get none. peiso warns when the initramfs has no skeleton file.

Don't list a skeleton directory in [liveboot]. The layout's directories are made first, and the skeleton leaves an existing directory as it is, so it would lose the skeleton's descriptor.

Refused until supported #

A spec can already use these keys, but peiso refuses each, saying why, until Peios can do what it asks:

KeyNeeds
url in a [[repository]]Repositories on the network.
autoinstall, offerinstall in a [[package]]An installer.

Test Ownership

Peios / Developing for Peios / Qualification

Keep a test beside the component whose contract it checks. A test that needs a VM still belongs to that component if its assertions concern that component's behavior. The VM is apparatus, not an ownership rule.

Choose an owner #

Test or helperOwner
Unit tests and isolated API checksThe component
Native contract tests using a real kernelThe component
Behavior across several real servicesIntegration Tests
Complete boot, upgrade, and release qualificationIntegration Tests
Generic VM lifecycle and host utilitiesProvium
Component-specific fixtures and helpersThe component

For example, a resolver test using a stub network manager belongs to resolvd. A scenario asserting behavior across real resolvd and netd belongs to Integration Tests. An authd event test can use eventd as observation apparatus while checking authd's documented event contract.

Keep one maintained copy #

A component exports its suite through tests/integration/suite.json. The kernel uses peios/tests/integration/suite.json. The manifest lists owned test files and maps helper and fixture sources into a virtual layout. Cross-component scenarios have a manifest in the central repository.

The central suites.lock.json records each repository's exact commit and manifest hash. The runner reads files from those Git objects and assembles the layout in a fresh run directory. It rejects duplicate export paths. Shared helpers come from their owning repositories, not copied snapshots inside each consumer.

Keep fast checks in ordinary component CI. Run native conformance with supplied images and tools. Use the central runner for both component and system selections, so both produce the same provenance and result format.

Preserve migration evidence #

The migration map accounts for 604 imported test files. Imported assertions retain their historical specification references. One resolver test moves its inline probe into a supplied tool; its assertions remain unchanged. The map records source paths and hashes; helper adaptations are listed separately in migration-adaptations.json.

The central legacy package-event scenario exercises .peipkg. It does not establish compatibility with PPK blobs and manifests. Archived recipes preserve fixture requirements without activating retired image builders.

Running Conformance Tests

Peios / Developing for Peios / Qualification

Run the host checks before using the qualification runner. They need pekit on a Linux host:

pekit test

The qualification runner itself needs Python 3.11 or later and Git.

A native run also needs a suitable QEMU host, the required privileges, networking tools, and Peios images. Provium checks host prerequisites. Prepare images outside the runner, with the fixtures and services described by the selected suite. The archived profile recipes document those inputs.

Prepare the composition #

Copy examples/composition.json. Replace every placeholder with a supplied path, its hash, and the exact component source revisions in the image. Calculate a file or directory hash with:

./peios-qualify hash /path/to/artifact

Supply signed guest tools when a test requests them. Their signatures must match the image's trust policy. The runner checks hashes, not signatures; verify signature authority when preparing the supplied artifacts.

Use kernel-only for kernel and network apparatus, prelude for early boot, and peinit for full-system service tests. A component selection can need more than one profile. Prelude tests also require PT_MKIRF to name a recorded artifact; no sibling build or host-path fallback is used.

Select and run tests #

Keep all repositories named by the lock available, including helper owners. The runner reads their recorded Git objects without switching branches. List a component's test files:

./peios-qualify list --lock suites.lock.json --suite authd

Stage a run without starting Provium:

./peios-qualify prepare --lock suites.lock.json --suite authd \
  --composition /path/to/composition.json --output /path/to/prepared-run

Run with a fresh output directory. Avoid single quotes and control characters in that path because the imported helpers use shell commands:

./peios-qualify run --lock suites.lock.json --suite authd \
  --composition /path/to/composition.json --output /path/to/run \
  --timeout-seconds 3600

Repeat --suite for several components. Select system for the central scenarios; omit --suite for all test files. An empty selection is an error. Slow cases are included. A timeout stops the runner and its child processes.

Component bundles also expose a check-integration script. Set PEIOS_QUALIFY to the central executable and supply the same lock, composition, and fresh output path. These entry points do not build images.

Test a candidate #

Commit the candidate suite and use a clean checkout. Add an explicit --candidate authd=/path/to/authd to select its committed test source. This overrides one suite pin and records the selected commit. It does not replace the image or infer which binaries the image contains.

Update the supplied composition when testing candidate binaries. Keep the test revision and image component revision distinct in the result record. After reviewing permanent suite changes, refresh the lock deliberately:

./peios-qualify pin --catalog suites.json --output suites.lock.json

Review the lock diff before committing it. Pin updates are separate from running tests and do not publish any repository.

Composition Format

Peios / Developing for Peios / Qualification

A composition is a JSON object with format set to 1. Paths in artifacts are absolute or relative to the composition file. Every artifact has a path and sha256. Other fields refer to an artifact with an object such as {"artifact": "kernel"}.

Fields #

FieldMeaning
modesystem by default; harness for local runner checks
artifactsNamed regular files or directory trees and their hashes
runnerArtifact reference for the executable Provium runner
componentsImage component names mapped to exact Git commit IDs
profilesNamed boot profiles using recorded artifact references
host_toolsExecutable names mapped to supplied artifact references
guest_toolsTest tool names with unsigned and optional signed inputs
environmentExplicit PT_* and supported *_TEST_* artifacts
packagesOptional declared package identities and manifest references
file_timeout_secondsPer-file timeout; default 300 seconds

System mode requires a declared component composition, boot profiles, and a recorded qemu-system-x86_64 executable. Harness mode uses Provium's local backend, skips VM host preflight, and never produces OS qualification. The host runtime remains a dependency in either mode. Local mode requires selected test manifests to declare harness_only: true; ordinary native suites cannot run on the local backend.

The image composition is an operator declaration. The runner does not inspect an image to prove that its binaries came from those commits. Package declarations use name, version, arch, and manifest. The runner checks that each supplied manifest has the declared identity; it does not resolve dependencies, install packages, or verify image contents.

Profile inputs #

A profile accepts kernel, initrd, root, cmdline_file, and agent_overlay_path as artifact references. It also accepts cmdline, guest_os, inject_agent, and agent_boot_timeout as ordinary values. Every profile needs a kernel or a root containing one. Agent injection requires an explicit agent overlay.

A disks entry accepts path, id, readonly, and mediated. Its path is an artifact reference. Writable disks use separate working copies; read-only media keep their supplied snapshot. Final working-disk hashes are recorded separately from original input hashes.

Build commands and profile discovery directories are rejected. The runner passes --no-build to Provium and writes its own explicit configuration. The historical build.sh and sign.sh helper names resolve supplied guest tools; they do not build or sign anything.

Hashes and storage #

A file hash is SHA-256 of its bytes. A directory hash covers sorted relative paths, modes, file hashes, and link targets using the runner's canonical JSON encoding. Use peios-qualify hash for trees. Links must be relative and remain inside the tree. Special files and symlink artifact roots are rejected.

Each run copies and verifies supplied artifacts before execution. Keep enough disk space for those copies and writable disk snapshots. The output directory must not already exist. Preserve the result directory with the release evidence; its hashes are useful only while the corresponding inputs remain available.

Candidate binary inputs include PEINIT_TEST_BINARY, TRUSTD_TEST_BINARY, LOREGD_TEST_BINARY, NETD_TEST_BINARY, RESOLVD_TEST_BINARY, NSS_NET_TEST_BINARY, and NSS_IDENTITY_TEST_BINARY. Service seed inputs use NETD_TEST_SERVICE or RESOLVD_TEST_SERVICE. All are artifact references. The resolver probe uses guest_tools.pt-nss.unsigned; its source and dynamic linking requirements are in the resolver's integration bundle.

Qualification Results

Peios / Developing for Peios / Qualification

The runner writes run.json before staging inputs and updates it as the run progresses. It records suite commits, source hashes, supplied artifact hashes, the composition, command, environment, and host details. stdout.jsonl preserves Provium's per-file reports. stderr.log preserves diagnostics, and events.msgpack preserves the event stream.

Status and exit codes #

StatusMeaningExit code
preparedInputs staged; no tests executed0
passedEvery selected file reported successful cases0
incompleteAt least one case was skipped3
failedFailure, timeout, missing report, or changed immutable input1
blockedInputs could not be staged or validated2
interruptedThe user interrupted execution130

Malformed arguments also return 2. A file with no reported cases is a failure. Missing or duplicated file reports fail the run. A zero exit code from Provium cannot hide failed cases or an incomplete report set.

qualification is true only for a passed system-mode run. It applies to the recorded selection and supplied composition, not an entire OS release. A harness run can pass while qualification remains false.

Release evidence #

Keep component fast checks, native conformance, system scenarios, and release acceptance as separate gates. A successful host check establishes runner behavior; it does not establish that a Peios image boots or that its services work together.

Review the selected suites and skipped cases before accepting a release. Also review the provenance declaration: hashes identify bytes, but do not establish signing authority or prove the declared source-to-image mapping. The runner records selected host executable hashes; host libraries, QEMU data files, privileges, and kernel behavior remain environmental inputs.

Candidate overlays, such as PT_EVENTD_ROOT, must be supplied as hashed artifacts. A test that requires an absent candidate overlay can skip; the result then remains incomplete. Do not treat that as a successful release gate or suppress the skip to make the result green.

1.1 Library Conventions

Peios / Developing for Peios / SDK Reference / Library Conventions

libpeios and librsi share an error model and explicit ownership rules. Check each result before using output parameters, and follow the installed header for the function's particular buffer contract.

1.1.1 Results and errors #

Most int functions return zero or a new file descriptor on success and -1 with errno on failure. Length-returning functions use ssize_t. Predicate functions and void builder setters have different contracts; read their declarations before choosing an error check.

Read errno only after a function reports failure. Save it before cleanup calls if the caller needs to report the original error.

1.1.2 Buffers and builders #

Many libpeios encoders support a zero-capacity size probe. Allocate the reported space and repeat the call. String lengths exclude the terminating NUL, so string buffers need one additional byte.

Registry reads use lengths stored in parameter structures and report a short buffer through ERANGE. They do not use the same return convention as security encoders. Recheck sizes when retrying reads of mutable data.

Builders retain their first error until it is inspected or the result is requested. Free each builder with its matching library destructor. Do not pass a library-owned builder to free().

1.1.3 Borrowed data #

Parsed views borrow the caller's input bytes. Keep those bytes alive and unchanged until every view and derived pointer is unused. Copy borrowed data before retaining it beyond the input buffer's lifetime.

Registry source request decoders follow the same rule. Reading the next request into a frame buffer invalidates views into the previous frame.

1.1.4 File descriptors #

Close owned descriptors when their use ends. Passing a descriptor to an operation does not transfer ownership unless the header states otherwise. A successful operation does not grant ownership of a descriptor merely mentioned in an output structure; use that function's documented contract.

Start with result conventions and memory ownership for examples.

1.2 How Results Are Returned

Peios / Developing for Peios / SDK Reference / Library Conventions

Every entry point reports success or failure through its return type. There are three return shapes, and the shape tells you how to read the result.

1.2.1 int — a file descriptor, or zero #

A function returning int returns either:

  • a file descriptor (a non-negative int), when its job is to open something — a token, a registry key, an event stream; or
  • 0 on success, when it performs an action with no handle to hand back; and
  • -1 on failure, with the reason in errno.
int fd = peios_token_open_self(/* … */);
if (fd < 0) {
    /* errno is set — perror(), strerror(errno), etc. */
}

1.2.2 ssize_t — a byte length #

A function returning ssize_t produces a variable-length result — a SID, a serialized security descriptor, a formatted string, a registry value. It returns:

  • the length in bytes of the result on success (>= 0); or
  • -1 on failure, with the reason in errno.

These are the functions that use the two-call buffer protocol below. The returned length is always the full length of the result, which is what makes the protocol work.

For functions that format a string, the returned length excludes the terminating NUL — exactly like snprintf. So a return of 41 means "41 characters plus a NUL"; size your buffer as len + 1.

1.2.3 Structured results — out-parameters #

When a call produces more than one value, or a value that isn't naturally a length or an fd, it writes through out-parameters and returns int (0 / -1). The access check is the archetype: it returns 0 when access is granted and -1 with errno == EACCES when it is denied, and it writes the granted access mask through an out-parameter either way.

uint32_t granted = 0;
int rc = peios_access_check(/* … */, &granted);
/* rc == 0: granted; rc == -1 && errno == EACCES: denied.
   `granted` is populated in both cases. */

A denial is a normal, expected outcome, not a bug — which is why it is reported the same disciplined way as any other errno, rather than through a separate channel.

1.2.4 errno #

Failure is always reported through the standard C errno. The library sets errno on every -1 return and uses ordinary, portable errno values — there are no libpeios-specific or PKM-specific error numbers to learn. The ones you will see most:

errnoMeaning in libpeios
EINVALMalformed input — a bad SID, an unparseable SDDL string, an argument out of range.
ERANGEYour output buffer was non-zero but too small. Nothing was written. (See the protocol below.)
EACCESAn access check denied the request.
ENOMEMAn allocation failed (for the heap-backed builders).
EBADF, ESRCH, EFAULTThe usual Linux meanings — a bad fd or pidfd, a vanished process, a bad pointer.

Because the values are standard, strerror, perror, and your language's normal errno handling all work unchanged. Check the return value first, then read errno — like any POSIX call, errno is only meaningful after a call that signaled failure.

Nothing ever unwinds across the boundary. The library is compiled to abort rather than propagate a panic through the C ABI, so a call either returns a value you can inspect or the process dies — it never leaves you with a corrupt half-state to reason about.

1.3 The Two-call Buffer Protocol

Peios / Developing for Peios / SDK Reference / Library Conventions

Every function that returns variable-length bytes — anything with an ssize_t return and an (out, cap) pair — follows the same getxattr-style protocol. It is the single most important convention in the library, so it is worth internalising.

The rule:

  • Call with cap == 0 (or a NULL buffer) to probe: the function writes nothing and returns the number of bytes the result needs.
  • Call with a buffer of at least that size to retrieve: the function fills the buffer and returns the number of bytes it wrote.
  • Call with a non-zero but too-small buffer and it fails with ERANGE and writes nothing — never a truncated or partial result.

That last point is the safety property that makes the protocol trustworthy: a too-small buffer is a clean, detectable error, not a silent truncation. You never have to wonder whether you got the whole thing.

The canonical two-call sequence:

/* 1. Probe for the size. */
ssize_t need = peios_sid_format(sid, sid_len, NULL, 0);
if (need < 0) { /* errno set */ }

/* 2. Allocate. For a string, add 1 for the NUL. */
char *buf = malloc(need + 1);

/* 3. Retrieve. */
ssize_t n = peios_sid_format(sid, sid_len, buf, need + 1);
if (n < 0) { /* errno set */ }
/* buf now holds the formatted SID; n is its length (excluding the NUL). */

When you already know a comfortable upper bound, you can skip the probe and call once with a big-enough buffer. Some results have a fixed maximum the library gives you a constant for — for example a SID is never larger than PEIOS_SID_MAX_BYTES, so a stack buffer of that size always fits and never needs a probe. Those shortcuts are called out where they apply; the two-call protocol is always available as the general fallback.

1.4 Memory Ownership

Peios / Developing for Peios / SDK Reference / Library Conventions

libpeios never hands you an allocation to free(). Instead it uses two ownership patterns — builders for constructing byte buffers and views for reading them — and both keep the memory question simple: you own your buffers, the library borrows or copies, and the two never get confused.

1.4.1 Builders — constructing buffers #

Anything you assemble (an ACL, a security descriptor, a token specification) is built with a builder: an opaque, heap-backed object you create, feed, take the bytes from, and free.

Builders have three properties worth knowing up front:

  1. They are sticky-error. The incremental add/set calls return void — they never fail inline. If one hits a problem (a bad input, an allocation failure), the builder latches the error and every later call is a no-op. You do not have to check each step. Instead you check once, at the end: either call the builder's _error() accessor (it returns the latched errno, or 0 if all is well), or notice that taking the bytes fails. This lets you write a long, clean sequence of add calls without a conditional after every line.

  2. You free every builder you create. Each _new() is paired with a _free(). Builders also have a _reset() that drops the accumulated content and clears the sticky error, so you can reuse one builder across several objects instead of churning allocations.

  3. Taking the bytes: borrow (and sometimes copy). Every builder has a _bytes() that hands back a pointer into the builder — zero-copy, no allocation. That pointer is valid only until the next mutating call, _reset(), or _free() on that builder. Use it when you are going to consume the bytes immediately (for instance, pass them straight into a kernel call). The call comes in two shapes, and not every builder offers a copying counterpart:

    • The security builders (peios_acl_builder_bytes, peios_sd_builder_bytes) return the pointer — NULL if the sticky error is set — and write the length through an optional len_out pointer. Each is paired with a _finish() that copies the buffer into a caller-supplied buffer using the two-call protocol above, for when the bytes must outlive the builder.
    • peios_token_builder_bytes and peios_mp_writer_bytes are shaped the other way round: they return the length as an ssize_t (-1 with errno on a latched error) and write the borrowed pointer through an out-parameter (which can be NULL to get the length). Neither has a _finish() — copy the borrowed bytes yourself if they need to outlive the builder.

A typical builder lifecycle:

peios_acl_builder *b = peios_acl_builder_new();   /* NULL on OOM */
peios_acl_builder_allow(b, sid, sid_len, mask, 0); /* void — no check */
peios_acl_builder_deny(b, other, other_len, mask, 0);

size_t len;
const void *acl = peios_acl_builder_bytes(b, &len); /* NULL if errored */
if (!acl) { int err = peios_acl_builder_error(b); /* handle */ }
/* … use `acl` before the next mutation … */

peios_acl_builder_free(b);

1.4.2 Views — reading buffers #

Anything you parse (a security descriptor, an ACL, a SID array from a token) is read through a view: a small, caller-allocated struct that you point at a buffer you already hold.

Views have their own two rules:

  1. You allocate the view; it is stack-friendly. A view type such as peios_sd_view is an opaque fixed-size struct — you declare one as a local variable and pass its address to the parse call. No heap, no free. The struct's fields are opaque: never read them directly; use the accessor functions.

  2. A view borrows the buffer it parses — zero-copy. The parse call does not copy the data; the view points into your buffer, and every accessor that yields a SID, a nested ACL, or a blob hands back a pointer into that same buffer. So the buffer must stay alive and unmodified for as long as the view — and anything you derived from it — is in use. Free or mutate the underlying buffer and every pointer the view gave you dangles.

peios_sd_view sd;                        /* on the stack */
if (peios_sd_parse(buf, buf_len, &sd) != 0) { /* EINVAL */ }

const void *owner; size_t owner_len;
if (peios_sd_view_owner(&sd, &owner, &owner_len) == 0) {
    /* `owner` points INTO `buf` — valid only while `buf` lives. */
}

Views compose: parsing a security descriptor gives you a peios_sd_view, from which you obtain a peios_acl_view for its DACL, from which you obtain each peios_ace_view. Every one of them borrows the same original buffer, so keeping that one buffer alive keeps the whole tree valid.

The symmetry is the thing to remember: builders own heap and must be freed; views own nothing and borrow your buffer. Constructing is builders, reading is views, and neither ever asks you to free something the library allocated.

1.5 File Descriptors

Peios / Developing for Peios / SDK Reference / Library Conventions

Handles that libpeios opens — tokens, registry keys, event streams — are raw int file descriptors, the same kind open() gives you. You close them with close(), poll them, and pass them across exec (or not) with the usual fd machinery.

They are created O_CLOEXEC by default: a handle does not leak across an exec unless you deliberately clear the flag with fcntl. This is the safe default for security-sensitive handles — a token or key fd will not silently end up in a child process you launch.

1.6 Constants

Peios / Developing for Peios / SDK Reference / Library Conventions

libpeios does not invent its own names for the kernel's wire constants. The access-right bits, ACE types, control flags, and mapping structs all come straight from the <pkm/*.h> UAPI headers, and you use those published names directly: KACS_ACCESS_*, KACS_ACE_TYPE_*, KACS_SD_*, struct kacs_generic_mapping, and so on. There is no parallel PEIOS_* aliasing to translate in your head — the name in the PSD, the name in the kernel header, and the name you write in your code are the same name.

The handful of constants that are libpeios's own — buffer-size ceilings like PEIOS_SID_MAX_BYTES, and enums for convenience selectors like enum peios_wks (well-known SIDs) — are prefixed PEIOS_ and documented with the module that defines them.

1.7 The Conventions at a Glance

Peios / Developing for Peios / SDK Reference / Library Conventions

ConventionThe rule
int returnfd or 0 on success; -1 + errno on failure.
ssize_t returnbyte length on success; -1 + errno on failure. Strings exclude the NUL.
Two-call protocolcap == 0 / NULL probes for the size; too-small non-zero buffer → ERANGE, nothing written.
errnostandard values only; check the return first, then errno.
Access denial-1 + EACCES, with the granted mask still written to the out-param.
Buildersheap-backed, sticky-error, void adders; check _error() at the end; _free() every one; _bytes() borrows, and the security builders add a _finish() that copies.
Viewscaller-allocated (stack), opaque, borrow the parsed buffer; keep that buffer alive and unmodified.
File descriptorsraw int, O_CLOEXEC by default, closed with close().
Constantsuse the <pkm/*.h> KACS_* names directly; only libpeios's own additions are PEIOS_*.

With these in hand, the module documentation reads as "what does this function do?" — the how of memory and errors is answered here, once, for all of them. Next: your first program, which puts the protocol and the error model to work in something you can compile.

2.1 Security Descriptors

Peios / Developing for Peios / SDK Reference / security.h — SIDs and Descriptors

<peios/security.h> is the shared vocabulary of the whole access-control surface. SIDs, security descriptors, ACLs, and ACEs are the currency every KACS interface trades in — tokens carry them, files are protected by them, access checks evaluate them, and the registry secures keys with them. They cross the kernel boundary as variable-length, self-relative byte buffers in the MS-DTYP wire formats, and this module is the one place libpeios lifts that raw wire form into something safe to handle from C.

Everything here assumes the library conventions: ssize_t returns are byte lengths using the two-call protocol, builders are heap-backed and sticky-error, and views borrow the buffer they parse. This page does not repeat those rules per function — read that page first.

The module has four parts:

  • SIDs — build, parse, format, and compare security identifiers.
  • ACLs and security descriptors — assemble them with builders.
  • Parsing — read them back with zero-copy views.
  • SDDL and inheritance — the text form and the userspace-only inheritance helpers.

The wire constants (KACS_SID_*, KACS_SD_*, KACS_ACE_*, and struct kacs_generic_mapping) come straight from <pkm/sid.h> and <pkm/sd.h>. libpeios does not re-alias them — you use the published ABI names directly.

2.1.1 See also #

  • Library conventions — the error, buffer, builder, and view rules this page builds on.
  • SIDs and Security descriptors — the operator-side concepts behind this vocabulary.
  • <peios/token.h>, <peios/file.h>, <peios/access.h> — the KACS interfaces that consume this vocabulary, including the generic-mapping tables peios_access_map_generic expects.

2.2 SIDs

Peios / Developing for Peios / SDK Reference / security.h — SIDs and Descriptors

A SID (Security Identifier) is the unique binary name of a principal. For the full account of what a SID is — its string and binary forms, the mixed endianness, the equality rule — see the operator-side page on SIDs. This section is the API for handling them.

A SID is small and bounded. The largest possible encoding is PEIOS_SID_MAX_BYTES (68) bytes, so a buffer of that size holds any valid SID and the SID builders never need a two-call probe — you can always pass a PEIOS_SID_MAX_BYTES stack buffer and skip straight to the retrieve call.

#define PEIOS_SID_MAX_BYTES 68u

2.2.1 Constructing SIDs #

Each of these encodes a SID into your buffer and returns its length (or -1 with errno). Because a SID fits in PEIOS_SID_MAX_BYTES, the probe is optional — but these are still ssize_t/two-call functions, so passing cap == 0 to probe works too.

FunctionBuilds
peios_sid_build(out, cap, id_authority, sub_auths, count)An arbitrary SID from its parts: a 48-bit identifier authority (numeric, encoded big-endian) and count sub-authorities (encoded little-endian). count is 0..KACS_SID_MAX_SUB_AUTHORITIES.
peios_sid_parse_string(out, cap, sddl)A binary SID from its SDDL string form ("S-1-5-21-…").
peios_sid_integrity(out, cap, level_rid)An integrity-label SID S-1-16-<rid> (see peios_integrity_level).
peios_sid_logon(out, cap, session_id)A logon SID S-1-5-5-<hi>-<lo> from a 64-bit session id.
peios_sid_well_known(out, cap, which)A well-known SID selected by enum peios_wks.
ssize_t peios_sid_build(void *out, size_t cap, uint64_t id_authority,
                        const uint32_t *sub_auths, unsigned count);
ssize_t peios_sid_parse_string(void *out, size_t cap, const char *sddl);
ssize_t peios_sid_integrity(void *out, size_t cap, uint32_t level_rid);
ssize_t peios_sid_logon(void *out, size_t cap, uint64_t session_id);
ssize_t peios_sid_well_known(void *out, size_t cap, enum peios_wks which);

peios_sid_build fails with EINVAL if count exceeds the maximum, and (like all of these) with ERANGE if a non-zero cap is too small.

2.2.2 Formatting and inspecting SIDs #

FunctionReturns
peios_sid_format(sid, len, out, cap)The SDDL string form ("S-1-…"), as a string length excluding the NUL — allocate len + 1.
peios_sid_valid(sid, len)true if sid is a structurally valid SID of exactly len bytes.
peios_sid_length(sid)The encoded length of sid, read from its sub-authority count. You must have already validated sid, or bounded it to PEIOS_SID_MAX_BYTES — this trusts the buffer.
peios_sid_equal(a, alen, b, blen)true for exact binary equality — the only equality KACS defines for SIDs.
peios_sid_rid(sid, len)The RID (last sub-authority), or 0 if the SID has none.
ssize_t  peios_sid_format(const void *sid, size_t len, char *out, size_t cap);
bool     peios_sid_valid(const void *sid, size_t len);
size_t   peios_sid_length(const void *sid);
bool     peios_sid_equal(const void *a, size_t alen, const void *b, size_t blen);
uint32_t peios_sid_rid(const void *sid, size_t len);

The split between peios_sid_valid and peios_sid_length is deliberate: validation is the safe check that bounds an untrusted buffer; peios_sid_length is the fast reader you use after you trust the bytes (or when you have already capped the buffer at PEIOS_SID_MAX_BYTES). When in doubt, validate first.

2.2.3 Well-known SIDs #

peios_sid_well_known constructs any of the standard system principals without you memorising their numbers:

enum peios_wks {
    PEIOS_WKS_NULL,                 /* S-1-0-0    Nobody */
    PEIOS_WKS_EVERYONE,             /* S-1-1-0    World */
    PEIOS_WKS_LOCAL,                /* S-1-2-0    Local */
    PEIOS_WKS_CREATOR_OWNER,        /* S-1-3-0 */
    PEIOS_WKS_CREATOR_GROUP,        /* S-1-3-1 */
    PEIOS_WKS_OWNER_RIGHTS,         /* S-1-3-4    suppresses owner WRITE_DAC */
    PEIOS_WKS_ANONYMOUS,            /* S-1-5-7 */
    PEIOS_WKS_SELF,                 /* S-1-5-10   PRINCIPAL_SELF */
    PEIOS_WKS_AUTHENTICATED_USERS,  /* S-1-5-11 */
    PEIOS_WKS_SYSTEM,               /* S-1-5-18   Local System */
    PEIOS_WKS_LOCAL_SERVICE,        /* S-1-5-19 */
    PEIOS_WKS_NETWORK_SERVICE,      /* S-1-5-20 */
    PEIOS_WKS_ADMINISTRATORS,       /* S-1-5-32-544 */
};

For the meaning of each principal, see Well-known principals.

2.2.4 Integrity levels #

Integrity-label SIDs have the form S-1-16-<rid>, where the RID names a level. peios_sid_integrity takes that RID; the standard levels are:

enum peios_integrity_level {
    PEIOS_IL_UNTRUSTED = 0,
    PEIOS_IL_LOW       = 4096,
    PEIOS_IL_MEDIUM    = 8192,
    PEIOS_IL_HIGH      = 12288,
    PEIOS_IL_SYSTEM    = 16384,
};

These are the labels that appear in a SACL as a SYSTEM_MANDATORY_LABEL ACE (see peios_acl_builder_label).

2.3 Access Masks

Peios / Developing for Peios / SDK Reference / security.h — SIDs and Descriptors

An access mask is a 32-bit set of rights. Masks can contain four generic bits (KACS_ACCESS_GENERIC_READ/WRITE/EXECUTE/ALL) that stand in for object-specific rights until they are mapped to a concrete object class.

uint32_t peios_access_map_generic(uint32_t mask,
                                  const struct kacs_generic_mapping *m);

peios_access_map_generic folds the generic bits of mask into object-specific rights using the mapping m, and clears the generic bits from the result. Each object class publishes its canonical mapping as a data symbol you pass here — peios_file_generic_mapping (from <peios/file.h>) and peios_token_generic_mapping (from <peios/token.h>). Use it when you have a mask written in generic terms (say, from an SDDL string using GR/GW) and need the concrete rights for a specific object type.

2.4 Building ACLs

Peios / Developing for Peios / SDK Reference / security.h — SIDs and Descriptors

An ACL is an ordered list of ACEs. You assemble one with a peios_acl_builder — create it, add ACEs, take the serialized bytes, free it. Builders follow the sticky-error rules: the adders return void, the first error latches, and you check peios_acl_builder_error at the end.

typedef struct peios_acl_builder peios_acl_builder;

peios_acl_builder *peios_acl_builder_new(void);   /* NULL on OOM */
void               peios_acl_builder_free(peios_acl_builder *b);
void               peios_acl_builder_reset(peios_acl_builder *b);

peios_acl_builder_reset drops every accumulated ACE and clears the sticky error, so you can reuse one builder for several ACLs.

2.4.1 Adding ACEs #

The common single-SID families have convenience adders. flags is a mask of KACS_ACE_FLAG_* and is usually 0 — the flags carry inheritance semantics, which matter only for container/inheritable ACEs.

void peios_acl_builder_allow(peios_acl_builder *b, const void *sid, size_t len,
                             uint32_t mask, uint8_t flags);
void peios_acl_builder_deny (peios_acl_builder *b, const void *sid, size_t len,
                             uint32_t mask, uint8_t flags);
void peios_acl_builder_audit(peios_acl_builder *b, const void *sid, size_t len,
                             uint32_t mask, uint8_t flags);
AdderAppends
_allowAn ACCESS_ALLOWED ACE — grants mask to sid.
_denyAn ACCESS_DENIED ACE — denies mask to sid. Order matters: put denies before allows.
_auditA SYSTEM_AUDIT ACE — logs access by sid matching mask. Belongs in a SACL, not a DACL.

For an integrity label there is a dedicated adder:

void peios_acl_builder_label(peios_acl_builder *b, uint32_t integrity_rid,
                             uint32_t policy_mask);

It appends a SYSTEM_MANDATORY_LABEL ACE for integrity level S-1-16-<integrity_rid>. policy_mask is a mask of the KACS_SYSTEM_MANDATORY_LABEL_NO_{READ,WRITE,EXECUTE}_UP bits (from <pkm/sd.h>) that says which accesses a lower-integrity caller is denied. Like _audit, a label ACE belongs in a SACL.

For everything else — object ACEs, callback ACEs, resource-attribute ACEs — there is the general adder and a fully-specified ACE struct:

struct peios_ace_spec {
    uint8_t       type;      /* KACS_ACE_TYPE_* */
    uint8_t       flags;     /* KACS_ACE_FLAG_* */
    uint32_t      mask;
    const void   *sid;       /* trustee */
    size_t        sid_len;
    const uint8_t *object_type;            /* 16-byte GUID, or NULL */
    const uint8_t *inherited_object_type;  /* 16-byte GUID, or NULL */
    const void   *app_data;  /* trailing callback/resource data */
    size_t        app_data_len;
};

void peios_acl_builder_add(peios_acl_builder *b, const struct peios_ace_spec *ace);

Fill in only the fields the type uses; leave the rest NULL/0:

  • Object ACEs (KACS_ACE_TYPE_*_OBJECT) read object_type and inherited_object_type — each a 16-byte GUID, or NULL when absent.
  • Callback and resource-attribute ACEs carry trailing app_data (which is NULL only when app_data_len is 0). For callback ACEs this is the conditional-expression bytecode you can produce with peios_sddl_parse_condition.

The convenience adders are exactly peios_acl_builder_add with a pre-filled spec for the common cases; reach for _add when you need object, callback, or resource-attribute ACEs.

The SDDL encoder includes zero padding after a variable-length payload so the total AceSize is a multiple of four, as required by PCDS. This includes resource claims ending in an odd-length octet or string payload. The padding is included in AceSize; it does not change lengths or offsets within the claim itself. The raw C ACL builder requires the supplied ACE body to already be four-byte aligned; it rejects an unaligned body with EINVAL.

2.4.2 Taking the ACL bytes #

const void *peios_acl_builder_bytes(peios_acl_builder *b, size_t *len_out);
ssize_t     peios_acl_builder_finish(peios_acl_builder *b, void *buf, size_t cap);
int         peios_acl_builder_error(const peios_acl_builder *b);
  • peios_acl_builder_bytes borrows: it returns a pointer into the builder (valid until the next mutation, _reset, or _free), writing the length to len_out if non-NULL. It returns NULL if the sticky error is set.
  • peios_acl_builder_finish copies the serialized ACL out using the two-call protocol.
  • peios_acl_builder_error returns the latched errno, or 0 if the builder is healthy.

The usual next step is to hand these bytes to peios_sd_builder_dacl or _sacl.

2.5 Building Security Descriptors

Peios / Developing for Peios / SDK Reference / security.h — SIDs and Descriptors

A security descriptor binds an owner, a group, a DACL, a SACL, and control flags into one self-relative buffer. Its builder mirrors the ACL builder's shape.

typedef struct peios_sd_builder peios_sd_builder;

peios_sd_builder *peios_sd_builder_new(void);
void              peios_sd_builder_free(peios_sd_builder *b);
void              peios_sd_builder_reset(peios_sd_builder *b);

2.5.1 Setting components #

void peios_sd_builder_owner(peios_sd_builder *b, const void *sid, size_t len);
void peios_sd_builder_group(peios_sd_builder *b, const void *sid, size_t len);
void peios_sd_builder_control(peios_sd_builder *b, uint16_t set, uint16_t clear);
void peios_sd_builder_dacl(peios_sd_builder *b, const void *acl, size_t len);
void peios_sd_builder_dacl_null(peios_sd_builder *b);
void peios_sd_builder_sacl(peios_sd_builder *b, const void *acl, size_t len);
  • Owner / group. Omit the call to leave the component absent. That is exactly what you want when building a partial SD to set only some components through kacs_set_sd — the SD then carries only what you set.
  • Control bits. peios_sd_builder_control sets the bits in set and clears those in clear (KACS_SD_DACL_PROTECTED, and friends). You do not manage SELF_RELATIVE or the *_PRESENT bits — the builder maintains those for you as you add components.
  • DACL / SACL. Pass ACL bytes, typically straight from peios_acl_builder_bytes. An ACL with zero ACEs is a present-but-empty DACL, which grants only the owner's implicit rights.

The DACL has one subtlety worth stating plainly. KACS has no NULL-DACL encoding — there is no "DACL present, pointer null" form; the kernel's parser rejects it. So "grant everyone everything" is expressed as an absent DACL (the DACL_PRESENT control bit clear). peios_sd_builder_dacl_null requests exactly that: it clears any DACL you set earlier and produces the same bytes as never setting a DACL at all. It exists so you can state the grant-all intent explicitly rather than by omission — but be clear that it means grant all, not deny all.

2.5.2 Taking the SD bytes #

Identical in shape to the ACL builder:

const void *peios_sd_builder_bytes(peios_sd_builder *b, size_t *len_out);
ssize_t     peios_sd_builder_finish(peios_sd_builder *b, void *buf, size_t cap);
int         peios_sd_builder_error(const peios_sd_builder *b);

_bytes borrows (valid until the next mutation/reset/free, NULL if errored), _finish copies out getxattr-style, _error returns the latched errno.

2.6 Parsing — Views

Peios / Developing for Peios / SDK Reference / security.h — SIDs and Descriptors

To read a security descriptor, ACL, or ACE you use zero-copy views. A view is a caller-allocated, opaque, stack-friendly struct that borrows the buffer you parse — see the view rules. Every accessor that yields a SID, a nested ACL, or a blob returns a pointer into the original buffer, so that buffer must outlive the view and everything derived from it.

typedef struct peios_sd_view        { uint64_t _opaque[8]; } peios_sd_view;
typedef struct peios_acl_view       { uint64_t _opaque[4]; } peios_acl_view;
typedef struct peios_ace_view       { uint64_t _opaque[4]; } peios_ace_view;
typedef struct peios_sid_array_view { uint64_t _opaque[4]; } peios_sid_array_view;

The _opaque arrays are sized for stack allocation with headroom — declare a view as a local and never read its fields.

2.6.1 Security-descriptor views #

int      peios_sd_parse(const void *sd, size_t len, peios_sd_view *out);
uint16_t peios_sd_view_control(const peios_sd_view *v);
int      peios_sd_view_owner(const peios_sd_view *v, const void **sid, size_t *len);
int      peios_sd_view_group(const peios_sd_view *v, const void **sid, size_t *len);
int      peios_sd_view_dacl(const peios_sd_view *v, peios_acl_view *out);
int      peios_sd_view_sacl(const peios_sd_view *v, peios_acl_view *out);

peios_sd_parse validates a self-relative SD and populates out, returning 0 or -1 (EINVAL). peios_sd_view_control returns the raw control-bit word.

The four component accessors return 0 with their out-params set on success, or -1 if the component is absent. For the DACL and SACL, -1 also covers the NULL-DACL case — since an absent DACL and a NULL DACL are the same thing in KACS, a -1 from peios_sd_view_dacl uniformly means "no DACL constrains this object."

2.6.2 ACL and ACE views #

You can also parse a bare ACL directly — a token's default DACL, for instance, arrives as an ACL, not wrapped in an SD:

int      peios_acl_parse(const void *acl, size_t len, peios_acl_view *out);
unsigned peios_acl_view_count(const peios_acl_view *a);
int      peios_acl_view_ace(const peios_acl_view *a, unsigned i, peios_ace_view *out);

peios_acl_view_count gives the number of ACEs; peios_acl_view_ace populates out for ACE i (0-based, in stored order), returning 0 or -1 (ERANGE for an out-of-range index). Iterate in the obvious way:

unsigned n = peios_acl_view_count(&dacl);
for (unsigned i = 0; i < n; i++) {
    peios_ace_view ace;
    peios_acl_view_ace(&dacl, i, &ace);
    /* inspect ace … */
}

Each ACE is read through its own accessors:

uint8_t  peios_ace_view_type(const peios_ace_view *e);
uint8_t  peios_ace_view_flags(const peios_ace_view *e);
uint32_t peios_ace_view_mask(const peios_ace_view *e);
int      peios_ace_view_sid(const peios_ace_view *e, const void **sid, size_t *len);
int      peios_ace_view_object_type(const peios_ace_view *e, const uint8_t **guid16);
int      peios_ace_view_inherited_object_type(const peios_ace_view *e,
                                              const uint8_t **guid16);
int      peios_ace_view_app_data(const peios_ace_view *e, const void **data,
                                 size_t *len);
AccessorYields
_type / _flags / _maskThe ACE's KACS_ACE_TYPE_* type, KACS_ACE_FLAG_* flags, and 32-bit access mask.
_sidThe trustee SID (a pointer into the buffer). 0 / -1.
_object_typeThe object GUID of an object ACE — 0 with *guid16 set to the 16 bytes, or -1 if not present / not an object ACE.
_inherited_object_typeThe inherited-object GUID, same convention.
_app_dataTrailing application data of a callback or resource-attribute ACE — for a callback ACE, this is the conditional-expression bytecode you can render with peios_sddl_format_condition.

2.6.3 SID-and-attributes arrays #

Several token classes — GROUPS, RESTRICTED_SIDS, DEVICE_GROUPS, CAPABILITIES — return a packed [count][sid_len][sid][attrs]… blob rather than an ACL. Parse those with the SID-array view:

int      peios_sid_array_parse(const void *blob, size_t len, peios_sid_array_view *out);
unsigned peios_sid_array_count(const peios_sid_array_view *a);
int      peios_sid_array_get(const peios_sid_array_view *a, unsigned i,
                             const void **sid, size_t *len, uint32_t *attrs);

peios_sid_array_get yields the i-th entry's SID (a pointer into the blob), its length, and its 32-bit attribute word (the KACS_SE_GROUP_* flags — enabled, mandatory, deny-only, and so on).

2.7 SDDL Text Codec

Peios / Developing for Peios / SDK Reference / security.h — SIDs and Descriptors

The SDDL codec converts between the binary wire forms and their human-readable SDDL text (MS-DTYP §2.5.1). This is a pure-userspace facility — the kernel speaks only binary — so it lives entirely in libpeios. All four entries use the two-call protocol (cap == 0 to probe) and fail with EINVAL on malformed input.

ssize_t peios_sddl_parse_sd(void *out, size_t cap, const char *sddl);
ssize_t peios_sddl_format_sd(char *out, size_t cap, const void *sd, size_t sd_len);
  • peios_sddl_parse_sd parses SDDL text (for example "O:SYG:BAD:(A;;FA;;;BA)") into self-relative SD wire bytes.
  • peios_sddl_format_sd renders SD wire bytes back to a NUL-terminated SDDL string (length excludes the NUL, so allocate len + 1).

These are the friendliest way to construct a descriptor when you have one written down — parse the string rather than assembling ACEs by hand — and the friendliest way to log or display one.

2.7.1 Conditional expressions #

Callback ACEs carry a conditional expression as compiled "artx" bytecode. The codec converts between that bytecode and its SDDL expression text:

ssize_t peios_sddl_parse_condition(void *out, size_t cap, const char *expr);
ssize_t peios_sddl_format_condition(char *out, size_t cap, const void *artx, size_t len);
  • peios_sddl_parse_condition compiles an expression such as @User.Title == "PM" into the bytecode you place in a callback ACE's app_data.
  • peios_sddl_format_condition renders bytecode back to text (with no outer parentheses), length excluding the NUL.

So the round trip for a conditional ACE is: write the condition as text → peios_sddl_parse_condition → put the bytecode in peios_ace_spec.app_data with a callback ACE type → add it to an ACL builder.

2.7.2 Input limits and malformed data #

Conditional expressions have a maximum tree depth of 128. Each comparison, existence check, membership test, logical operator, or composite operand adds one level; scalar operands add none. For example, a comparison has depth one, and adding 127 negations reaches the limit. Long && and || chains also count because each operator adds a level to the resulting tree.

Text parsing also limits nested parentheses, negations, and composite braces to 128 levels along any one parsing path. Delimiters inside string literals do not count. These limits apply when parsing conditional ACEs inside a descriptor as well as when converting a standalone condition. The bytecode decoder applies the same tree limit, including nested composite operands.

Inputs beyond either limit fail with EINVAL; simplify the expression before retrying. The C functions return -1 and leave the output buffer untouched.

GUID fields require ASCII hexadecimal digits in the standard hyphenated form. Malformed Unicode GUID text fails with EINVAL. When reading resource claims, the codec checks that the complete value-offset table fits inside the supplied bytes before allocating storage for its entries. An impossible or truncated table also fails with EINVAL.

2.7.3 Descriptor text and omitted components #

Sections use O:<sid>G:<sid>D:<acl>S:<acl>. Each is optional but can appear only once. Formatting orders them as owner, group, DACL, and SACL.

D: is an empty, present DACL. D:NO_ACCESS_CONTROL and an omitted DACL encode the absent-DACL state. The marker can accompany ACL flags but not ACEs. The same representation rule applies to SACL absence. The formatter can omit an absent ACL unless flags need preserving, and uses D:NO_ACCESS_CONTROL for an otherwise empty descriptor.

These rules describe a complete supplied descriptor. In a tool that queried only selected components, an omitted section can instead mean "not queried." Formatting cannot recover missing components. Do not use matching partial SDDL strings as proof of complete descriptor equality or as a full backup.

An ACE has six semicolon-separated fields, or seven for a payload:

(type;flags;rights;object_guid;inherit_object_guid;account_sid;payload)

Object GUID fields apply to object ACEs; supplying them for other types is an error. Callback payloads carry conditions, and resource-attribute payloads carry claims. For example, O:SYG:SYD:(A;OICI;GA;;;SY) names SYSTEM as owner and group and grants SYSTEM generic-all with object/container inheritance. This explains the string; it does not select a suitable policy for every object.

2.7.4 ACL control flags #

FlagMeaning
PProtected. The ACL does not inherit from its parent.
AIAuto-inherited. The ACL was produced by inheritance propagation.
ARAuto-inherit required. Requests that propagation be applied.

2.7.5 ACE type codes #

CodeACE type
AAccess allowed
DAccess denied
AUSystem audit
OAAccess allowed, object
ODAccess denied, object
OUSystem audit, object
XAAccess allowed, callback — carries a condition
XDAccess denied, callback — carries a condition
XUSystem audit, callback — carries a condition
ZAAccess allowed, callback object
ZDAccess denied, callback object
ZUSystem audit, callback object
ALSystem alarm — continuous auditing
OLSystem alarm, object
XLSystem alarm, callback — carries a condition
ZLSystem alarm, callback object
MLMandatory label — the integrity level
TLProcess trust label
RAResource attribute — carries a claim
SPScoped policy identifier
FLAccess filter — carries a condition

2.7.6 ACE flag codes #

CodeMeaning
CIContainer inherit — child containers receive it.
OIObject inherit — child objects receive it.
NPNo propagate — children receive it, grandchildren do not.
IOInherit only — it does not apply to the object carrying it.
IDInherited — this ACE arrived by propagation.
SAAudit successful access.
FAAudit failed access.

2.7.7 Rights codes #

CodeRight
GAGeneric all
GRGeneric read
GWGeneric write
GXGeneric execute
CodeRight
SDDelete
RCRead control — read the descriptor
WDWrite DACL
WOWrite owner
CodeMaskRight
FA0x001F01FFAll file access
FR0x00120089File read
FW0x00120116File write
FX0x001200A0File execute
CodeMaskRight
KA0x000F003FAll key access
KR0x00020019Key read
KW0x00020006Key write
KX0x00020019Key execute
CodeRight
CCCreate child
DCDelete child
LCList children
SWSelf write
RPRead property
WPWrite property
DTDelete tree
LOList object
CRControl access
CodePolicy
NWNo write up
NRNo read up
NXNo execute up

2.7.8 Absolute SID aliases #

CodeSIDPrincipal
WDS-1-1-0Everyone
ANS-1-5-7Anonymous
IUS-1-5-4Interactive
NUS-1-5-2Network logon
SUS-1-5-6Service
RCS-1-5-12Restricted code
WRS-1-5-33Write-restricted code
PSS-1-5-10Principal self
EDS-1-5-9Enterprise domain controllers
AUS-1-5-11Authenticated Users
SYS-1-5-18Local System
LSS-1-5-19Local Service
NSS-1-5-20Network Service
ACS-1-15-2-1All application packages
CodeSIDPrincipal
COS-1-3-0Creator Owner
CGS-1-3-1Creator Group
OWS-1-3-4Owner rights
CodeSIDPrincipal
LWS-1-16-4096Low integrity
MES-1-16-8192Medium integrity
MPS-1-16-8448Medium-plus integrity
HIS-1-16-12288High integrity
SIS-1-16-16384System integrity
CodeSIDPrincipal
BAS-1-5-32-544Administrators
BUS-1-5-32-545Users
BGS-1-5-32-546Guests
PUS-1-5-32-547Power users
AOS-1-5-32-548Account operators
SOS-1-5-32-549Server operators
POS-1-5-32-550Printer operators
BOS-1-5-32-551Backup operators
RES-1-5-32-552Replicator
RUS-1-5-32-554Pre-Windows 2000 compatible access
RDS-1-5-32-555Remote desktop users
NOS-1-5-32-556Network configuration operators
MUS-1-5-32-558Performance monitor users
LUS-1-5-32-559Performance log users
ISS-1-5-32-568IIS users
CYS-1-5-32-569Cryptographic operators
ERS-1-5-32-573Event log readers
CDS-1-5-32-574Certificate service DCOM access
RAS-1-5-32-575RDS remote access servers
ESS-1-5-32-576RDS endpoint servers
MSS-1-5-32-577RDS management servers
HAS-1-5-32-578Hyper-V administrators
AAS-1-5-32-579Access control assistance operators
RMS-1-5-32-580Remote management users

2.7.9 Context-sensitive codes #

CodeAs a rightAs an accountElsewhere
WDWrite DACLEveryone
RCRead controlRestricted code
AUAuthenticated UsersACE type: system audit
RARDS remote access serversACE type: resource attribute
FAAll file accessACE flag: audit failed access
SDDelete

2.7.10 Numeric masks and canonical formatting #

An entirely ASCII-digit rights field is an unsigned decimal mask. Leading zeros remain decimal; signs, non-ASCII digits, overflow beyond 4294967295, and mixing decimal text with mnemonic codes are rejected. Hexadecimal uses 0x and consumes the rest of the field, so it can follow mnemonic rights only as the final portion. FRFX0x6 combines file read/execute with the two additional bits.

The formatter prefers composite masks and does not preserve every accepted spelling. KX has the same mask as KR; one spelling is emitted. Directory object codes share bits with other vocabularies, so outside mandatory-label ACEs formatting can use hexadecimal rather than guess an object class. Mandatory-label masks use their label vocabulary. Unknown ACE types fail formatting instead of silently disappearing.

XL and ZL are Peios callback-alarm extensions and are not portable Windows ACE codes. Domain-relative aliases such as DA and machine-relative LA cannot resolve without a base SID; the codec rejects them with an explanation. Use an explicit full SID. BUILTIN aliases are absolute despite their names. The null SID and protected-process integrity SID have no short alias.

A displayed f in the sd command's rights summary is that command's shorthand, not the SDDL grammar or a hexadecimal nibble. Consult the tool's manual before feeding rendered output back into a parser.

2.8 SD Inheritance

Peios / Developing for Peios / SDK Reference / security.h — SIDs and Descriptors

Inheritance — computing a child object's ACEs from its parent's inheritable ones — is also pure userspace (MS-DTYP §2.5.3.4). Both helpers take and produce self-relative SDs and use the two-call protocol.

ssize_t peios_sd_reinherit(void *out, size_t cap, const void *parent_sd,
                           size_t parent_len, const void *child_sd,
                           size_t child_len, int is_container);
ssize_t peios_sd_strip_inherited(void *out, size_t cap, const void *sd,
                                 size_t sd_len, uint32_t info);

peios_sd_reinherit recomputes a child SD's inherited ACEs from its parent. It strips the ACEs carrying ACE_FLAG_INHERITED from the child DACL, re-derives them from the parent DACL, and appends them after the child's explicit ACEs; the child's owner, group, SACL, and control bits pass through unchanged. is_container is non-zero if the child is itself a container (which determines how container-inherit and object-inherit flags propagate). This is what you call when a parent's ACL changed and you need to push the new inheritance down to a child.

peios_sd_strip_inherited drops the ACE_FLAG_INHERITED ACEs from the ACLs selected by info — a mask of *_SECURITY_INFORMATION bits, of which DACL_SECURITY_INFORMATION and SACL_SECURITY_INFORMATION are honored and the rest ignored (selecting neither copies the input verbatim). Owner, group, and control bits pass through. Use it to reduce a descriptor to its explicit ACEs — for example before storing a "protected" descriptor that should not carry inherited entries.

Both return the new SD's byte length, or -1 with EINVAL (malformed input) or ERANGE (a non-zero buffer too small).

3.1 Tokens and Sessions

Peios / Developing for Peios / SDK Reference / token.h — Tokens

<peios/token.h> is the token surface of KACS. A token is the runtime object that carries an identity — a user SID, group SIDs, privileges, an integrity level, claims — and every access decision is made against one. This module lets you open the tokens that already exist (your own, another process's, a socket peer's), mint new ones, read their contents, transform them, and install or impersonate them.

A token handle is a file descriptor. Every open/create/duplicate call returns a raw int fd, O_CLOEXEC by default, that you close with close(). The access argument several calls take is the desired handle-right mask (KACS_TOKEN_*), access-checked against the token's own security descriptor and cached on the fd — a handle only lets you do what its rights allow.

The wire constants (KACS_TOKEN_*, KACS_IMLEVEL_*, KACS_SE_*_PRIVILEGE, KACS_TOKEN_CLASS_*, KACS_LOGON_TYPE_*) and the ioctl arg structs (kacs_priv_entry, kacs_group_entry) come from <pkm/token.h>. Query payloads that are SID arrays or ACLs are read with the views in <peios/security.h>.

The module divides into: opening & creating, the token-spec builder, query, adjust/transform, and logon sessions.

3.1.1 See also #

  • <peios/security.h> — the SID/ACL/SD vocabulary and the views used to parse group and privilege query payloads.
  • <peios/access.h> — checking access with a token fd.
  • Tokens and Impersonation — the operator-side model.

3.2 Opening and Creating Tokens

Peios / Developing for Peios / SDK Reference / token.h — Tokens

Each of these returns a token fd (or -1 with errno).

int peios_token_open_self(unsigned flags, uint32_t access);
int peios_token_open_process(int pidfd, uint32_t access);
int peios_token_open_thread(int pidfd, int tid, uint32_t access);
int peios_token_open_peer(int conn_fd);
int peios_token_create_raw(const void *spec, size_t len);
FunctionOpens
peios_token_open_selfThe calling thread's token. flags can be KACS_TOKEN_OPEN_REAL to get the primary token even while the thread is impersonating; otherwise you get the effective (impersonation-aware) token. access is the desired handle rights.
peios_token_open_processThe primary token of the process named by pidfd. Subject to a process-query access check and PIP dominance over the target.
peios_token_open_threadThread tid's impersonation token if it is impersonating, else the process primary token.
peios_token_open_peerThe peer-identity token captured at connect() on a connected Unix stream/seqpacket socket conn_fd — how a server learns who is on the other end of a socket. Reads the KACS_SO_PEER_TOKEN socket option (level SOL_KACS, <pkm/socket.h>). The handle carries fixed `QUERY
peios_token_create_rawMints a token from a pre-built token-spec buffer. This is the escape hatch — prefer the builder below. Requires SeCreateTokenPrivilege.

Errors, per call:

  • peios_token_open_self — EINVAL (unknown flags; empty or unknown access bits), EACCES (the token's own SD denies access).
  • peios_token_open_process — EACCES (any of the three checks failed — process-query right, PIP dominance, or the token SD; deliberately indistinguishable), EBADF (invalid pidfd), ESRCH (target exited), EINVAL (empty or unknown access bits).
  • peios_token_open_thread — the _open_process set, plus ESRCH (thread exited, or not in pidfd's process) and EINVAL (tid <= 0).
  • peios_token_open_peer — ENOTCONN (not connected), ENODATA (connected but no captured identity — a socketpair end), EOPNOTSUPP (a datagram or non-Unix socket), ENOTSOCK (not a socket), EBADF (invalid fd).
  • peios_token_create_raw — EPERM (privilege missing), EINVAL (spec failed kernel validation), EFAULT (bad spec pointer), ENOMEM (allocation failed).

peios_token_open_peer is the cornerstone of local authentication: accept a connection, open the peer token, and you have the caller's identity to query or impersonate — no password, no handshake, the kernel's word for who connected.

3.2.1 Peer identity on sockets #

int peios_token_impersonate_peer(int conn_fd);
int peios_socket_set_impersonation_level(int sock_fd, uint32_t level);
int peios_socket_get_impersonation_level(int sock_fd, uint32_t *level);
int peios_socket_set_pass_token(int sock_fd, bool on);
int peios_socket_restamp(int sock_fd);
  • peios_token_impersonate_peer is peios_token_open_peer followed by peios_token_impersonate and a close — the one-call form for a handler that impersonates, works, and reverts on a single thread. It returns 0 or -1; the errno is whichever step failed.
  • peios_socket_set_impersonation_level is the client's side of the exchange: it sets the KACS_SO_IMPERSONATION_LEVEL socket option (KACS_IMLEVEL_*), bounding the level at which the peer can capture this socket's identity — Identification to be known but not acted as, Anonymous to withhold identity entirely. Usually set before connect(); it can change at any time and bounds every capture from then on. The default is KACS_IMLEVEL_IMPERSONATION. Errors: EINVAL (unknown level), EOPNOTSUPP (a non-Unix socket).
  • peios_socket_get_impersonation_level reads the level back into *level.
  • peios_socket_restamp replaces the identity a listening socket conveys to connecting clients — captured when listen() was called — with the caller's own (KACS_SO_RESTAMP; EINVAL if the socket is not listening). Capture is symmetric: a client's peios_token_open_peer on its own socket right after connect() returns the listener's identity at Identification level, which is how a client verifies the service it reached. A service that receives listeners it did not create (from the descriptor store after a restart, or from a broker) restamps them before accepting.
  • peios_socket_set_pass_token turns on per-message identity for a sending socket (KACS_SO_PASS_TOKEN): every send then carries the sender's effective identity as a KACS_SCM_TOKEN ancillary message, and the peer's peios_token_open_peer follows whoever was impersonating at each send. This is what makes a pooled or multiplexed connection convey the right identity per request without the client library knowing. To attach a specific token to one message instead — a router forwarding for many clients, or a submitter handing a job manager the identity a job should run as — use peios_socket_send_message below.

3.2.2 Per-message identity and descriptors #

A message on a Unix socket can carry two things beside its bytes: a token the kernel attests the sender could act as (KACS_SCM_TOKEN, level SOL_KACS) and a set of file descriptors (SCM_RIGHTS). Building the control buffer by hand and walking it back is the same twenty lines in every program that does it, and a wrong CMSG_ALIGN is silent; these calls do it once.

struct peios_socket_message {
    int      token_fd;   /* out: attached token (QUERY|IMPERSONATE|DUPLICATE, O_CLOEXEC), or -1 */
    int     *fds;        /* in:  SCM_RIGHTS descriptors land here, each O_CLOEXEC */
    unsigned fd_cap;     /* in:  capacity of fds */
    unsigned fd_count;   /* out: how many were filled */
    unsigned flags;      /* out: PEIOS_SOCKET_MSG_* */
};
#define PEIOS_SOCKET_MSG_TRUNCATED  0x1u   /* data did not fit (MSG_TRUNC) */
#define PEIOS_SOCKET_MSG_CTRUNCATED 0x2u   /* ancillary data did not fit (MSG_CTRUNC) */

ssize_t peios_socket_send_message(int sock_fd, const void *buf, size_t len,
                                  int token_fd, const int *fds, unsigned fd_count,
                                  int flags);
ssize_t peios_socket_recv_message(int sock_fd, void *buf, size_t cap,
                                  struct peios_socket_message *msg, int flags);
int     peios_socket_peer_pidfd(int sock_fd);
  • peios_socket_send_message sends len bytes from buf on sock_fd with one sendmsg(2), attaching token_fd as a KACS_SCM_TOKEN when it is >= 0 and fds[0..fd_count] as SCM_RIGHTS when fd_count > 0; flags are sendmsg flags. Returns the bytes sent. The kernel gates the token attach exactly as it gates impersonating it — the handle needs TOKEN_IMPERSONATE, and the token travels at the sending socket's impersonation level (peios_socket_set_impersonation_level, default Impersonation), which can only lower what the token already carries: if attaching would have to lower the token's level the send fails rather than downgrading. Ownership is unchanged by a send — the caller keeps token_fd and every entry of fds; the kernel duplicates them into the receiver on delivery.
  • peios_socket_recv_message receives one message with recvmsg(2) into buf/cap, with room for one attached token and msg->fd_cap descriptors written into the caller-owned msg->fds (pass NULL with fd_cap == 0 to accept none). MSG_CMSG_CLOEXEC is always added to flags, so every descriptor delivered is O_CLOEXEC. Returns the bytes received (0 at end of stream). On return the caller owns msg->token_fd (when >= 0) and msg->fds[0..fd_count] and closes each; the token handle carries QUERY | IMPERSONATE | DUPLICATE, the same fixed rights as peios_token_open_peer. Nothing leaks on any path: a second token in one message, or a descriptor past fd_cap, is closed by the library before it returns, and msg->flags reports the loss as PEIOS_SOCKET_MSG_CTRUNCATED; PEIOS_SOCKET_MSG_TRUNCATED means the bytes did not fit cap (on a SOCK_SEQPACKET socket the tail is gone). A receiver that cannot accept a truncated message closes what it was handed. On -1 nothing was consumed and *msg is untouched. fd_cap above the kernel's SCM_MAX_FD (253) is capped silently. The truncation flag also covers handles that fit in the syscall's ancillary buffer but exceed the caller's capacity. For example, fd_cap == 0 closes any received rights and reports control truncation. This flag is retained alongside payload truncation when both occur.
  • peios_socket_peer_pidfd returns a new pidfd (O_CLOEXEC) for the process on the other end of a connected Unix socket — getsockopt(SOL_SOCKET, SO_PEERPIDFD), a Linux ≥ 6.5 facility that libpeios only wraps; the option itself comes from the kernel UAPI and glibc. It is the kernel's handle on the peer, which is what peios_token_open_process takes to open the peer's primary token — the identity a process has, as distinct from the identity it conveyed at connect() (peios_token_open_peer) — and never a PID the peer named, so a recycled PID can never be opened by mistake.

Errors: peios_socket_send_message — EINVAL (NULL buffer with len > 0, NULL fds with fd_count > 0, or fd_count above SCM_MAX_FD), EACCES (token_fd lacks TOKEN_IMPERSONATE), EPERM (attaching would lower the token's level), EBADF (a descriptor in fds is not open), plus the sendmsg set (ENOTCONN, EPIPE, EMSGSIZE, EAGAIN). peios_socket_recv_message — EINVAL (NULL msg), plus the recvmsg set (ENOTCONN, EAGAIN, EBADF). peios_socket_peer_pidfd — ENODATA (no connected peer to name), ENOPROTOOPT (a kernel without SO_PEERPIDFD), ENOTSOCK, EBADF, EMFILE.

The client side of a job submission (PSPU §7) is the archetype — one record, one identity, two descriptors:

const char *request = "{\"command\":\"submit\",\"image_path\":\"/usr/bin/backup\","
                      "\"descriptors\":[\"control\"],\"output\":true}";
int fds[2] = { control_sock, STDOUT_FILENO };   /* named descriptors first, output sink last */

/* `job_token` is a token I hold with TOKEN_IMPERSONATE; the job runs as it. */
if (peios_socket_send_message(jobs_sock, request, strlen(request),
                              job_token, fds, 2, 0) < 0) { /* errno */ }
/* I still own job_token, control_sock and my stdout. */

and the manager's side, receiving it:

char buf[64 * 1024];
int fds[8];
struct peios_socket_message msg = { .fds = fds, .fd_cap = 8 };

ssize_t n = peios_socket_recv_message(conn, buf, sizeof buf, &msg, 0);
if (n < 0) { /* errno; nothing consumed */ }
if (n == 0) { /* end of stream */ }
if (msg.flags & (PEIOS_SOCKET_MSG_TRUNCATED | PEIOS_SOCKET_MSG_CTRUNCATED)) {
    /* not the message the sender meant: refuse it and close what arrived */
}
if (msg.token_fd >= 0) {
    /* the sender attested to this identity, at its socket's level */
    uint32_t level;
    peios_token_impersonation_level(msg.token_fd, &level);   /* for example refuse below Impersonation */
} else {
    /* no identity conveyed: fall back to the peer process's own primary token */
    int pidfd = peios_socket_peer_pidfd(conn);
    int primary = peios_token_open_process(pidfd, KACS_TOKEN_QUERY | KACS_TOKEN_DUPLICATE);
    close(pidfd);
}
/* msg.fds[0..msg.fd_count] and msg.token_fd are mine to use and close */

3.3 The Token-spec Builder

Peios / Developing for Peios / SDK Reference / token.h — Tokens

Minting a token means assembling a 192-byte-header wire format with many optional sections. The builder is the ergonomic path — typed setters, no hand-packed offsets — and follows the standard sticky-error builder rules: the setters return void, the first error latches, you check peios_token_builder_error at the end, and you _free every builder.

typedef struct peios_token_builder peios_token_builder;

peios_token_builder *peios_token_builder_new(void);
void                 peios_token_builder_free(peios_token_builder *b);
void                 peios_token_builder_reset(peios_token_builder *b);

3.3.1 The index convention #

Three fields — the owner, the primary group, and the restrict/deny indices — refer to SIDs by index into the token's own SID list rather than by value. The convention is fixed:

Index 0 is the user SID. Indices 1..N are the 1st..Nth group you added with peios_token_builder_add_group, in order.

So to make the second group the primary group, you set primary_group_index to 2. Do not add the logon SID yourself — the kernel injects it.

3.3.2 Core fields #

void peios_token_builder_user(peios_token_builder *b, const void *sid, size_t len);
void peios_token_builder_add_group(peios_token_builder *b, const void *sid,
                                   size_t len, uint32_t attrs);
void peios_token_builder_privileges(peios_token_builder *b, uint64_t present,
                                    uint64_t enabled);
void peios_token_builder_type(peios_token_builder *b, uint8_t type, uint8_t imp_level);
void peios_token_builder_integrity(peios_token_builder *b, uint32_t rid);
void peios_token_builder_session(peios_token_builder *b, uint64_t session_id);
void peios_token_builder_owner_index(peios_token_builder *b, uint32_t index);
void peios_token_builder_primary_group_index(peios_token_builder *b, uint32_t index);
void peios_token_builder_default_dacl(peios_token_builder *b, const void *acl, size_t len);
SetterSets
_userThe user SID (index 0).
_add_groupAppends a group SID with its KACS_SE_GROUP_* attribute word (enabled, mandatory, deny-only, …). Call once per group, in the order you want them indexed.
_privilegesThe privilege bitmasks: present (which privileges the token holds) and enabled (which are on). Bits are KACS_SE_*_PRIVILEGE.
_typeThe token type (KACS_TOKEN_TYPE_* — primary or impersonation) and the impersonation level imp_level (KACS_IMLEVEL_*). Choose the level deliberately: it caps every identity derived from the token, including a primary. CreateToken accepts all four levels; Identification permits peers to identify the process without acting as it, and Anonymous hides its identity from peers. The process still acts as its own user. Older kernels reject primary levels below Impersonation. DuplicateToken retains its separate Impersonation floor for primary results.
_integrityThe integrity level, as the RID of an S-1-16-<rid> label (see peios_integrity_level).
_sessionThe logon session id the token references.
_owner_index / _primary_group_indexWhich SID (by index) is the default owner / primary group.
_default_daclThe default DACL applied to new objects the token creates (ACL bytes, for example from a peios_acl_builder).

3.3.3 Advanced fields #

These cover the rest of the token-spec and can be left unset. They are marked [adv] in the header for a reason — most tokens need none of them.

void peios_token_builder_mandatory_policy(peios_token_builder *b, uint32_t bits);
void peios_token_builder_projected_ids(peios_token_builder *b, uint32_t uid, uint32_t gid);
void peios_token_builder_expiration(peios_token_builder *b, uint64_t when);
void peios_token_builder_source(peios_token_builder *b, const char name[8],
                                uint64_t source_id);
void peios_token_builder_audit_policy(peios_token_builder *b, uint32_t bits);
void peios_token_builder_add_restricted_sid(peios_token_builder *b, const void *sid,
                                            size_t len, uint32_t attrs);
void peios_token_builder_add_device_group(peios_token_builder *b, const void *sid,
                                          size_t len, uint32_t attrs);
void peios_token_builder_confinement(peios_token_builder *b, const void *sid, size_t len);
void peios_token_builder_supp_gids(peios_token_builder *b, const uint32_t *gids,
                                   unsigned count);
SetterSets
_mandatory_policyThe mandatory-integrity policy bits governing how the integrity label is enforced.
_projected_idsThe POSIX uid/gid this token projects into the Linux-compatibility layer.
_expirationAn absolute expiry time after which the token is not valid.
_sourceThe token's source: an 8-byte name and a source_id, recording who issued it (appears in audit).
_audit_policyPer-token audit policy bits.
_add_restricted_sidAppends a restricting SID (a write-restricted / restricted token intersects these against the normal SIDs).
_add_device_groupAppends a device group SID (the device/machine side of a claim-aware token).
_confinementThe confinement/AppContainer package SID that sandboxes the token.
_supp_gidsReplaces the projected supplementary GIDs (pass NULL, 0 to clear).

3.3.4 Token flags #

The four boolean token-spec flags are set together, so a designated initializer reads clearly:

struct peios_token_flags {
    bool write_restricted;
    bool user_deny_only;
    bool isolation_boundary;
    bool confinement_exempt;
};
void peios_token_builder_flags(peios_token_builder *b, const struct peios_token_flags *f);
  • write_restricted — the token's restricting SIDs are checked only for write access.
  • user_deny_only — the user SID is usable for deny ACEs but not to grant access.
  • isolation_boundary — marks an isolation boundary for confinement.
  • confinement_exempt — the token is exempt from confinement checks.

3.3.5 Claims #

A claim is a named, typed, multi-valued security attribute — the input to conditional (callback) ACEs. Claims come in user and device flavors; both share the same shape.

struct peios_token_claim_value {
    uint64_t    scalar;   /* INT64 / UINT64 / BOOLEAN (0 or 1) */
    const void *bytes;    /* STRING (UTF-8) / SID / OCTET */
    size_t      len;
};

struct peios_token_claim {
    const char *name;         /* UTF-8; transcoded to UTF-16LE on the wire */
    uint16_t    value_type;   /* KACS_CLAIM_TYPE_* */
    uint32_t    flags;        /* KACS_CLAIM_ATTR_* */
    const struct peios_token_claim_value *values;
    unsigned    value_count;
};

void peios_token_builder_add_user_claim(peios_token_builder *b,
                                        const struct peios_token_claim *claim);
void peios_token_builder_add_device_claim(peios_token_builder *b,
                                          const struct peios_token_claim *claim);

The value_type selects which member of each value carries the data:

value_typeValue member
KACS_CLAIM_TYPE_INT64 / _UINT64 / _BOOLEANscalar (a boolean is 0 or 1).
KACS_CLAIM_TYPE_STRINGbytes/len — a UTF-8 string (transcoded to UTF-16LE on the wire).
KACS_CLAIM_TYPE_SIDbytes/len — a binary SID.
KACS_CLAIM_TYPE_OCTETbytes/len — an opaque blob.

Each claim you add is round-tripped through the kernel's own claim parser before acceptance, so a malformed claim latches EINVAL on the builder immediately — you find out at build time, not at token-create time.

3.3.6 LCS registry credentials #

The final optional section grants the token registry-layer powers: which layer scopes it can resolve and which private layers it owns.

struct peios_token_lcs_credentials {
    const uint8_t (*scope_guids)[16];    /* array of 16-byte GUIDs, each non-nil & unique */
    unsigned    scope_count;             /* <= KACS_TOKEN_LCS_MAX_SCOPE_GUIDS */
    const char *const *private_layers;   /* UTF-8 names, 1..255 bytes, no '/' or '\\', unique */
    unsigned    private_layer_count;     /* <= KACS_TOKEN_LCS_MAX_PRIVATE_LAYERS */
};
void peios_token_builder_lcs_credentials(peios_token_builder *b,
                                         const struct peios_token_lcs_credentials *creds);

Setting it replaces any prior credentials; it is emitted as the last token-spec section. See <peios/registry.h> for what layers and scopes mean.

3.3.7 Finishing the builder #

ssize_t peios_token_builder_bytes(peios_token_builder *b, const void **out);
int     peios_token_builder_create(peios_token_builder *b);
int     peios_token_builder_error(const peios_token_builder *b);
  • peios_token_builder_bytes returns the serialized length and, if out is non-NULL, writes a pointer into the builder (valid until the next reset/free) through it. Use this if you want the raw token-spec bytes.
  • peios_token_builder_create does it in one step: serialize and mint, returning the new token fd. This is the usual call. It requires SeCreateTokenPrivilege.
  • peios_token_builder_error returns the latched errno, or 0.

Errors: _bytes and _create first surface any latched builder error — EINVAL (malformed field, SID, claim, or index) or ENOMEM (allocation failed). A clean _create then adds the peios_token_create_raw set: EPERM (privilege missing), EINVAL (spec failed kernel validation), ENOMEM.

peios_token_builder *tb = peios_token_builder_new();
peios_token_builder_user(tb, user_sid, user_len);
peios_token_builder_add_group(tb, admins_sid, admins_len, KACS_SE_GROUP_ENABLED);
peios_token_builder_type(tb, KACS_TOKEN_TYPE_PRIMARY, 0);
peios_token_builder_integrity(tb, PEIOS_IL_MEDIUM);
peios_token_builder_session(tb, session_id);

int tok = peios_token_builder_create(tb);       /* -1 on failure */
if (tok < 0) { int e = peios_token_builder_error(tb); /* or errno */ }
peios_token_builder_free(tb);

3.4 Query

Peios / Developing for Peios / SDK Reference / token.h — Tokens

You read a token's contents by information class. The generic reader handles any class getxattr-style; typed convenience wrappers cover the common ones.

ssize_t peios_token_query(int fd, uint32_t info_class, void *buf, size_t cap);
ssize_t peios_token_user(int fd, void *sid_buf, size_t cap);   /* CLASS_USER */
  • peios_token_query reads the class info_class (KACS_TOKEN_CLASS_*) into buf using the two-call protocol. Classes that return SID arrays or ACLs are parsed afterward with the <peios/security.h> views — for example read CLASS_GROUPS into a buffer, then peios_sid_array_parse it.
  • peios_token_user is the same two-call read specialized to the user SID (CLASS_USER): probe with sid_buf == NULL, cap == 0, then retrieve.

For the common scalar classes there are typed helpers that write through a mandatory non-NULL out-pointer and return 0 / -1:

struct peios_privilege_set {
    uint64_t present;
    uint64_t enabled;
    uint64_t enabled_by_default;
    uint64_t used;
};

struct peios_token_statistics {
    uint64_t token_id;
    uint64_t auth_id;       /* LogonSession LUID */
    uint64_t modified_id;
    uint32_t token_type;
    uint32_t reserved;
    uint64_t expiration;
};

int peios_token_type(int fd, uint32_t *out);            /* CLASS_TYPE */
int peios_token_impersonation_level(int fd, uint32_t *out); /* CLASS_IMPERSONATION_LEVEL */
int peios_token_interactivity_scope(int fd, uint32_t *out); /* CLASS_INTERACTIVITY_SCOPE */
int peios_token_guid(int fd, uint8_t guid_out[16]);     /* CLASS_GUID */
int peios_token_statistics(int fd, struct peios_token_statistics *out); /* CLASS_STATISTICS */
int peios_token_integrity(int fd, uint32_t *level_rid_out); /* CLASS_INTEGRITY_LEVEL */
int peios_token_privileges(int fd, struct peios_privilege_set *out); /* CLASS_PRIVILEGES */

peios_token_impersonation_level reads the token's impersonation level (KACS_IMLEVEL_*): the ceiling on everything captured from, conveyed by, or duplicated out of it — on a primary token as much as an impersonation one, since the level only ever ratchets down (Kernel TRM §3.5.1). A manager handed a token over a socket reads this before deciding what the token can become; a token below Impersonation cannot be turned into a primary token for a new process.

peios_token_interactivity_scope reads the token's interactive-environment scope. It is not a logon-session identifier. To read the token's uint64_t LogonSession LUID, use peios_token_statistics and inspect auth_id; that helper returns the complete fixed-width statistics record.

peios_token_guid writes the immutable 16-byte token GUID used by KMES. The caller supplies 16 writable bytes; the helper leaves them unchanged on failure. The result contains raw bytes in KMES order. The query requires TOKEN_QUERY; kernels predating KACS_TOKEN_CLASS_GUID return EINVAL. Deploy the supporting kernel before consumers. The statistics record and its LUID remain unchanged.

peios_token_privileges returns all four privilege words at once: which privileges are present, which are enabled, which are enabled_by_default, and which have been used (the audit trail of privilege use).

Errors (all query calls): EACCES (handle lacks QUERY), EINVAL (unknown class), ERANGE (non-probe buffer too small), EFAULT (bad buffer pointer). The typed helpers add EINVAL (NULL out-pointer, or an unexpected payload shape).

3.5 Adjust and Transform

Peios / Developing for Peios / SDK Reference / token.h — Tokens

These change a token or derive a new one from it. Deriving calls return a new fd; in-place adjustments return 0 / -1.

3.5.1 Privileges and groups #

int peios_token_adjust_privileges(int fd, const struct kacs_priv_entry *entries,
                                  unsigned count, uint64_t *prev_enabled);
int peios_token_reset_privileges(int fd);
int peios_token_adjust_groups(int fd, const struct kacs_group_entry *entries,
                              unsigned count, uint64_t *prev_state);
int peios_token_reset_groups(int fd);
  • peios_token_adjust_privileges enables/disables the privileges named in entries (each a kacs_priv_entry); if prev_enabled is non-NULL it receives the prior enabled mask, so you can restore it later. peios_token_reset_privileges restores enabled := enabled_by_default. Errors: EACCES (handle lacks ADJUST_PRIVILEGES), EINVAL (empty or oversized batch, duplicate entry, enabling an absent privilege, unknown attribute bits), EFAULT (bad entries pointer).
  • peios_token_adjust_groups is the group analogue. prev_state, if non-NULL, points at a caller array of KACS_TOKEN_GROUP_MASK_WORDS uint64_t words that receives the prior enabled bitmask. peios_token_reset_groups restores the default group state. Errors: EACCES (handle lacks ADJUST_GROUPS), EINVAL (mandatory, deny-only, or logon-SID group targeted; duplicate or out-of-range index; empty batch), EFAULT (bad entries pointer).

3.5.2 Duplicate and restrict #

int peios_token_duplicate(int fd, uint32_t access, uint8_t type, uint8_t imp_level);

struct peios_token_restrict {
    uint64_t           privs_to_delete;
    const uint32_t    *deny_group_indices;   /* groups demoted to deny-only */
    unsigned           deny_count;
    const void *const *restrict_sids;        /* added restricting SIDs */
    const size_t      *restrict_sid_lens;
    unsigned           restrict_count;
    uint32_t           flags;                /* KACS_TOKEN_RESTRICT_WRITE_RESTRICTED */
};
int peios_token_restrict(int fd, const struct peios_token_restrict *spec);
  • peios_token_duplicate copies the token, returning a new fd with handle rights access, token type (KACS_TOKEN_TYPE_*), and impersonation level imp_level (KACS_IMLEVEL_*). This is how you turn a primary token into an impersonation token, an impersonation token into a primary one for a process launched as that identity, or narrow a handle's rights. imp_level is a ratchet: it can equal or lower the source's level, never raise it, whichever direction the type goes. Errors: EACCES (handle lacks DUPLICATE, or the new token's SD denies access), EINVAL (unknown type/imp_level, a level above the source's, a primary requested below KACS_IMLEVEL_IMPERSONATION, empty or unknown access bits), ENOMEM (allocation failed).
  • peios_token_restrict creates a filtered token — the sandboxing primitive. It can delete privileges (privs_to_delete), demote groups to deny-only (deny_group_indices, by index), add restricting SIDs (restrict_sids/restrict_sid_lens), and set KACS_TOKEN_RESTRICT_WRITE_RESTRICTED. The result is a strictly less-powerful token you can hand to less-trusted code. Errors: EACCES (handle lacks DUPLICATE), EINVAL (duplicate or out-of-range deny index, malformed restricting SID, unknown flags, NULL spec, or arrays), ENOMEM (allocation failed).

3.5.3 Impersonation and installation #

int peios_token_install(int fd);
int peios_token_impersonate(int fd);
int peios_token_revert(void);
  • peios_token_install makes this primary token the calling process's primary token. Errors: EACCES (handle lacks ASSIGN_PRIMARY, or SeAssignPrimaryTokenPrivilege missing), EINVAL (not a primary token), EAGAIN (thread set changed mid-install — retry), ENOMEM (allocation failed).
  • peios_token_impersonate makes this impersonation token the calling thread's effective identity — subsequent access checks on that thread run as the impersonated identity. Errors: EACCES (handle lacks IMPERSONATE), EINVAL (not an impersonation token), EPERM (restricted→unrestricted same-user — the one hard deny), ENOMEM (allocation failed).
  • peios_token_revert undoes it: it clears the thread's impersonation token so checks run as the thread's real (primary) identity again. It takes no argument and is a no-op (reported as success) if the thread was not impersonating. This is the inverse of peios_token_impersonate — always pair them, ideally with revert in the cleanup path. Errors: none in normal operation.

The archetypal server flow: peios_token_open_peer the caller → peios_token_impersonate it → do the work as them → peios_token_revert. peios_token_impersonate_peer (see Opening and creating tokens) fuses the first two steps and the close.

3.5.4 Linked tokens and defaults #

int peios_token_link(int elevated_fd, int filtered_fd, uint64_t logon_session_id);
int peios_token_get_linked(int fd);
int peios_token_adjust_default(int fd, const void *dacl, size_t len,
                               uint16_t owner_index, uint16_t group_index);
int peios_token_set_interactivity_scope(int fd, uint32_t scope);
  • peios_token_link links an elevated + filtered primary-token pair in logon_session_id — the UAC-style split-token model, where a filtered token is the everyday identity and its elevated linked token is available on demand. peios_token_get_linked opens the linked token of fd, returning a new fd. Errors (_link): EACCES (SeTcbPrivilege missing, or either handle lacks DUPLICATE), EINVAL (self-link, role/logon-session/user-SID mismatch, not primary tokens, unknown logon_session_id, or an fd that is not a token fd), EBADF (invalid fd). Errors (_get_linked): EACCES (handle lacks QUERY), ENOENT (not part of a linked pair, or the pair was destroyed), ENOMEM (allocation failed).
  • peios_token_adjust_default replaces the token's default DACL, owner/primary-group indices, or both. dacl == NULL leaves the DACL unchanged (and ignores len); dacl != NULL with len == 0 clears it; an index of 0xFFFF leaves that index unchanged. Errors: EACCES (handle lacks ADJUST_DEFAULT), EINVAL (out-of-range index; malformed or oversized DACL), EFAULT (bad DACL pointer).
  • peios_token_set_interactivity_scope changes the token's uint32_t interactive-environment scope (requires SeTcbPrivilege). This is deliberately separate from the token's uint64_t LogonSession LUID (auth_id) and does not move the token between logon sessions. Errors: EACCES (handle lacks ADJUST_INTERACTIVITY_SCOPE, or SeTcbPrivilege missing).

3.6 Logon Sessions

Peios / Developing for Peios / SDK Reference / token.h — Tokens

A logon session is the lightweight kernel bookkeeping a token references — the "logon" a token belongs to. Creating and destroying them requires SeTcbPrivilege.

struct peios_session_spec {
    uint8_t     logon_type;     /* KACS_LOGON_TYPE_* */
    const char *auth_package;   /* UTF-8; may be "" */
    const void *user_sid;
    size_t      user_sid_len;
};

int peios_session_create(const struct peios_session_spec *spec, uint64_t *id_out);
int peios_session_destroy_empty(uint64_t session_id);
  • peios_session_create creates a logon session of type logon_type (KACS_LOGON_TYPE_* — interactive, network, service, …) for user_sid, attributing it to auth_package. id_out is mandatory and receives the new session id, which you then pass to peios_token_builder_session. Errors: EPERM (SeTcbPrivilege missing), EINVAL (NULL spec, id_out, or field; malformed SID; oversized spec), EFAULT (bad pointer), ENOMEM (allocation failed).
  • peios_session_destroy_empty destroys a session that has no live tokens — it fails rather than orphaning tokens. Clean up sessions only after every token referencing them is closed. Errors: EPERM (SeTcbPrivilege missing), ENOENT (no such session), EBUSY (live tokens, linked-pair state, or in-flight references).

3.6.1 Listing sessions #

struct peios_logon_session {
    uint64_t       logon_session_id;  /* a token's auth_id */
    uint64_t       created_at;        /* seconds since the Unix epoch */
    uint32_t       logon_type;        /* KACS_LOGON_TYPE_* */
    uint32_t       user_sid_len;
    const uint8_t *user_sid;          /* binary SID */
    const char    *auth_package;      /* UTF-8, not NUL-terminated */
    uint32_t       auth_package_len;
    uint32_t       reserved;
};

peios_logon_sessions *peios_logon_sessions_open(void);
int  peios_logon_sessions_next(peios_logon_sessions *s, struct peios_logon_session *out);
void peios_logon_sessions_close(peios_logon_sessions *s);

The kernel's own list of every live logon session, from /sys/kernel/security/kacs/sessions. Reading it needs BUILTIN\Administrators or SYSTEM.

  • peios_logon_sessions_open takes the whole listing at once, so a walk sees one moment. NULL with errno on failure: EACCES (not an administrator), ENOENT (securityfs not mounted), ENOMEM.
  • peios_logon_sessions_next fills out with the next session and returns 1, or 0 when there are no more. The pointers in out stay valid until the next call. -1 with EPROTO means a line it could not read; call again to step past it.
  • peios_logon_sessions_close frees the reader.

A session is listed while anything holds it, which includes a session nothing has used yet, so a listing can hold sessions with no process in them. SYSTEM's session is 999. To find a session's processes, read each process's token's auth_id (TokenStatistics) and match it.

peios_logon_sessions *s = peios_logon_sessions_open();
struct peios_logon_session one;
while (s && peios_logon_sessions_next(s, &one) == 1)
    printf("%llu type %u\n", (unsigned long long)one.logon_session_id, one.logon_type);
peios_logon_sessions_close(s);

3.7 The Generic Mapping

Peios / Developing for Peios / SDK Reference / token.h — Tokens

extern const struct kacs_generic_mapping peios_token_generic_mapping;

The canonical generic→specific rights mapping for the token object class. Pass it to peios_access_map_generic or as the mapping in a peios_access_request when the object under check is a token.

4.1 Access Checks

Peios / Developing for Peios / SDK Reference / access.h — Access Checks

<peios/access.h> answers the central question of the whole access-control model: can this subject perform this access on this object? You hand it a token, a security descriptor, and a desired access mask, and it runs the full KACS AccessCheck pipeline and tells you whether access is granted and exactly which rights were granted.

Two things are worth saying up front:

  • These calls are advisory. They evaluate, they do not enforce. peios_access_check tells you what the answer would be; enforcement of a real operation always runs inside the kernel against the subject's own process security block. Use these when your code is the resource manager — you hold an object, you have its security descriptor, and you need to make the grant/deny decision yourself.
  • A denial is a normal result, not an error. Per the library conventions, a denied check returns -1 with errno == EACCES, and the granted mask is still written out. Only a genuine failure (a bad token fd, a malformed SD) is an error in the usual sense.

4.1.1 See also #

  • <peios/security.h> — building the security descriptors and reading the generic-mapping tables this check consumes.
  • <peios/token.h> — obtaining the token_fd to check, and peios_token_generic_mapping.
  • Access decisions — the operator-side account of how KACS reaches a grant/deny decision.

4.2 The Request

Peios / Developing for Peios / SDK Reference / access.h — Access Checks

Every check is described by a single struct peios_access_request. Only the first block is needed for an ordinary check; everything below the divider is advanced and can be left zero/NULL. For every pointer/length pair, NULL is valid only when the matching length or count is zero.

struct peios_access_request {
    int      token_fd;   /* -1 = the caller's effective token */
    const void *sd;      /* the object's security descriptor (wire bytes) */
    size_t   sd_len;
    uint32_t desired;    /* desired access mask */
    struct kacs_generic_mapping mapping;   /* the object class's mapping */

    /* ---- [adv] ---- */
    const void *self_sid;        /* PRINCIPAL_SELF substitution; NULL to omit */
    size_t   self_sid_len;
    uint32_t privilege_intent;   /* backup/restore intent bits */
    const struct kacs_object_type_entry *object_tree;
    uint32_t object_tree_count;
    const void *local_claims;    /* @Local claim array */
    size_t   local_claims_len;
    uint32_t pip_type;           /* 0 = use the subject's PSB */
    uint32_t pip_trust;
    const void *audit_context;   /* the guarded object, a PGSS §6.7 map */
    size_t   audit_context_len;
};

4.2.1 The core fields #

FieldMeaning
token_fdThe subject token to evaluate. -1 means the caller's own effective token — the common case when you are checking access for yourself. Otherwise pass a token fd from <peios/token.h>.
sd / sd_lenThe object's security descriptor, as self-relative wire bytes — typically from a peios_sd_builder or read off the object.
desiredThe access mask you want checked. It can contain generic bits; the mapping resolves them.
mappingThe object class's generic mapping (a struct kacs_generic_mapping), so generic rights in desired and in the SD's ACEs fold to the right object-specific bits. Use the class's published table — for example peios_file_generic_mapping or peios_token_generic_mapping.

4.2.2 The advanced fields #

Leave these zero/NULL unless you need them:

FieldMeaning
self_sid / self_sid_lenThe SID to substitute for PRINCIPAL_SELF (S-1-5-10) in ACEs — the "self" the object belongs to.
privilege_intentBackup/restore intent bits, letting SeBackupPrivilege / SeRestorePrivilege widen the granted mask as they would for a real backup or restore.
object_tree / object_tree_countAn object-type tree for a per-property check (object ACEs with type GUIDs). Mandatory for peios_access_check_list.
local_claims / local_claims_lenAn @Local claim array to evaluate conditional ACEs against, beyond the claims already on the token.
pip_type / pip_trustProcess-integrity-protection trust label to evaluate against; pip_type == 0 uses the subject's own PSB.
audit_context / audit_context_lenThe identity of the object a daemon is guarding, for the audit record of the check: one MessagePack map holding kind and, under a key equal to the kind, the object's identifying fields — {kind: "service", service: {name: "jellyfin"}} — as PGSS §6.7 defines. The kernel accepts only that shape and fails the check with EINVAL otherwise. It copies the map into the kacs.audit.access.checked record as object.kind and object.<kind>.*, and marks the record fields.attestation.userspace, because the values are the caller's claim. Build it with peios_audit_context_encode. Both check calls validate a non-NULL context before the syscall and fail with EINVAL if the kernel would refuse it.

4.3 The Check

Peios / Developing for Peios / SDK Reference / access.h — Access Checks

int peios_access_check(const struct peios_access_request *req,
                       uint32_t *granted, struct peios_access_audit *audit);

Runs the full AccessCheck pipeline. Returns:

  • 0 if every right in desired is granted;
  • -1 with errno == EACCES if any desired right is denied;
  • -1 with another errno on a real error (for example EBADF for a bad token_fd, EINVAL for a malformed SD).

granted, if non-NULL, always receives the granted access mask — even on denial. This is the useful part: you can request a broad desired and read back exactly which subset was granted, rather than probing one right at a time. audit, if non-NULL, receives the audit outputs.

struct peios_access_request req = {
    .token_fd = -1,                      /* my own effective token */
    .sd = sd_bytes, .sd_len = sd_len,
    .desired = KACS_ACCESS_READ | KACS_ACCESS_WRITE,
    .mapping = peios_file_generic_mapping,
};

uint32_t granted = 0;
int rc = peios_access_check(&req, &granted, NULL);
if (rc == 0) {
    /* both READ and WRITE granted */
} else if (errno == EACCES) {
    /* denied; `granted` shows what WAS allowed (maybe READ only) */
} else {
    /* error: perror("access_check") */
}

libpeios owns the versioned struct kacs_access_check_args under the hood — it sets caller_size and zeroes the reserved fields so the request stays forward-compatible across kernel versions. You only ever fill in the peios_access_request above.

4.3.1 A supplied identity without a token #

int peios_access_check_subject(const struct peios_access_request *request,
                              const struct peios_access_subject *subject,
                              uint32_t object_index,
                              struct peios_subject_access_result *out);

Use this separate entry point when a trusted identity authority supplies a principal SID, source groups and disclosed claims without creating an OS logon token. libpeios packs the facts for the stateless kernel query, syscall 1028. An older kernel returns ENOSYS; no userspace fallback runs. Supplying SYSTEM's SID computes a hypothetical result; it conveys no SYSTEM authority.

The SD must be valid and have an owner. Set subject.size to its structure size and request.token_fd to -1. Here -1 is a required sentinel and never selects the caller's token. The privilege-intent, PIP, and request-local claim fields must be zero or NULL; local claim knowledge belongs in subject.

Subject group entries contain a SID span and KACS group attributes, including enabled and deny-only flags. A NULL list with zero count is unknown. A non-NULL list with zero count is a complete empty set. A NULL list with nonzero count is invalid. Group, claim, and known-absence arrays are bounded to 1024 entries. Group SIDs must be unique.

Each optional claim context contains typed peios_token_claim values, explicit known-absent names, and a complete flag. These use the same claim encoding and validation as the token builder. With complete equal to zero, any name not in the values or known-absent list remains unknown. With complete equal to one, omitted names are absent. Values and absence assertions must not contradict one another; equivalent names must be unique. Absent names are UTF-8 strings of 1–255 bytes. An omitted claim context is unknown, not an empty set.

Name equivalence follows the KACS conditional evaluator's Unicode lowercase mapping. An absence assertion must cover that entire equivalence class. A source using different name rules needs an adapter; copying its named absence responses directly can turn an existing equivalent claim into an apparent absence. Updated PGSS named disclosure uses this same rule, so its explicit absent_claims supply partial knowledge. Clients and authority must both use the updated Unicode name contract; the superseded ASCII-only development contract is incompatible for this purpose. A complete AllPermitted result can supply complete knowledge; a Filtered result supplies values with partial coverage and no invented absences. Conflicting equivalent values are invalid.

The return value is zero for all three decisions. Inspect out.decision:

DecisionMeaning
PEIOS_SUBJECT_ACCESS_GRANTEDAll requested rights were granted
PEIOS_SUBJECT_ACCESS_DENIEDThe supplied facts establish denial
PEIOS_SUBJECT_ACCESS_MISSING_CONTEXTMore context is needed for a safe answer

Missing-context results carry a zero granted mask and a category bitmask in out.missing. They do not identify restricted claim names or values. A service must not admit a caller using a provisional or partial answer. Missing-data detection is conservative and can request context from an irrelevant branch. Errors return -1 with errno; do not use a returned decision after an error.

The initial identity-only interface reuses KACS DACL, group, conditional, and object-list semantics. It does not invent process privileges, integrity, confinement, or a logon session. Explicit integrity/trust labels, scoped policy, and privilege-sensitive rights report missing execution context. Resource claims can be read from the supplied SD's SACL. This is not a replacement for the full token pipeline or kernel object enforcement.

For object ACEs, supply the object tree and select the node with object_index. Without a tree, the index is zero and GUID-scoped ACEs report missing object context instead of being interpreted as global grants.

Matching SACL audit ACEs emit kacs.audit.subject.checked when the actual caller holds enabled SeAuditPrivilege. The event's subject describes that caller; source.supplied-subject.sid is explicitly hypothetical. An optional AuditContext names the guarded object. No context leaves it unnamed. Audit-only missing facts require more context while auditing is active; they do not block the decision when the privilege gate suppresses records or the extended entry point peios_access_check_subject_ex receives PEIOS_SUBJECT_NO_AUDIT. Mandatory SACL labels still require execution context in either mode. Missing-context decisions emit no completed-check record. Detected audit preparation or submission errors fail the query; successful submission carries the existing KMES guarantees, without a durability promise. A service separately records its actual admission outcome.

The kernel copies one bounded request and validates that owned copy. A concurrent writer can produce a torn copy, which is still treated as untrusted input. Requests larger than 1 MiB, excessive collections, conflicting facts, and malformed sections are rejected whole. Typed claims are bounded to 64 KiB per namespace and 1024 values per attribute. The aggregate sum of encoded entry bytes multiplied by max(value count, 1), including descriptor resource claims, cannot exceed 1 MiB; this bounds repeated-offset decoding before allocation. No facts are silently truncated.

The safe Rust wrapper exposes AccessCheck::check_subject and check_subject_by_type with SuppliedSubject, SuppliedClaims, and an explicit SubjectAccessDecision. Use audit_context to label the guarded object and subject_no_audit(true) to suppress this query's audit records. That setter does not alter real-token checks or service admission events.

4.4 Audit Outputs

Peios / Developing for Peios / SDK Reference / access.h — Access Checks

struct peios_access_audit {
    uint32_t continuous_audit;   /* OR of matching alarm masks */
    int      staging_mismatch;   /* 1 if the staged CAAP result differs */
};

When you pass a non-NULL audit, the check reports:

  • continuous_audit — the OR of the masks of any SYSTEM_ALARM ACEs that matched. An enforcement point that keeps this mask on a handle emits a kacs.audit.handle.used event for each later operation whose required access overlaps it.
  • staging_mismatch — 1 if evaluating the staged central access policy would have produced a different result than the active one. This is the signal you watch when rolling out a central access policy change: a non-zero value means the pending policy would decide this access differently. The kernel records the same difference as a kacs.caap.staging.diverged event.

These are the outputs the check hands back to you. The audit records it writes to the event stream — kacs.audit.access.checked and kacs.audit.privilege.used — go to KMES, not to this struct. They name the object you checked only if the request carried an audit context, the map {kind: "<kind>", "<kind>": {…}}; anything else in that field fails the check with EINVAL.

4.5 The Object-type-list Variant

Peios / Developing for Peios / SDK Reference / access.h — Access Checks

int peios_access_check_list(const struct peios_access_request *req,
                            struct kacs_node_result *results, uint32_t count);

peios_access_check_list is the AccessCheckByTypeResultList form — a per-node check over an object-type tree, for objects whose properties or property sets carry their own object ACEs (a directory-service-style object, say). It evaluates the whole tree in one call and reports a separate result for each node.

  • req->object_tree / object_tree_count are mandatory here — they describe the tree of kacs_object_type_entry nodes to evaluate.
  • results receives one kacs_node_result per node, in preorder, and count must equal req->object_tree_count.
  • Returns 0 / -1 (EINVAL if count doesn't match, and the usual errors otherwise).

Each kacs_node_result carries that node's granted mask and status, so you can discover, for example, that a caller can read most of an object but not one protected property — in a single check rather than one per property.

4.6 The Audit Context

Peios / Developing for Peios / SDK Reference / access.h — Access Checks

A daemon that guards objects of its own (a service manager's services, an event store's namespaces) makes each access decision through peios_access_check. The kernel records that decision in a kacs.audit.access.checked event when the descriptor's SACL asks for one, but the kernel cannot tell what the descriptor belongs to. The audit context tells it. It is the request's audit_context field: one MessagePack map holding kind and, under a key equal to the kind, the fields that identify the object.

{kind: "service", service: {name: "jellyfin"}}

The kernel copies it into the record as object.kind and object.service.name, and marks the record fields.attestation.userspace, because the kernel did not observe those values: they are the daemon's claim. It refuses any other shape with EINVAL. PGSS §6.7 is the specification. A component that guards objects must pass one, and each field it names must be defined, as asserted, in that component's catalog fragment.

4.6.1 Encoding one #

enum peios_audit_value_type {
    PEIOS_AUDIT_STR  = 0,   /* bytes/len: a UTF-8 string, not NUL-terminated */
    PEIOS_AUDIT_UINT = 1,   /* scalar */
    PEIOS_AUDIT_INT  = 2,   /* scalar, read as a two's-complement int64_t */
    PEIOS_AUDIT_BOOL = 3,   /* scalar: 0 or 1 */
    PEIOS_AUDIT_BIN  = 4,   /* bytes/len: binary, for example a SID or GUID */
};

struct peios_audit_field {
    const char *key;         /* NUL-terminated; one kebab-case segment */
    uint32_t    value_type;  /* enum peios_audit_value_type */
    uint64_t    scalar;
    const void *bytes;
    size_t      len;
};

ssize_t peios_audit_context_encode(const char *kind,
                                   const struct peios_audit_field *fields,
                                   size_t count, void *buf, size_t cap);

peios_audit_context_encode writes the map for an object of kind kind, identified by count fields, using the two-call protocol: pass cap == 0 to learn the size. With no fields (fields can then be NULL), the context is {kind: <kind>}.

kind and every key must be a single segment of an event name: kebab-case, [a-z][a-z0-9]*(-[a-z0-9]+)*, so service, log-namespace or unit-name. A value is a scalar in one of the event wire forms: a string, an unsigned or signed integer, a boolean, or binary. A SID goes in as PEIOS_AUDIT_BIN with its binary bytes, never as SDDL text. There is no nil: a field with no value is left out of the array.

struct peios_audit_field fields[] = {
    { .key = "name", .value_type = PEIOS_AUDIT_STR,
      .bytes = "jellyfin", .len = strlen("jellyfin") },
};
uint8_t ctx[128];
ssize_t n = peios_audit_context_encode("service", fields, 1, ctx, sizeof ctx);
if (n < 0) { perror("audit context"); return -1; }

struct peios_access_request req = {
    .token_fd = caller_fd,
    .sd = sd_bytes, .sd_len = sd_len,
    .desired = SERVICE_START,
    .mapping = service_mapping,
    .audit_context = ctx, .audit_context_len = (size_t)n,
};
uint32_t granted = 0;
int rc = peios_access_check(&req, &granted, NULL);

The encoder fails with EINVAL when:

  • the kind or a key is not a segment, or a key is NULL;
  • a key appears twice;
  • value_type is not one of the five, or a boolean's scalar is not 0 or 1;
  • a string is not valid UTF-8, or bytes is NULL while len is not zero;
  • the encoded map would be longer than KACS_ACCESS_CHECK_MAX_AUDIT_CONTEXT_LEN (4096 bytes).

The kernel itself allows a nil value, a nested value, or a key that appears twice inside the body. The encoder refuses all three. A field with no value is left out (PGSS §6.5), an identifying field is a scalar, and a repeated key would make object.<kind>.<key> ambiguous.

4.6.2 Validating one built another way #

int peios_audit_context_validate(const void *buf, size_t len);

If you build the map yourself, for example with the msgpack writer, peios_audit_context_validate checks it against the kernel's own rules. It returns 0 if the kernel would accept it, and -1 with EINVAL otherwise, including for NULL or empty input. The rules are:

  • the top level is a map holding a string kind that is one segment, and at most one other key;
  • that key, if present, equals the kind, and its value is a non-empty map whose keys are segments;
  • nothing follows the map;
  • the bytes are well-formed MessagePack (UTF-8 strings, no reserved 0xC1 byte), nested no deeper than 31 levels. That is the event nesting limit less one, because the context lands one level below the record's root;
  • the map is at most 4096 bytes.

peios_access_check and peios_access_check_list apply the same check to any non-NULL audit_context before they make the syscall. A malformed context therefore fails there with EINVAL, without reaching the kernel. A non-NULL pointer with a zero length is refused too, as the kernel refuses it.

4.6.3 Language bindings #

Audit Contexts in Rust explains owned encoding and AccessDecision results. Audit Contexts in Go uses the maintained access package and its explicit denial errors.

5.1 File Security

Peios / Developing for Peios / SDK Reference / file.h — File Security

<peios/file.h> is the file surface of KACS. Where ordinary POSIX open() gives you a file descriptor governed by mode bits, peios_file_open performs a native KACS open — an NtCreateFile-shaped call carrying a desired access mask, a create disposition, create options, the sharing it allows other opens, and an optional creator security descriptor — and hands back an ordinary Linux file fd whose granted access mask is fixed for the fd's lifetime. Because the grant is baked into the fd, it can be delegated safely by dup, SCM_RIGHTS, or across exec: whoever holds the fd holds exactly the access it was opened with, no more.

Alongside the open, this module:

  • reads back what an open was granted, sets its file's delete disposition and renames the link it names (Working through a handle);
  • takes NT byte-range locks and leases through it (Locks and leases);
  • reads and sets a file's read-only flag and Created At (Special attributes);
  • reads and writes a file's security descriptor, by path or by fd; and
  • governs how a superblock without native SD storage is treated.

The wire constants and argument structs (KACS_DISPOSITION_*, KACS_CREATE_OPT_*, KACS_FILE_*, KACS_OPEN_*, KACS_RENAME_*, KACS_LOCK_*, KACS_LEASE_*, KACS_SATTR_*, KACS_SECINFO_*, KACS_MOUNT_POLICY_*, KACS_STATUS_*, struct kacs_open_info, struct kacs_lease_break, struct kacs_sattr) come from <pkm/file.h> and <pkm/sd.h>. The security descriptors these calls exchange are built and parsed with <peios/security.h>.

5.1.1 See also #

  • <peios/security.h> — building the creator SDs and parsing the SDs these calls return.
  • <peios/access.h> — evaluating a file SD with peios_file_generic_mapping.
  • File access and Mount policies — the operator-side model of native file security.
  • Sharing and Deletion — the kernel's rules for share modes, delete-pending files and pinning.

5.2 Opening a File

Peios / Developing for Peios / SDK Reference / file.h — File Security

peios_file_open requests an explicit access mask and creation policy. The returned descriptor represents the access granted by the kernel. The kernel native-open guide describes the kernel's validation and file creation behavior.

struct peios_open_params {
    uint32_t    desired_access; /* KACS_FILE_* | standard | generic | MAXIMUM_ALLOWED */
    uint32_t    disposition;    /* KACS_DISPOSITION_* */
    uint32_t    options;        /* KACS_CREATE_OPT_* */
    uint32_t    flags;          /* AT_SYMLINK_NOFOLLOW | KACS_BACKUP_INTENT | KACS_RESTORE_INTENT |
                                   KACS_OPEN_SHARE_ACCESS | KACS_OPEN_LEASE_KEY |
                                   KACS_OPEN_PIN_ANCESTORS */
    const void *sd;             /* creator SD on create, else NULL */
    size_t      sd_len;
    uint32_t    share_access;   /* KACS_FILE_SHARE_*, with KACS_OPEN_SHARE_ACCESS */
    int         lease_fd;       /* lease manager, with KACS_OPEN_LEASE_KEY */
    uint8_t     lease_key[16];  /* with KACS_OPEN_LEASE_KEY */
};

int peios_file_open(int dirfd, const char *path,
                    const struct peios_open_params *p, uint32_t *status_out);

peios_file_open opens path relative to dirfd (the usual *at convention — an absolute path ignores dirfd, and AT_FDCWD means the current directory). It returns a file fd, or -1 with errno.

Zero-initialize the struct and set the fields you need. share_access and the lease fields are read only when flags carries their flag, so a zeroed struct opens the way a plain open(2) does: sharing read, write, and delete.

The parameters:

FieldMeaning
desired_accessThe access mask you are requesting — KACS_FILE_* object rights, standard rights, or generic bits the file class maps. Every right named has to be granted, or the open fails with EACCES. MAXIMUM_ALLOWED asks for everything you can have, and can be named alone.
dispositionWhat to do about existence: KACS_DISPOSITION_* — open-existing, create-new, open-or-create, supersede, overwrite, and so on. This is the create/open decision open() splits across O_CREAT/O_EXCL/O_TRUNC.
optionsKACS_CREATE_OPT_DIRECTORY and KACS_CREATE_OPT_DELETE_ON_CLOSE; other bits fail with EINVAL. No-follow belongs in flags, not options.
flagsAT_SYMLINK_NOFOLLOW; the privilege-intent flags KACS_BACKUP_INTENT / KACS_RESTORE_INTENT; and the flags that switch on the fields below.
sd / sd_lenThe creator security descriptor — the SD to stamp on a newly created file. Pass NULL when opening an existing file (or to let the parent's inheritance decide the new file's SD).
share_accessWith KACS_OPEN_SHARE_ACCESS: which kinds of access other opens of the file can have while this one is open — KACS_FILE_SHARE_READ, _WRITE, and _DELETE.
lease_fd / lease_keyWith KACS_OPEN_LEASE_KEY: a lease manager and the key this opener holds leases under. Opening does not break leases held under the same manager and key (Locks and leases).

KACS_OPEN_PIN_ANCESTORS keeps the directories above the file from being renamed or removed while the open lasts, as Windows does for a file it has open. It needs SeLockParentagePrivilege enabled, and fails with EPERM without it.

5.2.1 What the descriptor can do #

The descriptor's access is fixed when it opens. Read it back with peios_file_query_open, which is how you learn what a MAXIMUM_ALLOWED open received.

The descriptor is readable if it was granted FILE_READ_DATA and writable if it was granted a write right. An open granted neither is a control handle: it cannot read or write the file's contents, but it can read attributes, read and change the security descriptor, set a delete disposition, and rename. You do not need to ask for a data right to get a descriptor.

An open that creates the file gets the access it asked for, even where the new file's descriptor would not grant it, as in Windows. You can create a file with a restrictive descriptor and still write it, in one step. Integrity labels, restricted tokens and confinement still apply, and later opens are checked against the descriptor as normal.

DELETE and FILE_READ_ATTRIBUTES can come from the parent directory: from FILE_DELETE_CHILD and FILE_LIST_DIRECTORY on it, as NTFS grants them.

5.2.2 Sharing #

Every open of a regular file or directory takes part in share checking, including plain open(2). An open that conflicts with another fails with EBUSY. Without KACS_OPEN_SHARE_ACCESS your open shares everything; with it, other opens are refused the kinds of access you leave out — but only those you could exercise yourself, so a reader cannot lock others out of a file it could not change. See Sharing and Deletion for the rules.

5.2.3 Status and errors #

status_out, if non-NULL, receives a KACS_STATUS_* code telling you what happened — whether the file was opened, created, superseded, overwritten. For OPEN_IF with no creator SD (sd = NULL, sd_len = 0), this distinguishes "created a new file" from "opened the existing one" without a separate stat race. Supplying a creator SD changes the existing-file behavior described by the disposition rules.

When the open fails for a reason errno alone cannot tell apart, status_out names it:

StatuserrnoCondition
KACS_STATUS_SHARING_VIOLATIONEBUSYAnother open's sharing conflicts with this one.
KACS_STATUS_DELETE_PENDINGEBUSYThe file is marked to be deleted when its last open closes.
KACS_STATUS_CANNOT_DELETEEPERMDelete-on-close on a read-only file.

Other errors include EACCES (a requested right denied), EEXIST (create-new and the file exists), ENOENT (open-existing and it doesn't), ENOTDIR (directory option, non-directory target), ELOOP (native open with no-follow and a final symlink), EPERM (pinning without the privilege), EINVAL (unsupported create-option bits, a field set without its flag, malformed creator SD, NULL path/p, sd == NULL with sd_len != 0), and EBADF (bad dirfd, or a lease_fd that is not a lease manager).

Supplying a creator SD with OPEN fails with EOPNOTSUPP, and with OVERWRITE fails with EINVAL. With OPEN_IF or OVERWRITE_IF, it fails with EINVAL when the path resolves to an existing object. The SDK forwards the disposition and SD; it does not silently drop the SD on that branch. See the kernel native-open guide for disposition rules. Use create-only when an explicit creator SD is required:

struct peios_open_params p = {
    .desired_access = KACS_FILE_READ_DATA | KACS_FILE_WRITE_DATA,
    .disposition    = KACS_DISPOSITION_CREATE,    /* fail if the path exists */
    .sd             = creator_sd, .sd_len = creator_sd_len,
};
uint32_t status = 0;
int fd = peios_file_open(AT_FDCWD, "data.bin", &p, &status);
if (fd < 0) { /* errno */ }
/* On success, status == KACS_STATUS_CREATED. */

To open an existing file for reading while nobody else writes or deletes it:

struct peios_open_params p = {
    .desired_access = KACS_FILE_READ_DATA,
    .disposition    = KACS_DISPOSITION_OPEN,
    .flags          = KACS_OPEN_SHARE_ACCESS,
    .share_access   = KACS_FILE_SHARE_READ,
};
uint32_t status = 0;
int fd = peios_file_open(AT_FDCWD, "report.txt", &p, &status);
if (fd < 0 && status == KACS_STATUS_SHARING_VIOLATION) { /* someone else has it */ }

To open an existing object, use KACS_DISPOSITION_OPEN with sd = NULL and sd_len = 0. If create-only returns EEXIST, decide whether opening the existing object is appropriate before issuing that separate call. A create/open retry is not an atomic transaction; neither is a stat-then-open check.

The wrapper forwards options, flags, the share access, the lease fields and the creator descriptor to the kernel, and zeroes reserved fields. Supplying an option through the library does not make an unsupported kernel option valid.

5.3 Reading and Writing a File's Security Descriptor

Peios / Developing for Peios / SDK Reference / file.h — File Security

A file's SD can be accessed by path or by fd. In both cases secinfo is a mask of KACS_SECINFO_* bits selecting which components (owner, group, DACL, SACL, …) the operation touches — you read or write the parts you name and leave the rest alone.

The rights required scale with the components you touch (see Managing file security):

Component (KACS_SECINFO_*)Reading needsWriting needs
OWNER / GROUPREAD_CONTROLWRITE_OWNER (plus owner-SID validation)
DACLREAD_CONTROLWRITE_DAC
SACLACCESS_SYSTEM_SECURITYACCESS_SYSTEM_SECURITY
LABELREAD_CONTROLWRITE_OWNER (the label cannot rise above the caller's integrity without SeRelabelPrivilege)

ACCESS_SYSTEM_SECURITY is itself gated by SeSecurityPrivilege; READ_CONTROL and WRITE_DAC are implicitly granted to the owner. SACL and LABEL cannot be combined in one call (EINVAL). The check is all-or-nothing: if any requested component fails its check, the whole call fails.

5.3.1 By path #

ssize_t peios_file_get_sd(int dirfd, const char *path, uint32_t secinfo,
                          void *buf, size_t cap, uint32_t at_flags);
int     peios_file_set_sd(int dirfd, const char *path, uint32_t secinfo,
                          const void *sd, size_t len, uint32_t at_flags);
  • peios_file_get_sd reads the secinfo-selected components of path's SD into buf, getxattr-style (two-call protocol — probe with cap == 0, and a too-small non-zero buffer fails ERANGE without truncating). at_flags accepts AT_SYMLINK_NOFOLLOW; in the kernel interface, it queries the terminal symlink's own SD instead of following it. Errors: EACCES (component right missing), EINVAL (SACL + LABEL together; NULL path, or NULL buffer with non-zero cap), ERANGE (non-probe buffer too small), ENOENT (path doesn't exist), ELOOP (a path-resolution failure, not a blanket rejection of a terminal symlink under no-follow).
  • peios_file_set_sd writes the secinfo components of sd onto path, preserving the components you did not select. So to change only the DACL, build an SD with a DACL, pass secinfo = KACS_SECINFO_DACL, and the owner/group/SACL are untouched. Errors: EACCES (component right missing), EPERM (owner-SID validation failed without SeRestorePrivilege; label raised without SeRelabelPrivilege; MANDATORY attribute removed without SeTcbPrivilege), EINVAL (malformed SD, SACL + LABEL together, NULL or zero-length sd), ENOENT, ELOOP.

Path flags belong to the operation that receives them. A no-follow file open and a no-follow security query have different purposes: the query can select the terminal link's descriptor. Do not infer one operation's behavior from another. Use an owned handle when the application needs to avoid a second path lookup.

5.3.2 By fd #

ssize_t peios_fd_get_sd(int fd, uint32_t secinfo, void *buf, size_t cap);
int     peios_fd_set_sd(int fd, uint32_t secinfo, const void *sd, size_t len);

The same operations against the object fd already refers to. The access check they perform depends on the fd type: a normal file fd is checked against its cached granted mask (the one baked in at open), while an O_PATH, pidfd, or token fd triggers a live check. That distinction — cached for the fixed-grant file fd, live for the others — is documented in the Peios Kernel TRM §3.9, FACS; the practical upshot is that a file fd already opened with the right access can get/set its SD without a second path resolution.

The required rights and errors match the by-path calls, minus the path-resolution failures (ENOENT/ELOOP), plus EBADF (bad fd).

5.3.3 By IPC kind and ID #

ssize_t peios_sysv_get_sd(uint32_t kind, int id, uint32_t secinfo,
                          void *buf, size_t cap);
int     peios_sysv_set_sd(uint32_t kind, int id, uint32_t secinfo,
                          const void *sd, size_t len);

System V message queues, shared memory segments, and semaphore arrays carry security descriptors too (Peios Kernel TRM §3.11), but have neither a path nor an fd. kind is one of KACS_SD_AT_SYSV_SHM, KACS_SD_AT_SYSV_MSG or KACS_SD_AT_SYSV_SEM from <pkm/ipc.h>, and id is what shmget, msgget or semget returned. The object is looked up in the caller's IPC namespace and the check is always live against its descriptor: READ_CONTROL (or ACCESS_SYSTEM_SECURITY for the SACL) to read, WRITE_DAC / WRITE_OWNER to write, with the same preserve-unselected-components merge as the file calls. Errors as for the by-fd calls, with EINVAL for an id that names nothing and EIDRM for an object that has been removed.

5.4 Mount Policy

Peios / Developing for Peios / SDK Reference / file.h — File Security

Not every filesystem can store native security descriptors. The mount policy governs how KACS treats a superblock that has no native SD storage — whether files there get a synthesised SD, a template SD, or are denied. These calls target the superblock the object fd lives on. At the pinned kernel revision below, both require enabled SeManageVolumePrivilege or SeTcbPrivilege, with successful privilege-use marking.

Important

The gate is verified in kernel 8e0e22de3a59cad506bbbf8873de456e16ad272d, for both reads and writes. The libpeios 0.5.8 wrappers at de0018bdcaed14abb796aeccec9c8387fd30e452 pass through to those syscalls; their TCB-only comments do not enforce an additional privilege gate. No runtime test or release boundary is established here. See operator policy-access checks before changing privileges.

struct peios_mount_policy {
    uint32_t    policy;      /* KACS_MOUNT_POLICY_* */
    uint32_t    flags;
    uint32_t    generation;
    const void *template_sd;
    size_t      template_sd_len;
};

int peios_mount_get_policy(int fd, struct peios_mount_policy *out,
                           void *tmpl_buf, size_t tmpl_cap);
int peios_mount_set_policy(int fd, const struct peios_mount_policy *p);
  • peios_mount_get_policy reads the policy for fd's superblock into out. The template SD is returned into your tmpl_buf getxattr-style: on success out->template_sd points into tmpl_buf when that buffer was large enough, or is NULL if the superblock has no template. A NULL template buffer (or tmpl_cap == 0) is valid only when you don't need the template bytes. A too-small template buffer is not an error — the call still succeeds, reports the true length in out->template_sd_len, and leaves out->template_sd NULL so you can size a retry. Errors: EPERM (neither accepted privilege enabled, or privilege-use marking failed), EBADF (bad fd), EINVAL (NULL out, or NULL tmpl_buf with non-zero tmpl_cap), EFAULT (bad buffer pointer), ENOMEM (allocation failed).
  • peios_mount_set_policy installs p as the superblock's policy. policy is a KACS_MOUNT_POLICY_* value; template_sd/template_sd_len supply the template SD when the policy calls for one. flags and generation must be zero on set — the kernel manages the generation counter itself and rejects a non-zero input. Errors: EPERM (neither accepted privilege enabled, or privilege-use marking failed), EINVAL (unknown or unmanaged policy, non-zero flags/generation, malformed or oversized template, NULL template with non-zero length), EOPNOTSUPP (superblock not KACS-managed), EBADF (bad fd), EFAULT (bad pointer).

5.5 The Generic Mapping

Peios / Developing for Peios / SDK Reference / file.h — File Security

extern const struct kacs_generic_mapping peios_file_generic_mapping;

The canonical generic→specific rights mapping for the file object class. Pass it to peios_access_map_generic, or as the mapping in a peios_access_request when checking access against a file's SD — for example to pre-flight whether a caller could open a file before you actually open it.

5.6 Working through a Handle

Peios / Developing for Peios / SDK Reference / file.h — File Security

These calls act on the file an open descriptor refers to, rather than on a name. Each is authorized by the access the descriptor was granted when it opened, so they work on the file you opened even if someone has since renamed it, and they cannot hit a different file that has taken the old name. They need a descriptor from peios_file_open; any other descriptor fails with EOPNOTSUPP.

5.6.1 Reading back the grant #

int peios_file_query_open(int fd, struct kacs_open_info *out);

Fills out from the open:

FieldMeaning
granted_accessThe access mask the descriptor carries. After a MAXIMUM_ALLOWED open, this is what you received.
share_accessThe KACS_FILE_SHARE_* sharing the open allows others.
flagsKACS_OPEN_INFO_MANAGED; _DELETE_PENDING if the file is marked for deletion; _DELETE_ON_CLOSE if this open will mark it when it closes; _ANCESTORS_PINNED if the open pins its parent directories.

The call needs no right: it reports only what the descriptor already carries.

5.6.2 Deleting through the handle #

int peios_file_set_disposition(int fd, uint32_t flags);

Sets the file's delete disposition — what happens to it once nothing has it open. The open needs DELETE, or the call fails with EACCES. The flags are those of NT's FILE_DISPOSITION_INFORMATION_EX:

FlagMeaning
KACS_DISPOSITION_DELETEMark the file delete-pending: it is removed when its last open closes, from whichever process. Without this flag, the call clears the mark.
KACS_DISPOSITION_POSIX_SEMANTICSWith DELETE: remove the name now, as unlink(2) does. Open descriptors carry on with the file.
KACS_DISPOSITION_ON_CLOSESet or clear this open's own delete-on-close instead: the file becomes delete-pending when this open closes.
KACS_DISPOSITION_IGNORE_READONLYDelete a read-only file. Needs FILE_WRITE_ATTRIBUTES too.

While a file is delete-pending its name stays and still lists, but every new open of it fails with EBUSY and the status KACS_STATUS_DELETE_PENDING. The removal is authorized by whoever set the mark, not by whoever closes the file last.

A read-only file fails with EPERM unless KACS_DISPOSITION_IGNORE_READONLY is given. A directory has to be empty when it is removed.

/* Delete the file once everyone has finished with it. */
if (peios_file_set_disposition(fd, KACS_DISPOSITION_DELETE) != 0) { /* errno */ }
close(fd);

5.6.3 Renaming through the handle #

int peios_file_rename(int fd, int newdirfd, const char *newpath, uint32_t flags);

Moves the link fd names to newpath, resolved relative to newdirfd as by renameat2(). The open needs DELETE; the destination directory is checked as for any rename. The flags are those of NT's FILE_RENAME_INFORMATION_EX:

FlagMeaning
KACS_RENAME_REPLACE_IF_EXISTSReplace an existing file at newpath. Without it, an existing name fails with EEXIST.
KACS_RENAME_POSIX_SEMANTICSReplace a file that is open, if all its opens share delete.
KACS_RENAME_IGNORE_READONLYReplace a read-only file.

A directory is never replaced. A file that is open, delete-pending, or read-only without the flag fails with EBUSY or EPERM. If the handle's link has been removed, the call fails with ENOENT. Both names have to be on the same mount, or the call fails with EXDEV.

5.6.4 See also #

  • Sharing and Deletion — the kernel's rules for delete-pending files and renaming through a handle.

5.7 Locks and Leases

Peios / Developing for Peios / SDK Reference / file.h — File Security

5.7.1 Byte-range locks #

int peios_file_lock(int fd, uint32_t op, uint64_t offset, uint64_t length,
                    uint32_t flags, uint64_t cookie);

An NT byte-range lock reserves part of a file for one open. Unlike Linux's fcntl and flock locks, which programs can ignore, these are enforced: a read or write that conflicts with another open's lock fails with EAGAIN, whichever program issued it.

op is one of:

OperationMeaning
KACS_LOCK_EXCLUSIVEKeep every other open from reading or writing length bytes from offset.
KACS_LOCK_SHAREDKeep everyone, this open included, from writing the range.
KACS_LOCK_UNLOCKRelease a lock this open holds on exactly that range; ENOLCK if it holds none.
KACS_LOCK_CANCELCancel the waiting request named by cookie.

A conflicting request waits for the range to come free, unless flags carries KACS_LOCK_FAIL_IMMEDIATELY, when it fails with EAGAIN. Give a waiting request a cookie so that another thread can cancel it. Locks are released when the open closes.

A lock blocks other opens' reads and writes only if the open that took it could write the file. A reader's lock still conflicts with other locks, so cooperating readers can coordinate, but it cannot stop anyone's I/O. Memory mappings are not covered.

5.7.2 Leases #

A lease lets a program cache a file — its contents, its pending writes, or an open handle to it — while nobody else needs it. When another operation would make the cached state wrong, the kernel breaks the lease: it tells the holder to flush and give up some of its state, and the operation waits until the holder acknowledges. A file server holds leases for its clients and relays the breaks to them.

int     peios_lease_manager_create(uint32_t flags, uint32_t timeout_ms);
int     peios_file_lease(int fd, int manager_fd, const uint8_t key[16],
                         uint32_t *state, uint32_t flags);
ssize_t peios_lease_manager_read(int manager_fd, struct kacs_lease_break *out, size_t count);

A lease manager is a descriptor that receives the break notices for the leases held under it. flags takes KACS_LEASE_MANAGER_CLOEXEC and _NONBLOCK. timeout_ms bounds how long a break waits for acknowledgment before the kernel completes it itself; zero gives the default of 35 seconds.

peios_file_lease requests a lease on fd's file, held under the manager and a 16-byte key that identifies the holder. *state is the state asked for — any of KACS_LEASE_READ, _WRITE, and _HANDLE — and on return the state granted, which can be less. Opens made with the same manager and key, through KACS_OPEN_LEASE_KEY, do not break it.

peios_lease_manager_read reads up to count break notices and returns how many it read. Each names the lease by key, file, current state and the state it is being broken to, with the reason (KACS_LEASE_BREAK_*) and an epoch that counts the lease's breaks. Notices are never dropped, and the manager descriptor is pollable. Answer a notice with peios_file_lease, flags = KACS_LEASE_ACKNOWLEDGE, and a state no greater than the notice's new state, through an open of the same file under the same key; the waiting operation then proceeds.

5.7.3 See also #

  • Byte-Range Locks and Leases — the kernel's rules, including what breaks a lease.

5.8 Special Attributes

Peios / Developing for Peios / SDK Reference / file.h — File Security

KACS keeps two attributes for every file on a managed mount:

  • Read-only. A read-only regular file cannot be opened for writing or deleted, by anyone, its owner included, until the flag is cleared.
  • Created At, a settable creation date. It differs from the filesystem's birth time, which statx reports and nobody can set: Created At is the date a person sees, which a copy or a restore can carry across.
int peios_file_get_sattr(int dirfd, const char *path, struct kacs_sattr *out, uint32_t at_flags);
int peios_file_set_sattr(int dirfd, const char *path, const struct kacs_sattr *attrs,
                         uint32_t at_flags);
int peios_fd_get_sattr(int fd, struct kacs_sattr *out);
int peios_fd_set_sattr(int fd, const struct kacs_sattr *attrs);

struct kacs_sattr holds both:

FieldMeaning
versionKACS_SATTR_VERSION.
validOn a write, which fields to change: KACS_SATTR_VALID_ATTRIBUTES, KACS_SATTR_VALID_CREATED_AT. A read sets both.
attributesKACS_SATTR_READONLY.
flagsKACS_SATTR_CREATED_AT_SET if Created At is set.
created_at_sec, created_at_nsecCreated At, since the Unix epoch.

A read always fills the struct: a file that has never had either attribute set reads as not read-only with no Created At. A write changes only the fields its valid mask names, so two programs changing different attributes cannot undo each other. The struct means the same in both directions: a write with KACS_SATTR_VALID_CREATED_AT sets Created At if flags carries KACS_SATTR_CREATED_AT_SET, and unsets it if not. A struct read from one file can therefore be written to another to copy both attributes exactly.

Reading needs FILE_READ_ATTRIBUTES and writing FILE_WRITE_ATTRIBUTES: through the descriptor's grant for the fd forms, or a live check for the path forms. at_flags accepts AT_SYMLINK_NOFOLLOW.

/* Make a file read-only, leaving its Created At alone. */
struct kacs_sattr a = {
    .version    = KACS_SATTR_VERSION,
    .valid      = KACS_SATTR_VALID_ATTRIBUTES,
    .attributes = KACS_SATTR_READONLY,
};
if (peios_file_set_sattr(AT_FDCWD, "contract.pdf", &a, 0) != 0) { /* errno */ }

5.8.1 The creation date #

int peios_file_creation_time(int dirfd, const char *path, int64_t *sec, uint32_t *nsec,
                             uint32_t at_flags);
int peios_fd_creation_time(int fd, int64_t *sec, uint32_t *nsec);

A file's creation date is its Created At while that is set, and its birth time otherwise. These calls apply that rule, so a program showing or copying a creation date does not have to. They fail with ENODATA if the file has neither, as on a filesystem that records no birth time.

A tool that copies files and wants the copy to keep its creation date should read it with peios_file_creation_time and set it on the copy as Created At.

5.8.2 See also #

  • Special Attributes — the kernel's rules, including what read-only refuses.

6.1 Process Security

Peios / Developing for Peios / SDK Reference / process.h — Process Security

<peios/process.h> is the process-security surface of KACS. Today it is a small module with two jobs: turning on process mitigations — the hardening controls that live on a process's security block (PSB) — and reading a process's PSB back. More process-security surface will land here as it appears.

The mitigation bits are the KACS_MIT_* flags from <pkm/psb.h> (KACS_MIT_WXP through KACS_MIT_SML, with KACS_MIT_ALL as the mask of all valid bits). KACS_MIT_CFI is a legacy alias that expands to KACS_MIT_CFIF | KACS_MIT_CFIB. The full catalog and semantics are in the Peios Kernel TRM §3.3, the Process Security Block.

6.1.1 Setting mitigations #

int peios_process_set_mitigations(int pidfd, uint32_t mitigations);

Turns on the mitigation bits named in mitigations (a mask of KACS_MIT_*). Returns 0 on success, or -1 with errno.

Three properties define how this call behaves, and each matters:

  • It is one-way. Mitigation bits can only be set, never cleared. Once a protection is on, it stays on for the life of the process. This is deliberate — a mitigation you could turn off is a mitigation an attacker could turn off — so treat each call as a permanent, additive commitment.
  • It targets a process by pidfd. pidfd == -1 targets the calling process, which is the common case: a program hardens itself early in startup. Targeting another process requires PROCESS_SET_INFORMATION on it plus PIP dominance over it — you cannot harden (or interfere with) a process you don't already dominate.
  • It is activation-backed and fails closed. If a requested protection cannot actually be activated, the call fails without mutating anything — you never end up believing a mitigation is on when it isn't. Either every requested bit is activated and the call succeeds, or nothing changes and it returns -1.
/* Harden the current process: enforce W^X and speculation mitigation lock, refuse to
   proceed if either can't be activated. */
if (peios_process_set_mitigations(-1, KACS_MIT_WXP | KACS_MIT_SML) != 0) {
    perror("set_mitigations");
    /* nothing was changed; decide whether to continue unhardened or abort */
}

Because the call is all-or-nothing, request the bits you require together and check the result once: a success means the whole set is active, a failure means none of this call's bits were applied (bits set by earlier successful calls remain on).

6.1.2 Reading a PSB #

struct peios_psb {
    uint32_t pip_type;         /* 0 none, 512 Protected */
    uint32_t pip_trust;        /* 8192 PeiosTcb */
    uint32_t mitigations;      /* committed KACS_MIT_* bits */
    uint8_t  process_guid[16];
};

int peios_process_psb(int pid, struct peios_psb *out);

Reads process pid's PSB, from /proc/<pid>/psb, into *out. pid <= 0 reads your own. Returns 0, or -1 with errno.

  • Your own is always readable.
  • Another process's needs PROCESS_QUERY_LIMITED on its descriptor — which the default process descriptor gives Everyone — and not PIP dominance. A protected process's PIP type and trust are therefore readable when nothing else about it is, which is what lets a tool explain why it cannot see more.

mitigations is the committed set: bits a call asked for but could not activate are not in it, and neither is the KACS_MIT_CFI alias. process_guid identifies the process for its whole life, unlike its pid, and is what events carry.

Errors: ENOENT (no such process, or it has exited), EACCES (refused), EPROTO (a line this library cannot read), EINVAL (NULL out).

struct peios_psb psb;
if (peios_process_psb(pid, &psb) == 0 && psb.pip_type != 0)
    printf("%d is protected (trust %u)\n", pid, psb.pip_trust);

6.1.3 See also #

  • <peios/token.h> — Token identity is separate from the caller's PSB-derived PIP. Process targeting can require both identity-based rights and PIP dominance.
  • Process mitigations — the operator-side account of each mitigation and what it defends against.

7.1 The Registry (LCS)

Peios / Developing for Peios / SDK Reference / registry.h — the Registry

<peios/registry.h> is the client surface of LCS — the Layered Configuration Subsystem, Peios's kernel-mediated registry. LCS is modeled on the Windows registry: a hierarchy of keys (each with an immutable GUID identity and secured by its own KACS security descriptor) holding typed values. Its distinguishing feature is layers: every write is tagged with a precedence-ordered layer, and the effective view of a value resolves to the highest-precedence entry. That is what lets a base configuration, a site overlay, and a machine-local override coexist on one key and resolve deterministically.

This header is the registry client: open keys, read and write values, enumerate, watch, secure, back up, and run transactions. It does not cover the registry source (the storage backend) side — REG_SRC_REGISTER and the RSI framed protocol — which is a separate library, librsi. A client speaks only the syscalls and ioctls here.

Handles are fds. Three calls create file descriptors — peios_reg_open_key, peios_reg_create_key, and peios_reg_begin_transaction; everything else is an operation on a key fd or transaction fd, gated on the access right granted when the key was opened. The wire constants — value types (REG_SZ … REG_QWORD), key access rights (KEY_*), open/create flags, transaction states (REG_TXN_*), watch filters (REG_NOTIFY_*), and security-info bits — come from <pkm/lcs.h>.

7.1.1 See also #

  • <peios/security.h> — building and parsing the SDs that secure keys.
  • Library conventions — the base error and buffer rules the descriptor reads specialize.
  • The registry — the operator-side model of layers, hives, and precedence.

7.2 The Buffer Convention Here

Peios / Developing for Peios / SDK Reference / registry.h — the Registry

Most of libpeios returns variable-length data with an ssize_t and the two-call protocol. The registry's reads use the same idea but express it through descriptor structs rather than a return value, because a single read often fills more than one buffer (a value's data and its layer name, say). The pattern:

  • Each read takes a descriptor struct with *_cap fields (in) and *_len fields (out), plus buffer pointers.
  • On success it returns 0 and writes the actual length into each *_len.
  • If a buffer is too small it returns -1 with errno == ERANGE and writes the required length into the matching *_len — so a zero-capacity buffer probes the size.
  • A NULL buffer is valid only with zero capacity; NULL with a nonzero capacity is EINVAL.
  • For a read with two buffers, ERANGE is returned if either is too small, and both required lengths are reported, so one probe sizes everything.

Everything else follows the usual Linux convention: 0 / -1 + errno.

7.3 Opening and Creating Keys

Peios / Developing for Peios / SDK Reference / registry.h — the Registry

int peios_reg_open_key(int parent_fd, const char *path, uint32_t desired_access,
                       uint32_t flags);
int peios_reg_create_key(int parent_fd, const char *path, uint32_t desired_access,
                         uint32_t flags, const char *layer, int txn_fd,
                         uint32_t *disposition_out);

Both resolve path (NUL-terminated) against parent_fd — a key fd for a relative path, or < 0 for an absolute path — and return a key fd whose granted access mask is fixed for its lifetime (like a file fd, so it can be delegated). desired_access is the requested KEY_* rights, checked against the key's SD.

  • peios_reg_open_key opens an existing key. flags can be REG_OPEN_LINK to open a symlink key itself rather than following it. Errors: ENOENT, EACCES, EINVAL, ELOOP, ENAMETOOLONG, ETIMEDOUT, EIO, ENOMEM.
  • peios_reg_create_key opens an existing key or creates a new one. flags can combine REG_OPTION_VOLATILE (a key that does not survive reboot) and REG_OPTION_CREATE_LINK (create a symlink key). layer names the target layer to create in (NUL-terminated), or NULL for the base layer. txn_fd enlists the create in a transaction, or -1 to auto-commit. disposition_out, if non-NULL, receives REG_CREATED_NEW or REG_OPENED_EXISTING. Errors add ENOSPC and EPERM (privileged symlink creation) to the set above.

7.4 Values

Peios / Developing for Peios / SDK Reference / registry.h — the Registry

A value is named (length-counted; an empty name is the key's default value), typed (REG_*), and written into a layer. A base-layer target is layer == NULL with layer_len == 0; a non-NULL pointer with a zero length is rejected EINVAL.

7.4.1 Reading a value #

struct peios_reg_value {
    uint64_t sequence;  /* out: effective entry's sequence number */
    void    *data;      /* in:  buffer for the value data (NULL to probe) */
    void    *layer;     /* in:  buffer for the layer name (NULL to probe/skip) */
    uint32_t type;      /* out: value type (REG_*) */
    uint32_t data_cap;  /* in */   uint32_t data_len;  /* out: actual/required */
    uint32_t layer_cap; /* in */   uint32_t layer_len; /* out: actual/required */
};

int peios_reg_query_value(int key_fd, const void *name, uint32_t name_len, int txn_fd,
                          struct peios_reg_value *v);

peios_reg_query_value reads the effective value name on key_fd — the winner of the layer precedence resolution. name_len == 0 reads the default value; txn_fd reads within a transaction, or -1 for none. It fills v->data with the value bytes and v->layer with the name of the layer that won, and reports the resolved type and sequence. Pass a NULL layer buffer if you don't care which layer won. Errors: ENOENT (no effective value, or a tombstone masks it), ERANGE, EACCES, EINVAL.

7.4.2 Writing, deleting, tombstoning #

int peios_reg_set_value(int key_fd, const void *name, uint32_t name_len, uint32_t type,
                        const void *data, uint32_t data_len, const void *layer,
                        uint32_t layer_len, int txn_fd, uint64_t expected_seq);
int peios_reg_delete_value(int key_fd, const void *name, uint32_t name_len,
                           const void *layer, uint32_t layer_len, int txn_fd);
int peios_reg_blanket_tombstone(int key_fd, const void *layer, uint32_t layer_len,
                                int set, int txn_fd);
  • peios_reg_set_value writes value name of type into a specific layer (NULL/0 = base). type can be REG_TOMBSTONE to place a per-value tombstone that masks lower layers. expected_seq is a compare-and-swap guard: 0 disables it; otherwise the write applies only if the value's current sequence matches, else EAGAIN. This is how you do lost-update-safe read-modify-write — read the sequence from peios_reg_query_value, then set with expected_seq set to it. Errors: EINVAL, EAGAIN, ENOSPC, ENAMETOOLONG, EPERM, EACCES.
  • peios_reg_delete_value removes a layer's entry for name (NULL/0 = base). It is idempotent, and removing a layer's entry lets any lower-layer value re-emerge — deletion is per-layer, not global.
  • peios_reg_blanket_tombstone sets (set != 0) or clears (set == 0) a blanket tombstone on a layer, masking all lower-precedence values of this key on that layer at once — the wholesale version of a per-value tombstone. set must be 0 or 1 (else EINVAL).

7.4.3 Enumerating values #

int peios_reg_query_values_batch(int key_fd, int txn_fd, void *buf, uint32_t cap,
                                 uint32_t *len_out, uint32_t *count_out);

struct peios_reg_enum_value {
    void    *name;      /* in:  buffer for the value name (NULL to probe) */
    void    *data;      /* in:  buffer for the value data (NULL to probe) */
    uint32_t type;      /* out */
    uint32_t name_cap;  /* in */  uint32_t name_len;  /* out: actual/required */
    uint32_t data_cap;  /* in */  uint32_t data_len;  /* out: actual/required */
};
int peios_reg_enum_value(int key_fd, uint32_t index, int txn_fd,
                         struct peios_reg_enum_value *v);

Two ways to read every effective value of a key:

  • peios_reg_query_values_batch reads them all into one buf in a single call — the efficient path. Each record is packed little-endian, back to back: [name_len: u32][name][type: u32][data_len: u32][data], for count records. len_out receives the bytes written (or the required size on ERANGE); count_out receives the record count. Both can be NULL.
  • peios_reg_enum_value reads one value at a time by index, dense over the key's tombstone-resolved values — walk from 0 until ENOENT. Use it when you want to process values incrementally rather than buffer them all.

7.5 Subkeys, Metadata, and Watches

Peios / Developing for Peios / SDK Reference / registry.h — the Registry

7.5.1 Enumerating subkeys #

struct peios_reg_subkey {
    void    *name;             /* in:  buffer for the child's name (NULL to probe) */
    uint64_t last_write_time;  /* out: ns since the Unix epoch */
    uint32_t name_cap;         /* in */  uint32_t name_len;    /* out */
    uint32_t subkey_count;     /* out: the child's subkey count */
    uint32_t value_count;      /* out: the child's value count */
};
int peios_reg_enum_subkey(int key_fd, uint32_t index, int txn_fd,
                          struct peios_reg_subkey *v);

peios_reg_enum_subkey reads the child key at index, dense over visible children — walk from 0 until ENOENT. There is no per-child access check during enumeration (you see the names and counts; opening a child still checks its SD).

7.5.2 Key metadata #

struct peios_reg_key_info {
    void    *name;                 /* in:  buffer for the key's leaf name (NULL to probe) */
    uint64_t last_write_time;      /* out */
    uint64_t hive_generation;      /* out: per-hive change epoch */
    uint32_t name_cap;  uint32_t name_len;
    uint32_t subkey_count;         /* out */
    uint32_t value_count;          /* out */
    uint32_t max_subkey_name_len;  /* out */
    uint32_t max_value_name_len;   /* out */
    uint32_t max_value_data_size;  /* out */
    uint32_t sd_size;              /* out: security-descriptor size */
    uint8_t  volatile_key;         /* out: 1 if volatile */
    uint8_t  symlink;              /* out: 1 if a symlink */
};
int peios_reg_query_key_info(int key_fd, struct peios_reg_key_info *v);

peios_reg_query_key_info reads the key's leaf name and its metadata (needs READ_CONTROL). Note the ordering wrinkle: the kernel reports the metadata only once the name fits, so a too-small (or zero-capacity) name buffer returns ERANGE with the required name_len and no metadata — size the name buffer from that, then call again to get everything. The max_* fields are sizing hints for enumerations; hive_generation is a per-hive change epoch you can watch to detect that anything under the hive changed.

7.5.3 Deleting and hiding keys #

int peios_reg_delete_key(int key_fd, const void *layer, uint32_t layer_len, int txn_fd);
int peios_reg_hide_key(int key_fd, const void *layer, uint32_t layer_len, int txn_fd);

Both need DELETE access, take a layer (NULL/0 = base) and an optional txn_fd, and cannot target a hive root (EINVAL).

  • peios_reg_delete_key removes this key's path entry in a layer; lower-layer entries re-emerge. It fails with ENOTEMPTY if the key has visible children.
  • peios_reg_hide_key creates a HIDDEN path entry that masks the key in a layer; removing that layer makes the key reappear. This is the key-level analogue of a tombstone — hide rather than destroy.

7.5.4 Watching for changes #

int peios_reg_notify(int key_fd, uint32_t filter, int subtree);
int peios_reg_flush(int key_fd);
  • peios_reg_notify arms change watches on key_fd (needs KEY_NOTIFY). filter is a mask of REG_NOTIFY_VALUE / REG_NOTIFY_SUBKEY / REG_NOTIFY_SD (or REG_NOTIFY_ALL); subtree (0/1) extends the watch to descendants. filter == 0 disarms. Once armed, the key fd itself becomes pollable — EPOLLIN signals pending events, and read() on the fd returns the change records. So a watch integrates directly into an epoll loop with no side channel. Errors: ENOENT (orphaned key), EINVAL, EACCES.
  • peios_reg_flush forces the source to persist this key's hive's pending writes (needs KEY_SET_VALUE) and returns once persistence is confirmed — the durability barrier.

The change records. A read() on an armed key fd returns as many complete records as fit in your buffer — records are never split across reads. If the buffer is too small for even the next record the read fails EINVAL (so size it generously — a few KiB), and a non-blocking fd with nothing pending fails EAGAIN. Each record is a little-endian, possibly unaligned byte stream (Peios Kernel TRM §5.6, Watches, with the header offsets in §5.A):

OffsetSizeFieldMeaning
04total_lenRecord size in bytes — advance by this to the next record (future versions can append fields).
42event_typeREG_WATCH_VALUE_SET / _VALUE_DELETED / _SUBKEY_CREATED / _SUBKEY_DELETED / _SD_CHANGED / _KEY_DELETED / _OVERFLOW.
62name_lenByte length of name; 0 for the no-name events (SD_CHANGED, KEY_DELETED, OVERFLOW).
8name_lennameThe changed value or subkey name (UTF-8, not NUL-terminated).

A subtree watch appends two further fields after name: path_depth (u16) and that many length-prefixed path components (u16 length + UTF-8 bytes), locating the changed key relative to the watched key — depth 0 means the watched key itself.

Delivery is best-effort with an overflow fallback: if records accumulate faster than you read them, the oldest are dropped and a REG_WATCH_OVERFLOW record is queued — on seeing one, re-read the watched key (and subtree) to recover current state rather than trusting the stream. Records describe effective (layer-resolved) changes, and uncommitted transactions produce none — events fire at commit.

7.6 Key Security Descriptors

Peios / Developing for Peios / SDK Reference / registry.h — the Registry

int peios_reg_get_security(int key_fd, uint32_t security_info, void *sd, uint32_t cap,
                           uint32_t *sd_len_out);
int peios_reg_set_security(int key_fd, uint32_t security_info, const void *sd,
                           uint32_t sd_len, int txn_fd);

Keys are KACS-secured, so their SDs are read and written with the same <peios/security.h> vocabulary as files and tokens; security_info selects components (owner/group/DACL/SACL).

  • peios_reg_get_security reads the selected components into sd (KACS binary form), writing the length to *sd_len_out (can be NULL); a too-small buffer returns ERANGE with the required size there, and a zero cap probes. Owner/group/DACL need READ_CONTROL; the SACL needs ACCESS_SYSTEM_SECURITY.
  • peios_reg_set_security applies the selected components of sd, merging with the rest (the kernel parses and validates). The DACL needs WRITE_DAC, the owner WRITE_OWNER, the SACL ACCESS_SYSTEM_SECURITY. Here txn_fd gives atomicity, not layer qualification (SDs are not layered), or -1 to apply immediately. SD changes affect only future opens — handles already open keep their fixed grant.

7.7 Backup and Restore

Peios / Developing for Peios / SDK Reference / registry.h — the Registry

int peios_reg_backup(int key_fd, int output_fd);
int peios_reg_restore(int key_fd, int input_fd);
  • peios_reg_backup exports the key and its entire subtree to output_fd (needs SeBackupPrivilege). It takes a read-only snapshot and performs no per-key access check — the privilege is the gate. Errors: EPERM/EACCES, EBADF (output not writable), ENOENT, ENOTSUP, EBUSY.
  • peios_reg_restore replaces the key and its entire subtree from input_fd (needs SeRestorePrivilege), applied in one transaction. Errors: EPERM/EACCES, EBADF (input not readable), EINVAL (malformed stream), EEXIST (GUID collision), EOVERFLOW.

7.8 Transactions

Peios / Developing for Peios / SDK Reference / registry.h — the Registry

A transaction batches key creates and mutating value/key operations into an atomic unit.

int peios_reg_begin_transaction(void);
int peios_reg_begin_read_transaction(void);
int peios_reg_commit(int txn_fd);
int peios_reg_txn_status(int txn_fd, uint32_t *state_out, int *terminal_errno_out);
  • peios_reg_begin_transaction starts one and returns a transaction fd (initially unbound; it binds to a source on first use), or -1/ENOMEM. Pass this fd as the txn_fd argument to the create and mutating calls to enlist them. Closing the fd without committing aborts the transaction — so a transaction is abort-by-default, which makes error paths safe.
  • peios_reg_commit atomically applies everything enlisted. On success the fd is terminal — close it. Errors tell you what to do: EINVAL (already committed / never bound), EBUSY (write-lock contention — the transaction stays active, retry the commit), EIO (source failure — stays active), ETIMEDOUT.
  • peios_reg_txn_status reads a transaction's state: state_out receives the REG_TXN_* state, and terminal_errno_out receives the errno that ended it (0 while active or after a clean commit). Both can be NULL.

The lifecycle: begin → enlist operations by passing txn_fd → commit (retry on EBUSY/EIO) → close, or close to abort.

peios_reg_begin_read_transaction instead begins a read-only snapshot. The first read binds one hive and fixes data and layer selection. Reads and enumeration accept its fd directly; key opening, metadata, and security reads use their _transacted forms. Mutations fail EROFS. A capture race returns EAGAIN; repeat the complete read with a fresh transaction. Closing releases it. Normal transaction timeouts and read-only source quotas apply.

8.1 Events (KMES)

Peios / Developing for Peios / SDK Reference / event.h — Events

<peios/event.h> is the client surface of KMES — Peios's sole event path. The kernel stamps every event with trusted metadata (timestamp, per-CPU sequence, CPU id, identity GUIDs) and writes it into a per-CPU lock-free ring buffer. There is no other way to emit or observe events: audit records, subsystem events, and your own application events all flow through the same rings. Producers emit; consumers attach to the rings and drain them.

Each event payload is a single MessagePack value — build and parse it with <peios/msgpack.h>.

Two privileges gate the module: emitting requires SeAuditPrivilege, and consuming (attaching to a ring) requires SeSecurityPrivilege.

8.1.1 See also #

  • <peios/msgpack.h> — building and parsing the payloads events carry.
  • Auditing — the operator-side view of the event and audit stream.

8.2 Emitting Events

Peios / Developing for Peios / SDK Reference / event.h — Events

int peios_event_emit(const char *event_type, uint16_t event_type_len,
                     const void *payload, uint32_t payload_len);

Emits a single event. event_type is a length-counted UTF-8 event type such as "org.example.backup.snapshot.created", named as PGSS §6.3 requires — not NUL-terminated, and its length must be non-zero. payload is payload_len bytes of MessagePack (one well-formed value). The kernel validates the payload (one well-formed MessagePack value within the configured size and nesting limits) and stamps origin_class = userspace. Returns 0, or -1 with errno:

errnoCause
EPERMNo SeAuditPrivilege.
EINVALZero-length type, or a malformed payload.
ENOSPCPayload exceeds the size caps.
EAGAINRate-limited.
EFAULTBad pointer.

Since the kernel's payload check matches peios_mp_validate, you can validate in userspace first and turn a would-be EINVAL into a check you control.

/* Build a payload, then emit. */
peios_mp_writer *w = peios_mp_writer_new();
peios_mp_write_map(w, 1);                      /* {outcome: {success: true}} */
peios_mp_write_str(w, "outcome", 7);
peios_mp_write_map(w, 1);
peios_mp_write_str(w, "success", 7); peios_mp_write_bool(w, true);

static const char type[] = "org.example.backup.snapshot.created";
const void *buf; ssize_t n = peios_mp_writer_bytes(w, &buf);
if (n >= 0)
    peios_event_emit(type, sizeof type - 1, buf, (uint32_t)n);
peios_mp_writer_free(w);

8.2.1 The emission policy #

#define PEIOS_EVENT_TIER_ESSENTIAL 0u
#define PEIOS_EVENT_TIER_STANDARD  1u
#define PEIOS_EVENT_TIER_VERBOSE   2u
#define PEIOS_EVENT_TIER_DEBUG     3u

typedef struct peios_event_policy peios_event_policy;

peios_event_policy *peios_event_policy_open(void);
void peios_event_policy_close(peios_event_policy *policy);
int  peios_event_policy_enabled(peios_event_policy *policy, const char *event_type,
                                uint16_t event_type_len, uint32_t tier);

An emitter must not write an event whose type the emission policy has switched off (PGSS §6.9), and should find that out before it builds the payload. peios_event_policy_enabled answers it: 1 means build and emit, 0 means build nothing. tier is the tier the type declares in its fragment. An essential type is always 1, without reading anything.

peios_event_emit does not check the policy itself. By the time it is called the payload is built, and skipping that work is the point of asking.

The handle caches each type's answer and watches Machine\Generic\Events, so a change an administrator commits applies to your next decision. If that key does not exist yet, it watches for its creation; if nothing can be watched, it reads the policy again at least once a second. If the registry cannot be read at all, the answer is the tier's default: on for standard, off for verbose and debug.

peios_event_policy_open fails only with ENOMEM; it does not need the registry to be there. peios_event_policy_enabled returns -1 with EINVAL only for caller error: a NULL handle or type, a malformed type (empty, not UTF-8, an empty segment, or a \, / or NUL in a segment), or an unknown tier. Registry failures never make it fail.

Use a handle from one thread at a time, and don't use it across fork(): the child shares the parent's watch descriptor and would take the parent's notifications. A child opens its own handle.

8.2.2 Batch emit #

struct peios_event_entry {
    const char *event_type;      /* length-counted UTF-8; not NUL-terminated */
    uint16_t    event_type_len;
    const void *payload;         /* MessagePack bytes */
    uint32_t    payload_len;
};

int peios_event_emit_batch(const struct peios_event_entry *entries,
                           uint32_t count, uint32_t *emitted_out);

peios_event_emit_batch emits several events in one call, amortising the per-call overhead — a single timestamp capture, identity capture, and consumer wake cover the whole batch. count is in [1, KMES_BATCH_MAX_ENTRIES]. It returns 0 if all count were emitted, or -1 with the errno of the first entry that failed, with *emitted_out (if non-NULL) set to how many entries preceded the failure — so you know exactly where to resume. Rate-limiting is all-or-nothing here: an EAGAIN emits none of the batch.

8.3 Consuming Events

Peios / Developing for Peios / SDK Reference / event.h — Events

A consumed event is described by struct peios_event. The kernel-stamped header is copied to you by value; the two variable parts point into the ring mapping.

struct peios_event {
    uint64_t timestamp;                  /* ns since the Unix epoch (CLOCK_REALTIME) */
    uint64_t sequence;                   /* per-CPU, per-boot monotonic (gap = lost events) */
    uint16_t cpu_id;
    uint8_t  origin_class;               /* 0 = userspace, 1 = KMES, 2 = KACS, 3 = LCS */
    uint8_t  effective_token_guid[16];
    uint8_t  true_token_guid[16];
    uint8_t  process_guid[16];
    const char *event_type;              /* not NUL-terminated; use event_type_len */
    uint16_t    event_type_len;
    const void *payload;                 /* a MessagePack value */
    uint32_t    payload_len;
};

The trusted metadata is the point of KMES: the timestamp, the identity GUIDs (the effective and true tokens, and the process), and the origin_class are stamped by the kernel and cannot be forged by the emitter. sequence is per-CPU, per-boot monotonic — a gap in it means events were lost (overwritten before you drained them).

Lifetime: The high-level reader in libpeios 0.5.12 and later keeps a private event snapshot until the next read or close. Low-level peios_event_ring_event_at pointers still borrow the ring mapping; callers must copy their data and reject slots overwritten during the copy before interpreting that data.

8.3.1 Attaching to a ring #

int peios_event_attach(uint32_t cpu_id, uint64_t *capacity_out);

The low-level primitive: attach to CPU cpu_id's ring buffer, returning a fd and writing the data-region capacity to *capacity_out. Discover the CPU count by counting up from 0 until peios_event_attach returns -1 with errno == EINVAL. Requires SeSecurityPrivilege (EPERM otherwise). You then mmap the fd through peios_event_ring_map. Most callers should use the high-level reader instead, which does the attach and mmap for you.

8.3.2 The high-level reader #

typedef struct peios_event_reader peios_event_reader;

peios_event_reader *peios_event_reader_open(uint32_t cpu_id);
void                peios_event_reader_close(peios_event_reader *r);
int      peios_event_reader_next(peios_event_reader *r, struct peios_event *out);
int      peios_event_reader_wait(peios_event_reader *r, int timeout_ms);
uint64_t peios_event_reader_lost(const peios_event_reader *r);

The reader owns the attach + mmap and hides the whole lock-free drain — memory barriers, lapping recovery, sequence-gap (lost-event) accounting, buffer resize/generation handling, and the futex wait. You loop next/wait.

  • peios_event_reader_open attaches to cpu_id and maps its ring, ready to drain (NULL with errno on failure). peios_event_reader_close tears it down.
  • peios_event_reader_next fetches the next event into out (non-NULL). Returns 1 (event filled), 0 (none available right now — consider wait), or -1 with errno. The out pointers are valid only until the next call.
  • peios_event_reader_wait blocks until events are available or timeout_ms elapses (negative = forever). Returns 1 (call next), 0 (timeout/interrupted), or -1.
  • peios_event_reader_lost returns the cumulative count of lost events (from sequence gaps) — poll it to monitor whether you're draining fast enough.

The canonical consume loop, per CPU:

peios_event_reader *r = peios_event_reader_open(cpu);
for (;;) {
    struct peios_event ev;
    int rc = peios_event_reader_next(r, &ev);
    if (rc == 1) {
        /* handle ev — copy out event_type/payload before the next call */
    } else if (rc == 0) {
        peios_event_reader_wait(r, -1);   /* sleep until more arrive */
    } else {
        break;                            /* error */
    }
}
peios_event_reader_close(r);

To consume the whole machine, run one reader per CPU (discover the count as above), each typically on its own thread.

8.3.3 The low-level ring #

For callers that want to drive the drain themselves — integrating the rings into a custom event loop, say — the ring API exposes the mapping directly. The accessors apply the correct memory barriers; you own the read position and the empty/lapping/generation checks.

struct peios_event_ring { uint64_t _opaque[4]; };   /* opaque */

int  peios_event_ring_map(int fd, uint64_t capacity, struct peios_event_ring *ring);
void peios_event_ring_unmap(struct peios_event_ring *ring);

uint64_t peios_event_ring_capacity(const struct peios_event_ring *ring);
uint64_t peios_event_ring_write_pos(const struct peios_event_ring *ring);  /* acquire */
uint64_t peios_event_ring_tail_pos(const struct peios_event_ring *ring);   /* acquire */
uint64_t peios_event_ring_generation(const struct peios_event_ring *ring);
void     peios_event_ring_set_need_wake(const struct peios_event_ring *ring, int set);

ssize_t peios_event_ring_event_at(const struct peios_event_ring *ring,
                                  uint64_t read_pos, struct peios_event *out);
int     peios_event_ring_wait(const struct peios_event_ring *ring,
                              uint64_t read_pos, int timeout_ms);
  • peios_event_ring_map maps and validates a ring fd from peios_event_attach; ring must be zeroed or previously unmapped (remapping an active ring fails EBUSY). peios_event_ring_unmap releases it.
  • Positions are free-running byte counters. write_pos is where the producer will write next (acquire-loaded); tail_pos is the oldest still-live byte (advances as the ring laps); an event lives at (read_pos & (capacity - 1)). You drain by walking read_pos from tail_pos toward write_pos. generation changes when the buffer is resized — re-read capacity when it does.
  • peios_event_ring_event_at parses the event at read_pos into out and returns its byte size (advance read_pos by that), or -1 if the slot is corrupt. You must have confirmed read_pos is in [tail_pos, write_pos) first. Pass out == NULL to validate a slot and get its size without borrowing the event_type/payload pointers.
  • Before sleeping, arm the advisory wake flag with peios_event_ring_set_need_wake(ring, 1), then peios_event_ring_wait futex-waits until events past read_pos can be available or timeout_ms elapses (negative = forever): 1 (drain now), 0 (timeout/interrupted), -1.

The low-level loop mirrors the high-level one but with the position bookkeeping in your hands:

uint64_t rp = peios_event_ring_tail_pos(&ring);
for (;;) {
    uint64_t wp = peios_event_ring_write_pos(&ring);
    while (rp < wp) {
        struct peios_event ev;
        ssize_t sz = peios_event_ring_event_at(&ring, rp, &ev);
        if (sz < 0) { /* corrupt slot — resync from tail_pos */ break; }
        /* handle ev */
        rp += (uint64_t)sz;
    }
    peios_event_ring_set_need_wake(&ring, 1);
    peios_event_ring_wait(&ring, rp, -1);
}

Reach for this only when the high-level reader's loop doesn't fit your event model; for almost everything, peios_event_reader_* is the right tool.

9.1 MessagePack Codec

Peios / Developing for Peios / SDK Reference / msgpack.h — Encoding

<peios/msgpack.h> is a small, self-contained MessagePack codec. It exists because KMES event payloads are MessagePack: the kernel only structurally validates a payload on emit — it does not build or interpret it — so userspace owns the encode and decode. This codec is that path, and its validator's acceptance is deliberately matched to the kernel's emit-time check, so a payload this codec produces and validates is guaranteed to be accepted by peios_event_emit.

You can use it as a general MessagePack codec, but its reason for being is events.

It has three parts: a heap-backed writer, a stack-allocatable reader, and a validator.

9.1.1 See also #

  • <peios/event.h> — the KMES events these payloads travel in.
  • Library conventions — the sticky-error builder model the writer follows.

9.2 Conventions

Peios / Developing for Peios / SDK Reference / msgpack.h — Encoding

A few rules hold across the codec:

  • Integers are written in their smallest MessagePack form automatically — you write an int64/uint64 and the encoder picks the compact encoding.
  • str values must be valid UTF-8. Use bin for arbitrary bytes. The reader enforces this on str reads too.
  • A valid payload is exactly one top-level value, and an empty buffer is not valid. (A map or array at the top counts as that one value.)
  • The writer is sticky-error, exactly like the <peios/security.h> builders: the write calls cannot fail individually; the first error latches and surfaces at peios_mp_writer_bytes / peios_mp_writer_error.

9.3 Writer

Peios / Developing for Peios / SDK Reference / msgpack.h — Encoding

typedef struct peios_mp_writer peios_mp_writer;

peios_mp_writer *peios_mp_writer_new(void);
void             peios_mp_writer_free(peios_mp_writer *w);
void             peios_mp_writer_reset(peios_mp_writer *w);

Create a writer, append values, take the bytes, free it (or reset to reuse). All the append calls return void — errors latch.

9.3.1 Scalars #

void peios_mp_write_nil(peios_mp_writer *w);
void peios_mp_write_bool(peios_mp_writer *w, bool v);
void peios_mp_write_int(peios_mp_writer *w, int64_t v);
void peios_mp_write_uint(peios_mp_writer *w, uint64_t v);
void peios_mp_write_float(peios_mp_writer *w, double v);
void peios_mp_write_str(peios_mp_writer *w, const char *s, size_t len);  /* UTF-8 */
void peios_mp_write_bin(peios_mp_writer *w, const void *b, size_t len);

Use peios_mp_write_int for signed and peios_mp_write_uint for unsigned values; both are stored in the smallest form. peios_mp_write_str takes UTF-8 with an explicit length (no NUL needed); peios_mp_write_bin takes arbitrary bytes.

9.3.2 Containers #

void peios_mp_write_array(peios_mp_writer *w, uint32_t count);
void peios_mp_write_map(peios_mp_writer *w, uint32_t count);

Write the header, then exactly the promised number of values. A map of count needs 2 * count values — count key/value pairs — written key, value, key, value…. An under- or over-filled container is not caught at the write call; it surfaces at peios_mp_writer_bytes, when the whole structure is validated.

/* {"user": "alice", "ok": true} */
peios_mp_write_map(w, 2);
peios_mp_write_str(w, "user", 4);  peios_mp_write_str(w, "alice", 5);
peios_mp_write_str(w, "ok", 2);    peios_mp_write_bool(w, true);

9.3.3 Extensions and raw bytes #

void peios_mp_write_ext(peios_mp_writer *w, int8_t ext_type, const void *b, size_t len);
void peios_mp_write_raw(peios_mp_writer *w, const void *b, size_t len);
  • peios_mp_write_ext writes a MessagePack extension value with a signed type id.
  • peios_mp_write_raw appends pre-encoded MessagePack bytes verbatim — the escape hatch for splicing in a value you already have encoded. The result is still structurally validated as a whole at peios_mp_writer_bytes, so you can't smuggle malformed bytes through it.

9.3.4 Taking the bytes #

ssize_t peios_mp_writer_bytes(peios_mp_writer *w, const void **out);
int     peios_mp_writer_error(const peios_mp_writer *w);

peios_mp_writer_bytes confirms the buffer is exactly one well-formed top-level value, then borrows it: it writes a pointer to the encoded bytes through out (valid until the next mutating call on w) and returns the length. Pass out == NULL to validate and get the length without borrowing. It returns -1 with errno — EINVAL on a latched error or a malformed/under-filled structure, ENOMEM on a prior allocation failure. peios_mp_writer_error returns the latched errno directly, or 0.

Because this call validates, a successful peios_mp_writer_bytes is your guarantee the bytes are emit-ready.

9.4 Reader

Peios / Developing for Peios / SDK Reference / msgpack.h — Encoding

The reader is a cursor over a borrowed buffer — stack-allocatable, no heap, no free. It decodes one value at a time, advancing the cursor.

struct peios_mp_reader { uint64_t _opaque[4]; };   /* opaque — do not inspect */

void   peios_mp_reader_init(struct peios_mp_reader *r, const void *buf, size_t len);
size_t peios_mp_reader_remaining(const struct peios_mp_reader *r);

Declare a struct peios_mp_reader locally and peios_mp_reader_init it over your buffer before use. buf can be NULL only when len is zero. Borrowed str/bin/ext pointers the reader hands back point into the original buffer and are valid for as long as it lives. peios_mp_reader_remaining reports the unconsumed byte count.

9.4.1 Peeking #

enum peios_mp_type {
    PEIOS_MP_NIL, PEIOS_MP_BOOL, PEIOS_MP_INT, PEIOS_MP_FLOAT,
    PEIOS_MP_STR, PEIOS_MP_BIN, PEIOS_MP_ARRAY, PEIOS_MP_MAP, PEIOS_MP_EXT,
};

int peios_mp_peek(const struct peios_mp_reader *r);

peios_mp_peek returns the peios_mp_type of the next value without consuming it, or -1 at end-of-input or on an invalid lead byte. Note that integers of every width and sign report as PEIOS_MP_INT — read them with peios_mp_read_int or peios_mp_read_uint as you prefer. Peek is how you drive a dispatch over a value whose type you don't know ahead of time.

9.4.2 Reading scalars #

int peios_mp_read_nil(struct peios_mp_reader *r);
int peios_mp_read_bool(struct peios_mp_reader *r, bool *out);
int peios_mp_read_int(struct peios_mp_reader *r, int64_t *out);
int peios_mp_read_uint(struct peios_mp_reader *r, uint64_t *out);
int peios_mp_read_float(struct peios_mp_reader *r, double *out);

Each consumes one value on success (returns 0) and leaves the cursor untouched on a type mismatch or truncation (-1 with errno == EINVAL) — so a failed read is safe to follow with a different-typed read or a peek. The out pointer is optional: pass NULL to consume/type-check a value without receiving its payload.

9.4.3 Reading strings, bytes, containers, extensions #

ssize_t peios_mp_read_str(struct peios_mp_reader *r, const char **out);
ssize_t peios_mp_read_bin(struct peios_mp_reader *r, const void **out);
ssize_t peios_mp_read_array(struct peios_mp_reader *r);
ssize_t peios_mp_read_map(struct peios_mp_reader *r);
ssize_t peios_mp_read_ext(struct peios_mp_reader *r, int8_t *type_out, const void **out);
int     peios_mp_skip(struct peios_mp_reader *r);
  • peios_mp_read_str / peios_mp_read_bin borrow the bytes (a pointer into the reader's buffer through out) and return the length, or -1. Strings are not NUL-terminated — use the length — and peios_mp_read_str rejects invalid UTF-8.
  • peios_mp_read_array returns the element count; peios_mp_read_map returns the key/value pair count (so read 2 * count values). After the header you read that many values yourself.
  • peios_mp_read_ext borrows an extension value's bytes, reporting its signed type id through type_out (both type_out and out are independently optional), and returns the data length.
  • peios_mp_skip consumes exactly one complete value, descending into nested containers — the way to ignore a value (or a whole subtree) you don't care about. 0 / -1.
struct peios_mp_reader r;
peios_mp_reader_init(&r, payload, payload_len);

ssize_t pairs = peios_mp_read_map(&r);          /* top-level map */
for (ssize_t i = 0; i < pairs; i++) {
    const char *key; ssize_t klen = peios_mp_read_str(&r, &key);
    /* dispatch on key… then read or skip the value */
    peios_mp_skip(&r);
}

9.5 Validator

Peios / Developing for Peios / SDK Reference / msgpack.h — Encoding

int peios_mp_validate(const void *buf, size_t len, uint32_t max_depth);

peios_mp_validate confirms buf/len is exactly one well-formed MessagePack value: UTF-8 strings, nesting bounded by max_depth, no trailing bytes, non-empty. Returns 0 if valid, -1 with errno == EINVAL otherwise.

Crucially, its acceptance matches the kernel's emit-time check, so a 0 return means the event emit calls will accept the payload — at this depth bound. Pass KMES_CONFIG_MAX_NESTING_DEPTH_DEFAULT (32) for the default emit limit; the top-level value is depth 1. Validate before emitting when a payload comes from an untrusted or dynamic source, so you turn a would-be EINVAL from the kernel into a check you control.

10.1 Becoming a Source

Peios / Developing for Peios / SDK Reference / rsi/source.h — Becoming a Source

<rsi/source.h> is where a registry source begins. A source is a storage backend for the LCS registry — the provider counterpart to libpeios's registry client. Where a client opens keys and reads values, a source is what actually holds those keys and values and answers the kernel's requests for them.

This header has one job: registration. You declare which hives your process backs, register with the kernel, and get back a source fd. From that point on you serve the RSI (Registry Source Interface) protocol on that fd — reading requests and writing responses. Registration requires SeTcbPrivilege. The RSI wire constants (RSI_HIVE_PRIVATE, RSI_*) come from <pkm/lcs.h>.

This is part of librsi, a separate library from libpeios — link -lrsi and include <rsi.h> (or the individual <rsi/*.h>). It follows the same library conventions: raw fds, int returning 0/-1+errno, and the errno passed straight through from the kernel.

10.1.1 See also #

  • Registry sources overview — what a source is and how the RSI protocol flows.
  • The registry — the operator-side model of hives, layers, and sources.

10.2 Describing a Hive

Peios / Developing for Peios / SDK Reference / rsi/source.h — Becoming a Source

A hive is a subtree of the registry with its own root key. A source declares one struct rsi_hive per hive it backs:

struct rsi_hive {
    const void *name;         /* hive name (not NUL-terminated) */
    uint32_t    name_len;
    uint32_t    flags;        /* RSI_HIVE_PRIVATE, or 0 for a global hive */
    uint8_t     root_guid[16];/* root key GUID */
    uint8_t     scope_guid[16];/* private hives; zero for a global hive */
};
FieldMeaning
name / name_lenThe hive's name, length-counted (not NUL-terminated).
flagsRSI_HIVE_PRIVATE for a private (scoped) hive, or 0 for a global one.
root_guidThe GUID of the hive's root key — the anchor every path in the hive resolves from.
scope_guidFor a private hive, the scope GUID that bounds who can resolve it; zero for a global hive.

A global hive is visible system-wide; a private hive is scoped by scope_guid and resolvable only by tokens holding that scope (see the token LCS credentials). Set RSI_HIVE_PRIVATE and a non-zero scope_guid together for a private hive; leave both clear for a global one.

10.3 Registering

Peios / Developing for Peios / SDK Reference / rsi/source.h — Becoming a Source

int rsi_register(const struct rsi_hive *hives, uint32_t count, uint64_t max_sequence);

Opens /dev/pkm_registry and registers all count hives in one call, returning the source fd — the descriptor you then read(2) requests and write(2) responses on — or -1 with errno.

ArgumentMeaning
hives / countThe hives this source serves. count must be >= 1; the kernel enforces its configured MaxHivesPerSource limit.
max_sequenceThe highest sequence number this source has already persisted. The kernel resumes its global sequence counter past this value, so a source that has durable state from a previous run must report it here to avoid reusing sequence numbers. A fresh source with no persisted state passes 0.

Errors include EPERM (no SeTcbPrivilege), EINVAL, ENOSPC (over the hive limit), ENOMEM, EFAULT, and any error from the underlying /dev/pkm_registry open(2).

struct rsi_hive hive = {
    .name = "MyStore", .name_len = 7,
    .flags = 0,                                  /* global hive */
    .root_guid = { /* … 16 bytes … */ },
};

int src = rsi_register(&hive, 1, /*max_sequence=*/0);
if (src < 0) { perror("rsi_register"); return -1; }
/* `src` is now the source fd — serve the RSI protocol on it. */

The max_sequence parameter is the one piece of state a durable source must get right: on restart, scan your persisted data for the highest sequence you ever wrote and pass it, so the kernel never hands out a sequence number you've already used.

10.4 What Comes Next

Peios / Developing for Peios / SDK Reference / rsi/source.h — Becoming a Source

Registration is the whole of this header. Once you hold the source fd, the serve loop lives in the other two:

  • <rsi/request.h> — read and decode the requests the kernel sends.
  • <rsi/response.h> — build and send the replies.

The serving requests guide ties them together into a working serve loop.

11.1 Decoding Requests

Peios / Developing for Peios / SDK Reference / rsi/request.h — Decoding Requests

<rsi/request.h> is the receiving half of a registry source's serve loop. The kernel sends your source RSI requests — "look up this child", "store this value", "begin this transaction" — as framed messages on the source fd. This header reads one frame, splits its header from its payload, and decodes the payload into a flat, typed struct you can act on.

The shape of the loop is always: read a frame → parse the header → dispatch on the op-code → decode the payload with the matching parser. The decoders are thin wrappers over the kernel's own RSI parsers, so your wire handling is guaranteed compatible with what the kernel sent.

Borrowing: every decoded name/data field is a (ptr, len) pair that borrows into your frame buffer. The pointers are valid only until you reuse that buffer for the next rsi_read_request. Copy out anything you need to keep across iterations. This is the same borrow discipline as libpeios's views.

Op-code and field constants (RSI_LOOKUP, RSI_WRITE_KEY_FIELD_*, RSI_TXN_*) come from <pkm/lcs.h>.

11.1.1 See also #

  • <rsi/response.h> — building the reply each op expects.
  • Serving requests — the read/parse/dispatch/respond loop in full.

11.2 Reading and Parsing a Frame

Peios / Developing for Peios / SDK Reference / rsi/request.h — Decoding Requests

struct rsi_request {
    uint64_t    request_id;   /* echo this in the response */
    uint64_t    txn_id;       /* transaction id (0 outside a transaction) */
    const void *payload;      /* borrowed; valid until the frame is reused */
    uint32_t    payload_len;
    uint16_t    op_code;      /* RSI_LOOKUP, RSI_SET_VALUE, … — dispatch on this */
};

ssize_t rsi_read_request(int fd, void *buf, size_t cap);
int     rsi_parse_request(const void *frame, size_t len, struct rsi_request *out);
  • rsi_read_request reads one framed request from the source fd into buf — a thin read(2) wrapper that blocks until a request is queued, then returns the frame length (pass it to rsi_parse_request). It returns 0 at EOF (the source is closing — leave the loop) or -1 with errno, notably EMSGSIZE if cap is smaller than the pending frame (size buf generously, or grow and retry).
  • rsi_parse_request splits a frame into its header and payload view, filling out with the request_id (which you must echo in the response), the txn_id (0 when the request is not inside a transaction), the op_code to dispatch on, and a borrowed payload pointer. Returns 0, or -1 with errno (EINVAL on NULL args, EBADMSG on a malformed frame).

11.3 The Decoders

Peios / Developing for Peios / SDK Reference / rsi/request.h — Decoding Requests

Each decoder takes the parsed req and fills a flat struct: GUIDs by value, names, and data as borrowed (ptr, len) pairs. All return 0, or -1 with errno — EINVAL if the arguments are NULL or the decoder doesn't match req->op_code (so calling the wrong decoder for an op is a clean error), and EBADMSG on a malformed payload. You dispatch on req.op_code and call the matching one.

11.3.1 Path and entry operations #

These operate on the name→GUID bindings that make up the key hierarchy. A child is named under a parent GUID, and entries live in layers.

/* LOOKUP — is child_name visible under parent_guid? */
struct rsi_lookup {
    uint8_t     parent_guid[16];
    const void *child_name;  uint32_t child_name_len;
};
int rsi_request_lookup(const struct rsi_request *req, struct rsi_lookup *out);

/* CREATE_ENTRY — bind child_name → child_guid in layer_name. */
struct rsi_create_entry {
    uint8_t     parent_guid[16];
    uint8_t     child_guid[16];
    const void *child_name;  uint32_t child_name_len;
    const void *layer_name;  uint32_t layer_name_len;
    uint64_t    sequence;
};
int rsi_request_create_entry(const struct rsi_request *req, struct rsi_create_entry *out);

/* HIDE_ENTRY — tombstone child_name in layer_name. */
struct rsi_hide_entry {
    uint8_t     parent_guid[16];
    const void *child_name;  uint32_t child_name_len;
    const void *layer_name;  uint32_t layer_name_len;
    uint64_t    sequence;
};
int rsi_request_hide_entry(const struct rsi_request *req, struct rsi_hide_entry *out);

/* DELETE_ENTRY — remove child_name's entry in layer_name. */
struct rsi_delete_entry {
    uint8_t     parent_guid[16];
    const void *child_name;  uint32_t child_name_len;
    const void *layer_name;  uint32_t layer_name_len;
};
int rsi_request_delete_entry(const struct rsi_request *req, struct rsi_delete_entry *out);

/* ENUM_CHILDREN — list the children of parent_guid. */
struct rsi_enum_children { uint8_t parent_guid[16]; };
int rsi_request_enum_children(const struct rsi_request *req, struct rsi_enum_children *out);
OpYou mustReply with
LOOKUPResolve child_name under parent_guid across your layers.rsi_respond_lookup
CREATE_ENTRYBind child_name → child_guid in layer_name at sequence.status
HIDE_ENTRYPlace a tombstone for child_name in layer_name.status
DELETE_ENTRYRemove child_name's entry in layer_name.status
ENUM_CHILDRENList every child of parent_guid.rsi_respond_enum_children

11.3.2 Key operations #

These operate on key metadata records — the non-layered facts about a key (its name, parent, security descriptor, flags).

/* CREATE_KEY — create the metadata record guid under parent_guid. */
struct rsi_create_key {
    uint8_t     guid[16];
    uint8_t     parent_guid[16];
    const void *name;  uint32_t name_len;
    const void *sd;    uint32_t sd_len;
    uint8_t     volatile_key;  /* 1 if volatile */
    uint8_t     symlink;       /* 1 if a symlink */
};
int rsi_request_create_key(const struct rsi_request *req, struct rsi_create_key *out);

/* READ_KEY / DROP_KEY — a request carrying just a key GUID. */
struct rsi_key_guid { uint8_t guid[16]; };
int rsi_request_read_key(const struct rsi_request *req, struct rsi_key_guid *out);
int rsi_request_drop_key(const struct rsi_request *req, struct rsi_key_guid *out);

/* WRITE_KEY — update the mutable fields of guid named by field_mask. */
struct rsi_write_key {
    uint8_t     guid[16];
    uint32_t    field_mask;        /* RSI_WRITE_KEY_FIELD_SD | …_LAST_WRITE_TIME */
    const void *sd;  uint32_t sd_len;/* NULL when the SD bit is clear */
    uint64_t    last_write_time;   /* valid only when the time bit is set */
};
int rsi_request_write_key(const struct rsi_request *req, struct rsi_write_key *out);
OpYou mustReply with
CREATE_KEYStore the metadata record for guid (its name, parent, sd, and the volatile_key/symlink flags).status
READ_KEYReturn the metadata of guid.rsi_respond_read_key
DROP_KEYDelete the metadata record for guid.status
WRITE_KEYUpdate only the fields selected in field_mask — the SD when RSI_WRITE_KEY_FIELD_SD is set, the last_write_time when its bit is set — leaving the rest untouched.status

WRITE_KEY's field_mask is the important detail: sd is NULL unless the SD bit is set, and last_write_time is meaningful only when the time bit is set, so consult the mask before reading either.

11.3.3 Value operations #

These operate on the typed values stored on a key, each written into a layer.

/* QUERY_VALUES — read value_name (or all values when query_all) of guid. */
struct rsi_query_values {
    uint8_t     guid[16];
    const void *value_name;  uint32_t value_name_len;
    uint8_t     query_all;   /* 1 = every value (then value_name is ignored) */
};
int rsi_request_query_values(const struct rsi_request *req, struct rsi_query_values *out);

/* SET_VALUE — store value_name in layer_name with the given type/data. */
struct rsi_set_value {
    uint8_t     guid[16];
    const void *value_name;  uint32_t value_name_len;
    const void *layer_name;  uint32_t layer_name_len;
    uint32_t    value_type;
    const void *data;  uint32_t data_len;
    uint64_t    sequence;
    uint64_t    expected_sequence;  /* CAS guard (0 disables) */
};
int rsi_request_set_value(const struct rsi_request *req, struct rsi_set_value *out);

/* DELETE_VALUE_ENTRY — remove value_name's entry in layer_name. */
struct rsi_delete_value_entry {
    uint8_t     guid[16];
    const void *value_name;  uint32_t value_name_len;
    const void *layer_name;  uint32_t layer_name_len;
};
int rsi_request_delete_value_entry(const struct rsi_request *req,
                                   struct rsi_delete_value_entry *out);

/* SET_BLANKET_TOMBSTONE — set or clear a blanket tombstone on layer_name. */
struct rsi_set_blanket_tombstone {
    uint8_t     guid[16];
    const void *layer_name;  uint32_t layer_name_len;
    uint8_t     set;         /* 1 = set, 0 = clear */
    uint64_t    sequence;
};
int rsi_request_set_blanket_tombstone(const struct rsi_request *req,
                                      struct rsi_set_blanket_tombstone *out);
OpYou mustReply with
QUERY_VALUESReturn value_name — or every value when query_all is 1 (then value_name is ignored) — plus any blanket tombstones.rsi_respond_query_values
SET_VALUEStore value_name of value_type in layer_name. Honor expected_sequence as a compare-and-swap guard (0 disables it) — reject with a non-OK status if the current sequence differs.status
DELETE_VALUE_ENTRYRemove value_name's entry in layer_name.status
SET_BLANKET_TOMBSTONESet (set == 1) or clear a blanket tombstone on layer_name, masking all lower values at once.status

11.3.4 Transaction operations #

The kernel drives transaction boundaries; your source honors them so a group of writes commits or aborts atomically.

/* BEGIN_TRANSACTION — open transaction_id in mode. */
struct rsi_begin_transaction {
    uint64_t    transaction_id;
    uint32_t    mode;   /* RSI_TXN_READ_WRITE (0) or RSI_TXN_READ_ONLY (1) */
};
int rsi_request_begin_transaction(const struct rsi_request *req,
                                  struct rsi_begin_transaction *out);

/* COMMIT_TRANSACTION / ABORT_TRANSACTION — a request carrying just a transaction id. */
struct rsi_transaction { uint64_t transaction_id; };
int rsi_request_commit_transaction(const struct rsi_request *req, struct rsi_transaction *out);
int rsi_request_abort_transaction(const struct rsi_request *req, struct rsi_transaction *out);
OpYou mustReply with
BEGIN_TRANSACTIONOpen transaction_id in mode (RSI_TXN_READ_WRITE or RSI_TXN_READ_ONLY); buffer subsequent writes tagged with this id.status
COMMIT_TRANSACTIONAtomically apply everything buffered under transaction_id.status
ABORT_TRANSACTIONDiscard everything buffered under transaction_id.status

Requests that belong to a transaction carry its id in req.txn_id; a txn_id of 0 means the request is outside any transaction.

11.3.5 Layer operations #

/* DELETE_LAYER / FLUSH — a request carrying just a length-prefixed name. */
struct rsi_name { const void *name;  uint32_t name_len; };
int rsi_request_delete_layer(const struct rsi_request *req, struct rsi_name *out);
int rsi_request_flush(const struct rsi_request *req, struct rsi_name *out);
OpYou mustReply with
DELETE_LAYERRemove the entire named layer, reporting the GUIDs of any keys it orphaned.rsi_respond_delete_layer
FLUSHDurably persist pending writes for the named hive, replying only once persistence is confirmed.status

12.1 Building Responses

Peios / Developing for Peios / SDK Reference / rsi/response.h — Building Responses

<rsi/response.h> is the sending half of a source's serve loop. After you handle a request, you reply on the source fd with a framed response. This header builds those frames for you: you pass the result as flat arrays, and librsi validates and heap-encodes the wire frame — you never hand-pack a byte.

Every response echoes the request's id and its op-code (OR'd with the response bit) and carries an RSI_* status. Most operations are status-only; five carry a payload on success. Any operation can report a non-OK status with the status-only helper.

For the wire, a response is a 14-byte header (echoed request id, op-code | RSI_RESPONSE_BIT) plus a 4-byte RSI_* status, followed by an op-specific payload for payload-bearing successes; multi-byte integers are little-endian and names/data are length-prefixed. You don't assemble any of that — the helpers do. Status and target-type constants (RSI_OK, RSI_PATH_TARGET_GUID, …) come from <pkm/lcs.h>.

12.1.1 See also #

  • <rsi/request.h> — decoding the request each of these replies to.
  • Building responses — choosing and filling the right responder.

12.2 Status Codes

Peios / Developing for Peios / SDK Reference / rsi/response.h — Building Responses

Every response carries exactly one of these statuses. The kernel translates a non-OK status into the errno the registry client sees, so send the code that matches what actually happened:

CodeWhen to send it
RSI_OKThe operation succeeded. Status-only ops report it through rsi_respond_status; the five payload-bearing ops must use their own helper.
RSI_NOT_FOUNDThe requested key, entry, value, or layer does not exist in your store (client sees ENOENT).
RSI_ALREADY_EXISTSA create collided with something that already exists (client sees EEXIST).
RSI_STORAGE_ERRORYour backing store failed — I/O error, corruption, anything the client can't fix (client sees EIO).
RSI_NOT_EMPTYThe operation needs the key to have no children, and it has some (client sees ENOTEMPTY).
RSI_TOO_LARGEThe data exceeds what the source is willing or able to store (client sees ENOSPC).
RSI_TXN_BUSYA transaction can't proceed right now — for example write-lock contention; the operation can be retried (client sees EBUSY).
RSI_INVALIDThe request is well-formed RSI but violates the source's rules or refers to something malformed (client sees EINVAL).
RSI_CAS_FAILEDA sequence-guarded write's expected_sequence did not match the current entry — the compare-and-swap lost (client sees EAGAIN and retries).
RSI_TXN_NOT_SUPPORTEDReply to BEGIN_TRANSACTION from a source that does not implement transactions (client sees ENOTSUP).

12.3 The Response Contract

Peios / Developing for Peios / SDK Reference / rsi/response.h — Building Responses

All rsi_respond_* helpers return 0, or -1 with errno. A set of rules applies to every helper, and violating one is an EINVAL caller-contract error:

  • (ptr, len) pairs: a pointer can be NULL only when its length/count is zero.
  • Boolean fields (volatile_key, symlink, target types) must be exactly 0 or 1.
  • Hidden path targets (RSI_PATH_TARGET_HIDDEN) must carry an all-zero target_guid.
  • LOOKUP/ENUM_CHILDREN metadata must exactly cover the GUID path targets referenced — no missing metadata, no duplicates, no unreferenced entries.
  • DELETE_LAYER orphan GUIDs must be nonzero and unique.

Beyond EINVAL, any helper can also fail with ENOMEM (during validation or frame allocation), EOVERFLOW (validation arithmetic or the assembled frame too large), EIO (a short write), or the raw write(2) errno. Per-helper EINVAL additions are noted below.

12.4 Sending a Pre-built Frame

Peios / Developing for Peios / SDK Reference / rsi/response.h — Building Responses

ssize_t rsi_write_response(int fd, const void *frame, size_t len);

Writes one already-built response frame to the source fd — a thin write(2) wrapper returning the bytes written, or -1 with errno. Most callers never need this; the rsi_respond_* helpers build and send. It exists for callers assembling frames by other means.

12.5 Status-only Responses

Peios / Developing for Peios / SDK Reference / rsi/response.h — Building Responses

int rsi_respond_status(int fd, const struct rsi_request *req, uint32_t status);

The workhorse. Use it for:

  • status-only ops on success — pass status = RSI_OK; and
  • any op reporting a non-OK status — a LOOKUP that found nothing, a SET_VALUE that failed a compare-and-swap, a permission error: reply with the appropriate RSI_* status here, whatever the op.

It fails with EINVAL on a bad req, an unknown status, or RSI_OK given for a payload-bearing op (those must use their own helper on success), plus EIO / the write error.

The rule of thumb: on failure, always rsi_respond_status; on success, rsi_respond_status unless the op is one of the five below.

12.6 Payload-bearing Responses

Peios / Developing for Peios / SDK Reference / rsi/response.h — Building Responses

Five operations return data on success. Each takes the result as flat arrays and encodes the frame for you.

12.6.1 LOOKUP #

struct rsi_path_entry {
    const void *layer;  uint32_t layer_len;
    uint8_t     target_type;   /* RSI_PATH_TARGET_GUID (0) / RSI_PATH_TARGET_HIDDEN (1) */
    uint8_t     target_guid[16];
    uint64_t    sequence;
};
struct rsi_key_metadata {
    uint8_t     guid[16];
    const void *sd;  uint32_t sd_len;
    uint8_t     volatile_key;
    uint8_t     symlink;
    uint64_t    last_write_time;
};

int rsi_respond_lookup(int fd, const struct rsi_request *req,
                       const struct rsi_path_entry *entries, uint32_t entry_count,
                       const struct rsi_key_metadata *metadata, uint32_t metadata_count);

Answers a LOOKUP with the resolved path entries for the child — one per layer that has a view of it, each either a GUID target or a HIDDEN (tombstone) target — plus the metadata for every key the entries reference. A RSI_PATH_TARGET_HIDDEN entry must carry an all-zero target_guid; the metadata must exactly cover the GUID targets. EINVAL if req is not a LOOKUP, a nonzero count has a NULL array, or an entry has invalid target/boolean fields, missing/duplicate metadata, or unreferenced metadata.

12.6.2 ENUM_CHILDREN #

struct rsi_child_entry {
    const void            *child_name;  uint32_t child_name_len;
    const struct rsi_path_entry *entries;  uint32_t entry_count;
};

int rsi_respond_enum_children(int fd, const struct rsi_request *req,
                              const struct rsi_child_entry *children, uint32_t child_count,
                              const struct rsi_key_metadata *metadata, uint32_t metadata_count);

Answers an ENUM_CHILDREN with each child — its name and the path entries that resolve it — plus the metadata for every referenced key. The same target/boolean/metadata-coverage rules as LOOKUP apply. EINVAL on the same conditions, scoped to ENUM_CHILDREN.

12.6.3 READ_KEY #

int rsi_respond_read_key(int fd, const struct rsi_request *req, const void *name,
                         uint32_t name_len, const uint8_t *parent_guid, const void *sd,
                         uint32_t sd_len, uint8_t volatile_key, uint8_t symlink,
                         uint64_t last_write_time);

Answers a READ_KEY with the key's non-layered metadata: its name, parent_guid, security descriptor (sd), the volatile_key/symlink flags, and last_write_time. EINVAL if req is not a READ_KEY, parent_guid is NULL, or a boolean field is invalid.

12.6.4 QUERY_VALUES #

struct rsi_value_entry {
    const void *value_name;  uint32_t value_name_len;
    const void *layer_name;  uint32_t layer_name_len;
    uint32_t    value_type;
    const void *data;  uint32_t data_len;
    uint64_t    sequence;
};
struct rsi_blanket_entry {
    const void *layer_name;  uint32_t layer_name_len;
    uint64_t    sequence;
};

int rsi_respond_query_values(int fd, const struct rsi_request *req,
                             const struct rsi_value_entry *entries, uint32_t entry_count,
                             const struct rsi_blanket_entry *blankets, uint32_t blanket_count);

Answers a QUERY_VALUES with the value entries — each value's name, the layer it lives in, its type, data, and sequence — plus the blankets (the blanket tombstones on this key, each a layer and sequence). The kernel resolves precedence across the layers you report. EINVAL if req is not a QUERY_VALUES or a nonzero count has a NULL array.

12.6.5 DELETE_LAYER #

int rsi_respond_delete_layer(int fd, const struct rsi_request *req,
                             const uint8_t *orphaned_guids, uint32_t orphaned_count);

Answers a DELETE_LAYER with the GUIDs of the keys the deleted layer orphaned — a flat orphaned_count * 16-byte array. The GUIDs must be nonzero and unique. EINVAL if req is not a DELETE_LAYER or a nonzero count has a NULL array, a nil GUID, or a duplicate.

12.7 The Five at a Glance

Peios / Developing for Peios / SDK Reference / rsi/response.h — Building Responses

Success responseOpPayload
rsi_respond_lookupLOOKUPpath entries + referenced key metadata
rsi_respond_enum_childrenENUM_CHILDRENchildren (name + path entries) + metadata
rsi_respond_read_keyREAD_KEYone key's non-layered metadata
rsi_respond_query_valuesQUERY_VALUESvalue entries + blanket tombstones
rsi_respond_delete_layerDELETE_LAYERorphaned key GUIDs

Every other op — and every failure of these — is rsi_respond_status.

1.1 Overview

Peios / Developing for Peios / Go SDK Reference / Go SDK Conventions

The Go SDK uses Go values and interfaces for portable formats and native Peios operations. Its package documentation describes each public API; this chapter explains the ownership and authority rules shared by them.

1.1.1 Packages and authority #

Security formats and MessagePack codecs run without a Peios kernel. Native file, token, socket, process, registry, and event operations target Linux on x86-64 with the Peios kernel interface. Compiling on another Linux system does not supply those operations.

Native errors use syscall.Errno and support errors.Is. An access check reports a decision; the kernel still checks authority when you perform the operation. Process creation uses Go's os/exec and normal kernel inheritance. Activating process mitigations cannot clear existing bits.

1.1.2 Handles and buffers #

Close owned token, key, transaction, and file handles. Operations accepting syscall.Conn protect a descriptor from concurrent close and reuse during the call. A raw directory descriptor remains your responsibility: keep it open throughout the operation.

Descriptor parsers and event readers return owned data. Borrowed MessagePack cursor views remain tied to the caller's input buffer. MessagePack maps preserve pair order and duplicate keys. Decoder position advances only after a successful decode.

1.1.3 Identity scopes #

Token.Impersonate runs its callback on a dedicated, locked thread. The scope restores identity before returning and retires the thread if restoration fails. A callback panic is rethrown after cleanup.

WithIdentityThread supports repeated identity changes within one locked thread. The scope rejects calls after the callback or from another thread. Neither API transfers its identity to goroutines created by the callback. Installing a process token is a separate operation.

1.1.4 Security formats #

Binary descriptors retain entry order, unknown entry bodies, and metadata that text cannot express. Text formatting rejects unsupported entries rather than discarding them. An absent discretionary access control list (DACL) differs from an empty one. The present-null form is rejected.

Conditions have a 128-level expression limit, including long AND or OR chains. Parsing rejects deeper expressions with EINVAL, matching the formatter. Nested operands also have a depth bound.

Inheritance resolves creator identities and generic rights for the receiving object. It preserves explicit entries and protected lists. Stripping inherited entries preserves descriptor metadata and revision floors. Parsed lists can retain exact revision bytes during serialization.

1.2 Registry and Event Lifetimes

Peios / Developing for Peios / Go SDK Reference / Go SDK Conventions

Registry keys and event rings expose state that can change while your application reads it. The Go SDK gives returned data an explicit lifetime and reports changes that prevent a complete read.

1.2.1 Registry values and sources #

Registry writes use the base layer when Layer is empty. A nil or zero expected sequence disables compare-and-set. Delete operations reject an expected sequence because their kernel operation has no comparison field. Notifications are armed and read on the same key handle.

Allocating value helpers have a 16 MiB limit. QueryInto, ValuesInto, and ValueAtInto accept caller buffers; a nil buffer probes the required size and returns ERANGE. Batch counts are meaningful on success, and a size probe can report zero records.

TakeFile and TakeTransactionFile transfer descriptor ownership into registry handles. Close the resulting handle rather than closing its adopted descriptor separately.

registry/source.Source.Serve bounds concurrent handlers and serializes response writes. It closes the source on return or cancellation, waits for workers, and reports transport errors. Handlers must observe cancellation and provide storage and transaction semantics. Decoders permit trailing extension fields; the handler chooses its version policy.

1.2.2 Events and waits #

AttachAll visits the complete CPU slot range and skips empty slots. Each reader begins at its oldest surviving record and follows resizes. Returned events own their data and survive subsequent reads or closure.

Drain Next until no event is available, then wait with Wait(ctx). Cancellation or close can take up to 50 ms to interrupt a futex wait. Lost counts observed sequence gaps, not losses before attachment. Readers do not establish an ordering between different CPUs.

Low-level attachments and mappings have separate lifetimes: close both. EventAt returns owned data and a wire size, or EAGAIN for an empty, overwritten, or changed slot. Advance the absolute cursor by the wire size. A generation change requires a fresh attachment and mapping.

A context deadline bounds Ring.Wait. A canceled context permits a nonblocking readiness check; available data takes precedence over cancellation in that low-level method.

Emission policy is read afresh for each call. Essential events bypass registry policy; other tiers use defaults and the deepest valid Enabled value. This avoids retained watch handles at the cost of registry work on each policy check.

1.2.3 Messages and sessions #

A received socket message owns its delivered handles. Call Message.Close when finished. Receive closes all delivered handles if control data is truncated. ReceivePartial keeps handles that fit, closes excess handles, and reports truncation flags for the caller to assess.

A partial send does not resend ancillary data. Zero-length sequence-packet messages can transfer handles without an extra payload byte.

OpenSessions returns a snapshot reader. Next returns io.EOF at the end; a malformed line returns EPROTO and is consumed so reading can continue. Closing the last token destroys a used dynamic session. DestroyEmptySession handles an unused session. Session enumeration requires the appropriate classified securityfs mount and access rights.

2.1 Security Descriptors and Selectors

Peios / Developing for Peios / Go SDK Reference / Go SDK Security

security.SecurityInformation is the bitmask that selects components of a security descriptor. Use its named constants with file and registry descriptor operations:

ConstantValueSelected component
security.InfoOwner0x01Owner SID.
security.InfoGroup0x02Group SID.
security.InfoDACL0x04Discretionary ACL.
security.InfoSACL0x08Full system ACL.
security.InfoLabel0x10Mandatory-integrity label within the SACL.

Combine selectors with |, for example security.InfoOwner | security.InfoDACL. InfoLabel can accompany owner, group, or DACL selection, but must not be combined with InfoSACL; the kernel rejects that combination with EINVAL.

InfoLabel reads or writes a descriptor containing the label ACE in its SACL. Its payload is not a raw integrity SID. Reading the label requires READ_CONTROL; writing it requires WRITE_OWNER. Raising a label above the caller's integrity also requires SeRelabelPrivilege. Selecting the full SACL instead requires ACCESS_SYSTEM_SECURITY, gated by SeSecurityPrivilege.

Updates preserve components that were not selected. In particular, selecting only InfoLabel changes the mandatory label without replacing the other SACL entries. All selected components must pass their applicable authorization checks.

2.1.1 File descriptors #

file.GetDescriptor(f, info) returns owned descriptor bytes; file.SetDescriptor(f, info, sd) applies selected components from binary descriptor bytes. Both accept syscall.Conn, including *os.File. The path-relative variants are file.GetDescriptorAt(dirfd, path, info, flags) and file.SetDescriptorAt(dirfd, path, info, sd, flags).

For example, read and parse the mandatory label:

package example

import (
    "os"

    "github.com/peios/peios-go/file"
    "github.com/peios/peios-go/security"
)

func readLabel(f *os.File) (security.Descriptor, error) {
    wire, err := file.GetDescriptor(f, security.InfoLabel)
    if err != nil {
        return security.Descriptor{}, err
    }
    return security.ParseDescriptor(wire)
}

To request a medium-integrity, no-write-up label, build the descriptor and select only its label:

func setMediumLabel(f *os.File) error {
    sd, err := security.ParseSDDL("S:(ML;;NW;;;ME)")
    if err != nil {
        return err
    }
    wire, err := sd.MarshalBinary()
    if err != nil {
        return err
    }
    return file.SetDescriptor(f, security.InfoLabel, wire)
}

The second example uses the first example's imports. These functions perform native Peios operations and still depend on the caller's authority; constructing valid SDDL does not grant permission to set it.

2.1.2 Registry keys #

(*registry.Key).GetDescriptor(info) returns binary descriptor bytes, and (*registry.Key).SetDescriptor(info, sd, tx) writes selected components. They use the same security.Info* selectors, including InfoLabel, and the same prohibition on combining label and full-SACL selection. Pass a *registry.Transaction for a transactional update, or nil for an update without an explicit transaction.

Use security.ParseDescriptor to decode returned bytes and Descriptor.MarshalBinary to encode a descriptor for an update. security.ParseSDDL is available when constructing a descriptor from text. An absent DACL and an empty DACL are different: preserve that distinction when building or rewriting descriptors.

Formats and Constants

Peios / Reference / Interface References

Use the reference owned by the interface you are implementing. Shared data structures are specified in Peios Core Data Structures (PCDS). Kernel system calls and object layouts are documented beside the kernel's exported headers. A service's protocol belongs to that service's contract.

Shared structures #

StructureReference
Security identifier (SID), including its binary representation and well-known valuesPCDS SIDs
Globally unique identifier (GUID)PCDS GUIDs
Locally unique identifier (LUID)PCDS LUIDs
Self-relative security descriptor and its control flagsSD Structure
Access control list (ACL) header and entriesACL Format
Access mask and generic-right interpretationAccess Masks
Access control entry (ACE) types and bodiesACE Types
Inheritance and propagation flagsInheritance
Claims, resource attributes, and conditional expressionsSecurity Descriptors

PCDS describes the representation. The kernel's descriptor and ACE semantics and MS-DTYP compatibility notes explain implementation behavior. A representable ACE type does not by itself establish that the evaluator acts on that type.

Kernel interfaces #

InterfaceReference
Token creation, sessions, query classes, group attributes, and impersonation levelsToken and Session ABI
Access checks, descriptors, central policies, and security-information flagsAccess-Check and Descriptor ABI
File rights, create dispositions, and mount templatesFile and Mount ABI
Process rights, process security blocks, and mitigationsProcess and PSB ABI
Registry rights and key securityKey and Security ABI
Registry watch recordsWatch ABI
Event-ring records and constantsKMES ABI

The generated tables retain exact exported spellings, field widths, and limits. Consult their semantic companion pages for behavior that a compiler cannot measure. The naming map connects specification names to header names; do not invent a constant by changing its prefix.

Object-specific access bits are not interchangeable. A file, token, process, registry key, and service can assign different meanings to the same bit. Use the object's generic mapping and aggregate masks rather than copying a mask from another interface.

Privileges and service rights #

The kernel's privilege catalog describes what privileges enforce. Assignment and restriction remain separate questions: authd policy supplies grants, while peinit privilege restriction removes unrequested privileges using the names supported by that build.

Service-control rights belong to Peinit's constants and service access model. Do not substitute a Windows service-access table for Peinit's values.

Decode the actual format #

There is no universal length-prefix convention across these interfaces. Token input has a fixed header and structured variable sections. Session input uses fields of different widths. Central access policy input has its own version and rule structure; its ACL payloads are ACLs, while an applies-to expression uses conditional-expression bytecode.

Choose a decoder for the documented version, validate lengths and counts, and use its stated limits. A stale count of fields or query classes in a secondary summary is not a format contract. Prefer the supported SDK encoder when it provides the required operation.

Events and packages #

The Peios System-to-Kernel Protocols define shared kernel protocol contracts. Use the emitting component's evman catalog for individual event payloads; a name and a binary envelope do not define every event field.

Package and repository contracts are in Peios System-to-Userspace Protocols. Match the documented package format to the tool consuming it; a package format transition does not make an older container readable by a newer tool automatically.

1.1 Overview

Peios / Reference / peinit / Introduction

peinit is PID 1. It is the only service manager on a Peios system: every supervised process on the machine — a platform daemon, an application service, a startup hook, a health probe, a job some other service asked for on a user's behalf — is forked by peinit and watched by peinit until it exits.

It is a single-threaded Rust process. That is the constraint the rest of its design answers to. A blocking syscall in PID 1 stops everything: child reaping, watchdog expiry, shutdown signals, the control socket. So peinit keeps a complete in-memory model of every service it knows about, reads the registry synchronously only at boot and when it reloads — whether an administrator asked for the reload or a registry change notification set it off, which takes the same path (§10.4)  — and pushes anything that could block off the main loop into a forked helper or a pollable descriptor.

1.1.1 What makes it not systemd #

Two things, and both run deep enough to change the shape of the daemon.

Services are securable objects. A service carries a Security Descriptor that says who can start it, stop it, query it, or reload it, and peinit evaluates that descriptor against the caller's KACS token on every control request. There is no "root can do anything" path, because there is no root — there is a token, and AccessCheck is the only thing that decides.

Service identity is a token, not a user. peinit never sets a UID, a GID, or a Linux capability on a service process. It obtains a KACS token — minted from its own for the platform daemons that start before an authority exists, requested from authd for everything else — restricts its privileges to what the definition asked for, and installs it on the child before exec. Every service also carries a per-service SID derived from its name, so two services sharing an identity are still distinguishable to an access check.

Configuration follows from the second one: service definitions live in the registry, under Machine\System\Services\, where they are protected by the registry's own descriptors rather than by file permissions. There are no unit files, no generators, and no translation layer.

1.1.2 The shape of the daemon #

Boot is two phases with registryd as the boundary. Phase 1 is compiled in and has no registry dependency at all: it confirms the root is writable, mounts what is missing, restores entropy, settles the clock, and starts registryd. Phase 2 reads the service graph out of the registry and boots the system from it. When Phase 1 cannot complete, there is no Phase 2 to fall back to, and peinit drops into a recovery shell.

Once booted, peinit is an event loop over a handful of descriptors: a signalfd, the control socket, the jobs socket, the notify socket, one timerfd per armed timer, a pidfd per supervised process, a pipe pair per supervised process's output, and the registry's change-notification descriptor. Work arriving on most of them turns into an operation — a queued, observable request to move a service through its state machine — and executing an operation eventually forks a job. Work arriving on the jobs socket skips the operation: a submitted job has no service and no state machine to contend for, so a submission forks a job directly.

Those two objects are how peinit stays comprehensible under concurrency. Operations exist so that two administrators issuing conflicting commands get a defined answer instead of a race. Jobs exist so that "what actually ran" is a thing with an identifier, a token summary, an exit status and a log correlation key, rather than a PID that can already have been reused.

peinit keeps no history of either. A job or an operation that reaches a terminal state is emitted as a structured event into the KMES kernel ring buffer and dropped. eventd is the historian.

1.1.3 What peinit is not #

It does not assemble storage. The initramfs delivers a mounted, writable root, and peinit neither decrypts, nor assembles, nor checks it. It has no mount feature beyond the fixed Phase 1 set  — mounting a data partition is a Oneshot service's job.

It does not store logs. It holds the pipes at birth, tags each line, and forwards it to eventd; before eventd exists it buffers, and when the buffer fills it drops the oldest.

It does not authenticate anyone. authd mints tokens; peinit installs them. It does not resolve identities, and it does not know or care whether a principal is local or from a domain.

And it does not support forking daemons. It tracks the process it spawned, through a pidfd obtained at fork, and there is no mechanism for a service to point supervision somewhere else.

1.2 What This Manual Covers

Peios / Reference / peinit / Introduction

This manual describes peinit as it is built: the boot sequence, the service model and its registry schema, how a service acquires its identity, the exact sequence between "start this" and "the binary is running", the state machine and its causes, dependencies, jobs and operations, timers, output handling, shutdown, and the security model.

1.2.1 What is a contract and what is not #

Three of peinit's interfaces are specified separately. PSPU §4 gives the control socket, spoken by administrative tools and by any program that manages services or observes jobs, and the notification socket, spoken by every service and every submitted job that reports readiness, status, keepalives, or a stored descriptor. PSPU §7 gives the jobs socket, spoken by any process that asks peinit to run and supervise a program on its behalf. Those are contracts. A third party implements one side of each, and what is written there binds both.

This manual covers the other side of that boundary — how peinit fulfils them, and everything that is not a contract at all:

  • how a command becomes an operation, and what happens when two of them collide (§8.2, §8.3)
  • what a command does to a service in each state (§10.3)
  • how a notification is authenticated and applied (§10.5, §10.6)
  • how a submission becomes a running job, and what it is checked against afterward (§8.5, §10.7)

Where a chapter touches the contract it references PSPU §4 rather than restating it.

The service definition schema is here rather than in PSPU. It is registry configuration, protected by the registry's descriptors and administered by the same tools as the rest of the registry, and it is documented for the people who write service definitions rather than specified as a wire format. §3.2 is the reference.

1.2.2 What this manual does not cover #

  • KACS — tokens, Security Descriptors, AccessCheck, and the per-service SID algorithm peinit reproduces. Peios Kernel TRM §3.
  • LCS — the registry syscalls, watches, and layer resolution peinit reads through. Peios Kernel TRM §5.
  • KMES — the ring buffer peinit emits its events into. Peios Kernel TRM §2.
  • loregd — the storage behind registryd. Its own TRM.
  • eventd — where the logs and events go. Its own manual.
  • authd — token minting and identity routing. peinit's requirements of it are described in §4.3; its interface is authd's own.
  • How a token is conveyed on a socket, and what the kernel checks when it is — peer-token capture, KACS_SCM_TOKEN, the impersonation gates, and the level ratchet that job submission relies on. Peios Kernel TRM §3.5.
  • Using peinit — writing service definitions, the svctl command surface including svctl job, and everyday administration are covered in Using Peios.

1.2.3 Constants and keys #

Registry keys and compiled-in constants are collected in the appendices, so a chapter's reference material does not interrupt the prose that explains it. Where an appendix defines a value the body references it rather than repeating it.

1.3 Terminology

Peios / Reference / peinit / Introduction

Terms defined where they are introduced — activation generation, boot generation, transition cause, cgroup generation, start generation — are not repeated here.

Service. A named, supervised unit of execution: a definition in the registry, a runtime state, a Security Descriptor, and at most one running main process. Services are the primary unit of management and the thing dependencies are expressed between.

Job. One supervised process execution. Every fork peinit performs is a job — a service's main binary, a pre-exec hook, a health check invocation, a submitted job — with a GUID, a lifecycle, a token summary and a log correlation key. Jobs are the observable unit of what actually ran.

Submitted job. A job whose definition arrived on the jobs socket rather than from a service definition. It has no service, no operation, and no policy; it belongs to its submitter and is managed under its own Security Descriptor. §8.5.

Submitter. The identity a jobs socket connection carried when a submit was read: recorded on the job, counted for the quota, and the owner of the job's descriptor.

Job identity. The identity a submitted job's process runs as — the submitter's own primary token, or a token the kernel attached to the submit message. Never named by a field. §8.5.

Operation. A first-class object representing a requested state machine action on a service. Control commands do not mutate state directly; they create operations that are validated, queued, resolved against whatever else is in flight, and executed by the event loop.

Trigger. A rule in a service definition saying when the service starts automatically: at boot, once the boot set has settled, or on a schedule. A service with no triggers starts only when something asks for it.

Phase 1. The compiled-in bootstrap: root writability, the remaining virtual filesystems, the persisted random seed, the local machine ID, the clock, registryd, boot-time path provisioning, and infrastructure setup. No registry access happens before registryd is serving.

Phase 2. The registry-driven boot: read the service definitions, build and validate the dependency graph, and start the boot-triggered services in dependency order.

ErrorControl. The per-service policy for an irrecoverable failure. Normal leaves the service Failed; Critical syncs the filesystems and reboots.

Token. The per-thread KACS identity object — a user SID, group SIDs, a privilege bitmask, an integrity level, and metadata. Tokens are the sole identity mechanism: peinit sets no UIDs, GIDs, or Linux capabilities on service processes. Peios Kernel TRM §3.2.

Security Descriptor (SD). The KACS structure controlling access to a securable object. peinit evaluates three kinds: a ServiceSecurity descriptor per service, controlling who can manage it; its own control descriptor, controlling system-level operations; and a descriptor per submitted job, controlling who can observe, stop or signal it. Peios Kernel TRM §3 and PCDS §5.

AccessCheck. The KACS function that evaluates a token against a descriptor to produce a decision. peinit calls it for every control request. Peios Kernel TRM §3.8.

Per-service SID. A SID under authority S-1-5-80 derived deterministically from the service name, carried in the group list of every service token. Two services running as the same principal are still distinguishable to an access check. §4.4.

registryd. The userspace registry source daemon serving the persistent hives. peinit starts it in Phase 1 from a compiled-in definition and treats it as opaque thereafter. Its implementation is loregd, a distinction visible only in recovery mode.

Registry. The configuration system LCS and its sources provide together. peinit reads service definitions from Machine\System\Services\, boot configuration from Machine\System\Boot\, and its own parameters from Machine\System\Init\.

KMES. The kernel-mediated event subsystem. peinit emits its structured events — job and operation lifecycle, audit records — into its ring buffer, where they survive eventd restarts and reboots. Peios Kernel TRM §2.

pidfd. A descriptor referring to one specific process, obtained atomically at fork through clone3(CLONE_PIDFD). Every process peinit supervises is tracked by one, which is what makes supervision immune to PID reuse.

cgroup. peinit uses cgroups v2 for process tracking and clean kill only — not for resource accounting or limits. Every service gets its own tree under /sys/fs/cgroup/peinit/, and every submitted job one under /sys/fs/cgroup/peinit/jobs/. §5.1.

sd_notify. The datagram protocol services and submitted jobs use to report readiness, status, progress, keepalives and stored descriptors, over the socket named by NOTIFY_SOCKET. Specified in PSPU §4.

TCB. The Trusted Computing Base: the kernel, KACS, LCS, KMES, peinit, registryd, authd, lpsd, and eventd. A compromise of any of them compromises the system.

1.4 Compatibility and Prior Art

Peios / Reference / peinit / Introduction

peinit is not a port or a reimplementation of anything. The choices that give it its shape — identity as a token, configuration in the registry, operations as objects, jobs as observable executions — were made for Peios. But several interfaces deliberately match existing conventions, because the convention is good and breaking it buys nothing.

1.4.1 sd_notify #

peinit speaks systemd's sd_notify datagram protocol: a service reports readiness, keepalives, status, and stored descriptors by sending KEY=VALUE lines to the socket named in NOTIFY_SOCKET. Existing software that supports sd_notify works unmodified.

The compatibility is not total. MAINPID= is not supported, because peinit does not supervise forking daemons — it tracks the process it forked through a pidfd, and there is no way to redirect supervision somewhere else. BUSERROR= is not supported because Peios has no D-Bus.

The protocol as peinit speaks it, including which fields it accepts and how a sender is authenticated, is specified in PSPU §4.

1.4.2 The fd store #

FDSTORE=1, FDNAME=, FDSTOREREMOVE=1 and FDPOLL=0 work as they do under systemd, and descriptors come back to a restarted service at fd 3 onwards with LISTEN_FDS and LISTEN_FDNAMES set. A daemon written to survive a restart without dropping its listening sockets keeps working.

1.4.3 Calendar expressions #

Timer schedules use systemd's OnCalendar format, including weekday names, lists, ranges, repetition, the ~ last-day-of-month form, IANA timezone suffixes and the named shortcuts. §9.1 gives the grammar peinit actually parses; the one deliberate subtraction is sub-second precision, which service scheduling has no use for.

1.4.4 Service #

The service model owes its architecture to the Windows SCM: services as securable objects carrying their own descriptors, identity as a token rather than a user account, an access-controlled control interface, and a structured state machine. The debt is architectural. peinit implements none of the SCM's RPC protocol, none of its service types, and none of its control codes.

1.4.5 What is deliberately absent #

There is no systemd unit file support: no reader, no parser, no generator, no migration path. Service definitions are registry keys. Roles are how a package declares them.

There is no socket activation in the systemd sense — peinit does not listen on a service's behalf and hand it a connection. The fd store covers the case that matters, which is a service keeping its own listener across its own restart.

There is no resource control. peinit uses cgroups for tracking and for clean kill, and sets RLIMIT_NOFILE and RLIMIT_CORE if a definition asks, but it does not do accounting, slices, or limits.

1.4.6 Features that belong to other components #

ConcernComponent
Authentication and token mintingauthd
The local identity databaselpsd
Log storage, indexing, and querieseventd
Registry storageregistryd, over LCS
Packaging and installationpeipkg and the role system
Device managementeudev
Network configurationa dedicated service
File access control enforcementFACS

1.5 Service Manager Boundaries

Peios / Reference / peinit / Introduction

These design notes explain the boundaries behind the operator workflows. The implementation chapters specify each mechanism in detail.

1.5.1 peinit in one sentence #

peinit is the sole service manager and PID 1 — it reads service definitions from the registry, starts them in dependency order under per-service identities, supervises them through a defined state machine, and tears them down in reverse at shutdown.

Everything in this topic is an elaboration of that sentence: what a service definition is, what dependency order means, what the state machine looks like, how identity is materialised, and how you drive the whole thing from a shell.

1.5.2 Three kinds of object #

peinit is easiest to understand through the three first-class objects it works with. Keeping them straight is most of the battle when you read a status output or an event log.

ObjectWhat it isLifetime
ServiceA definition — a named unit of execution with identity, policy, and configuration, stored in the registry. It has a runtime state (the state machine) and, when running, a process.Long-lived. Persists across restarts and reboots.
JobA single process execution. Every time peinit forks — a service's main process, a hook, a health check, a submitted job — that is one job, with its own GUID and exit result.Short-lived. A restart creates a new job.
OperationA requested action on a service — start, stop, restart, reload, reset. Control commands create operations that are validated, queued, and executed.Short-lived. Resolves to a terminal state, then is dropped.

A service is the what; a job is what actually ran; an operation is what someone asked for. A single restart command, for example, is one operation, which stops the current job and starts a new one, all against one service. Jobs and operations both carry GUIDs and are emitted to eventd as they complete, which is how the history of a service is reconstructed after the fact. They get their own page: Jobs and operations.

Underneath all three sits the fourth thing peinit is always handling — the token, the identity a service runs under. Tokens are not peinit's invention; they are the system-wide identity object. peinit's role is to obtain the right token for each service and install it before the process runs. That is the subject of Service identity and privileges.

1.5.3 What peinit is not #

peinit borrows vocabulary from init systems you can already know, and the familiarity is a trap. Clearing three wrong mental models is most of understanding what peinit actually is.

It is not systemd. There are no unit files. peinit does not read, parse, or translate .service files, and there is no migration shim. A service definition is a key in the registry under Machine\System\Services\, made of typed registry values — not a text file under /etc. Some interfaces are deliberately compatible where that helps: peinit speaks the sd_notify readiness protocol, and timer schedules use systemd's OnCalendar calendar-expression format. The compatibility stops at those wire formats; the model underneath is different.

It is not Windows SCM. The influence is real — services as securable objects with per-service descriptors, token-based service identity, an access-controlled control interface, a structured state machine — but it is architectural, not interface-level. peinit does not implement the SCM RPC protocol, Windows service types, or Windows control codes.

It is not a logging system. peinit holds a service's stdout /stderr pipes at birth, so it controls where output goes — but storage, indexing, and queries are eventd's job. peinit forwards; eventd is the historian. The same split applies to job and operation history: peinit emits structured events and forgets them; eventd keeps them. See Service output and logging.

A fourth, smaller correction: peinit does not supervise forking daemons. A service that double-forks to "daemonise" is solving a problem that does not exist when the manager tracks the process it spawned. peinit tracks every process by pidfd; a legacy binary that insists on double-forking must be wrapped at the package layer.

1.5.4 The one operational invariant #

peinit is single-threaded PID 1, and that one fact explains a surprising amount of its design. In a single-threaded PID 1, a blocking system call blocks everything — child reaping, watchdog expiry, shutdown signals, every other event stops while the call is stuck. So peinit's hard rule is that its event loop never blocks on a userspace service.

Two consequences you will meet repeatedly:

  • peinit operates on an in-memory snapshot of the registry, not a live view. It reads service definitions at boot and on configuration reload, and thereafter works from an in-memory model that it updates from change notifications. Supervision never waits on the registry being available. This is why a configuration change does not always take effect immediately — see Defining a service.
  • Anything that could block is pushed off the main loop. Filesystem condition checks run in a short-lived forked helper rather than a stat() on the event loop; token requests to authd are driven by a timed state machine, not a blocking call; log delivery is best-effort and never exerts back-pressure on peinit.

You do not need to think about the event loop to operate peinit, but it is the reason behind several behaviors that would otherwise look arbitrary.

1.5.5 Where peinit sits in the system #

peinit is part of the Trusted Computing Base: a compromise of peinit is a compromise of the whole machine. It runs as SYSTEM with all privileges, and it never drops that identity. It depends on, and is depended on by, the other TCB components:

peinit relies onFor
KACSService identity (installing tokens on children), control-interface authentication (peer token + AccessCheck), and per-service access control. See Access decisions.
LCS / the registryService definitions, boot configuration, and its own parameters. See The registry.
registrydThe registry source daemon — the first service peinit starts. peinit treats it as an opaque dependency. (registryd is an interface; the default implementation is loregd — see Boot and boot modes.)
authdMinting tokens for non-platform services. peinit requests; authd mints.
eventdService logs (forwarded over a socket) and job/operation/audit events (emitted through KMES).
KACS, againConveying a job identity: when a process submits a job over peinit's jobs socket and attaches a token, the kernel gates the attach — so peinit can run a program as a service's client without ever judging the identity itself. See Jobs and operations.

The bootstrapping puzzle — authd needs the registry, the registry needs to be started by something, and that something is peinit running before any of them exist — is resolved by the boot model in Boot and boot modes.

1.5.6 How a token is materialised #

The Identity field decides where the token comes from:

Identity valueToken source
SYSTEMMinted by peinit from its own SYSTEM identity.
Any other principal name or SIDRequested from authd.
Absent or emptyauthd, defaulting to LocalService.

1.5.6.1 The SYSTEM path #

For a SYSTEM service, peinit mints an independent SYSTEM token using its own token as the template: it reads its own identity (user SID S-1-5-18, the group list, the privilege set) and mints a fresh primary token with the same identity, adding the service's per-service SID. The minted token is fully independent — the privilege trimming that follows affects only this token, never peinit's.

This path exists because of a bootstrapping problem: the platform services that make the normal token flow possible cannot use it, because they have to start before it exists. registryd and authd use this bootstrap path during boot. Standard eventd and lpsd deployments now use Identity=Service, take the authd path, and start after authd (§4.2).

Note

There is no allow-list restricting which services can be SYSTEM. The security boundary is the registry key descriptor on Machine\System\Services\ — an administrator who can create service definitions is already trusted to assign any identity, so a second gate would add nothing. The dangerous case is never implicit, though: SYSTEM must be written out explicitly; an empty Identity defaults to the minimal LocalService, never to SYSTEM.

1.5.6.2 The authd path #

For any other identity, peinit asks authd for a token: it sends the Identity value verbatim, and authd routes it to the right source —

  • Well-known principals (LocalService, NetworkService, …) → a built-in identity with a predefined minimal privilege set;
  • Local service accounts → lpsd, the local principal store;
  • Domain accounts → the directory connector;

— resolves the principal's SIDs, mints a token, creates a logon session, and hands the token back to peinit to install. peinit neither knows nor cares whether the identity is local or domain; routing is authd's job.

authd records each request as an authd.service.attested event: the service (object.service.name), the identity it got (object.token.sid), its session and the privileges policy granted it. A refused request is recorded too, with the reason, such as account-restricted for an identity that can not be used for a service logon. The event is standard, so the emission policy can switch it off on a machine that restarts services often.

Important

Every non-SYSTEM service start depends on authd. peinit interacts with it over a non-blocking, timed channel — if authd is unreachable or unresponsive, the service start fails rather than hanging PID 1. A broken authd therefore prevents non-SYSTEM service starts, including any platform service configured that way, while SYSTEM-minted services do not need this request. The authd interface is ServiceAttest on /run/logon.sock, specified in PGSS §2.19 and used through libauthd (§4.3).

1.5.7 The per-service SID #

Every service token — minted or authd-issued — carries a per-service SID in its group list. It uses authority S-1-5-80 and is derived deterministically from the service name: the SHA-1 of the uppercased name (as UTF-16LE), with the digest split into five sub-authorities. authd adds it automatically for the tokens it mints; peinit computes and adds it itself for SYSTEM tokens, no authd involvement needed.

The point of the per-service SID is fine-grained access control even when services share an identity. A dozen services might all run as LocalService , but each has a unique service SID, so an ACL can grant access to exactly one of them without inventing a dedicated account. It also keeps services configured as SYSTEM distinguishable to AccessCheck. See Well-known principals for the SID landscape this fits into.

1.5.8 A clean context #

A service inherits only what peinit explicitly hands it — its standard streams and any stored file descriptors. Every other descriptor peinit holds — the control socket, the notify socket, the event-loop fd, the registry, and authd and eventd connections — is opened close-on-exec, so it closes automatically at exec and can never leak into a service. peinit also resets the child's signal state to defaults (it runs with all signals blocked for its own signalfd; a service must not inherit that). The guarantee is that a service starts from a clean slate, not from peinit's privileged one.

1.5.9 The cgroup tree #

Every service runs in its own cgroup tree under /sys/fs/cgroup/peinit/, with separate sub-cgroups for the main process, hooks, and health checks:

/sys/fs/cgroup/peinit/<service>/
                       ├── main/     the main process
                       ├── hooks/    pre/post hooks
                       └── health/   health checks

peinit uses cgroups for two things only: tracking every process a service spawns (so a child that forks its own children is still accounted to the service), and clean kill (terminating the entire tree at once, so nothing is orphaned). It does not use cgroups for resource accounting or limits.

The split into sub-cgroups serves a real purpose: it satisfies cgroup v2's "no internal processes" rule, and it lets peinit kill a service's hooks or health checks without touching the main process.

When an old tree cannot be removed — because a process survived SIGKILL in D-state and leaked it — peinit creates a fresh generational tree (<service>.gen<N>) for the next start, so a stuck old instance never blocks a new one. Leaks are surfaced in the service's warnings; they are a sign of an underlying I/O fault, covered in Keeping services running.

2.1 The Initramfs Contract

Peios / Reference / peinit / Boot

peinit starts with the root filesystem already assembled. Everything that makes a root mountable — LUKS decryption, LVM activation, RAID assembly, any filesystem check — belongs to the initramfs and has happened before peinit exists. peinit performs no root assembly, no decryption, no repair, and no fsck, and it does not assume one has been done.

2.1.1 The handoff #

The initramfs transfers control by chroot -ing into the assembled root and exec'ing peinit there. Not switch_root, and not pivot_root: the kernel refuses to relocate onto the initramfs rootfs, so that route is closed. The consequence is that the initramfs rootfs does not go away. It remains the mount-namespace root — emptied, and unreachable from peinit's view, but present. peinit therefore never assumes a clean single-root mount topology, and never attempts pivot_root.

peinit is installed in package storage at /usr/bin/peinit2 and reached through the fixed runtime path /bin/peinit2. The boot-image tooling sets the kernel init= to the runtime path. Before the transfer, the initramfs has assembled the base StrataFS topology, including the /bin and /sbin views, because peinit reaches every binary it execs through them.

At handoff:

  • the real root is mounted read-write at /;
  • /proc, /sys, and /dev are mounted and have been moved into the real root;
  • the environment holds TERM and nothing else, and argv is peinit's own path.

The read-write requirement is registryd's, not peinit's. loregd's storage backend needs to write its write-ahead log and shared-memory files even to answer a read, so a read-only root cannot support Phase 2 at all. Delivering the root writable is the initramfs's job; peinit only confirms it.

peinit inherits nothing from that environment. It does not rely on having been given anything, and it does not pass its own near-empty startup environment through to services — the environment a service receives is constructed from scratch (§5.5).

2.1.2 What stays outside #

Non-root storage is not peinit's concern. Data partitions and additional filesystems are mounted at the services layer, typically by a Oneshot service that runs mount. peinit has no mount feature beyond the fixed Phase 1 set.

Note

The initramfs itself is assembled by mkirf from hook scripts that packages contribute; mkirf resolves the ordering and bakes the sequence its PID 1 runs. What peinit depends on is the handoff contract above, not how the initramfs arranged to satisfy it.

2.2 Bootstrap Identity

Peios / Reference / peinit / Boot

The steady-state identity flow is: peinit asks authd for a token, authd mints it, peinit installs it on the child. That flow cannot start the system, because authd needs a token of its own, and registryd has to be running before it. The bootstrap model breaks the circle.

2.2.1 Platform services run as SYSTEM #

A service whose definition says Identity=SYSTEM gets a token peinit mints from its own, with kacs_create_token (§4.2). No authd interaction is involved — which is the point, since authd does not exist when the first of these services starts.

Two services use it:

ServiceWhy
registrydStarts before authd exists at all.
authdNeeds SeTcbPrivilege and SeCreateTokenPrivilege; it is the minter for everything else.

lpsd and eventd used it too, until each moved to an account of its own (Identity=Service). Both now require authd, start after it, and take the authd path like any other service.

Nothing restricts which services can declare Identity=SYSTEM.

There is no allowlist, because an allowlist would be enforcing a boundary that is already enforced somewhere better: the Security Descriptor on Machine\System\Services\. Anyone who can create a service definition is by definition trusted to choose its identity, and adding a second list to maintain would only create a way for the two to disagree.

Every SYSTEM token peinit mints carries the service's per-service SID in its group list, computed by peinit itself from the service name (§4.4). That is what keeps platform services distinguishable to an access check despite all of them running as S-1-5-18.

Note

This is the same arrangement Windows uses: the SCM, LSASS, and the core platform services all run as LocalSystem. The trust anchor is that peinit is SYSTEM, and the kernel guarantees that by handing PID 1 the boot token.

2.2.2 After authd #

Once authd is running, every subsequent service gets its token through the ordinary authd flow (§4.3). A definition with no Identity field defaults to LocalService — a well-known principal with a minimal privilege set  — and authd adds the per-service SID to the token it mints.

2.3 Phase 1

Peios / Reference / peinit / Boot

Phase 1 is compiled into peinit. It does not change at runtime and has no registry dependency, because its whole purpose is to reach the point where a registry exists. It does the minimum needed to make Phase 2 possible, and most of its failures are fatal to the boot.

2.3.1 Step 1: Confirm the root is writable #

The initramfs delivers the root mounted read-write. peinit does not remount it — mount flags belong to the initramfs, and a redundant remount of an already-writable or overlay root can fail for reasons that have nothing to do with the root being usable.

Instead peinit probes. It creates /.peinit/ if it is absent, writes a uniquely named file there — the name is derived from peinit's own PID and a namespace identifier, so two probes cannot collide — writes to it, and removes it. If any part of that fails, the root is not usable for Phase 2 and peinit enters recovery mode.

2.3.2 Step 2: Mount what is missing #

/proc, /sys, and /dev are already mounted. peinit does not blindly mount them again: a redundant mount stacks a second filesystem over the populated one, and on some kernel and flag combinations returns EBUSY instead.

peinit reads /proc/self/mountinfo to find out what is already there, and mounts only what is not:

Mount pointFilesystemFlagsProvided by
/procprocnosuid, nodev, noexecinitramfs
/syssysfsnosuid, nodev, noexecinitramfs
/devdevtmpfsnosuidinitramfs
/dev/ptsdevptsnosuid, noexecpeinit
/dev/shmtmpfsnosuid, nodevpeinit
/runtmpfsnosuid, nodevpeinit
/sys/fs/cgroupcgroup2nosuid, nodev, noexecpeinit
/sys/kernel/securitysecurityfsnosuid, nodev, noexecpeinit

Each mount(2) passes the filesystem name as both the source and the filesystem type, passes only the listed flags, and passes null mount data. Mount points that do not exist are created first.

/dev/pts additionally gets a KACS mount policy immediately after it is mounted : SYNTHESIZE_EPHEMERAL, with a template descriptor granting SYSTEM and Administrators full control and Authenticated Users read, write and traverse. devpts cannot store security descriptors, and its terminal endpoints are materialised by the kernel when a terminal opens /dev/ptmx — never through a create path that could stamp or inherit one — so under the default DENY_MISSING every pseudo-terminal on the machine is unopenable. The policy is set through SYS_KACS_SET_MOUNT_POLICY on an O_PATH descriptor of the mount point. The template applies to every SD-less inode of the mount alike, so any authenticated principal can open any terminal endpoint. Per-owner endpoint descriptors need kernel support for stamping the opener's identity at materialisation, and are recorded as future work, not provided here.

/sys/kernel/security gets the same kind of policy, for the same reason: securityfs cannot store descriptors either. Its template grants SYSTEM full control and Authenticated Users read and traverse :

O:SYG:SYD:(A;;GA;;;SY)(A;;GRGX;;;AU)

KACS publishes kacs/self and kacs/sessions there (see Logon sessions), and each makes its own check when read, so opening sessions is allowed to anyone signed in while reading it stays with Administrators and SYSTEM. Only SYSTEM can write: lockdown is the one writable file on the mount, and raising the kernel's lockdown level is not routine administration.

There is a bootstrap wrinkle in reading mountinfo at all: the file lives in /proc, which is one of the things being checked for. If the read fails with ENOENT or ENOTDIR, peinit mounts /proc from the table and retries. Any other failure to read or parse mountinfo sends peinit to recovery.

For the three initramfs-provided rows, an already-mounted filesystem is success, and so is an EBUSY from an attempted mount. For the five peinit owns, a mount failure sends peinit to recovery.

After successful mount setup, peinit ensures /run/lock exists as a directory. Mounting /run hides the directory shipped by fsbase, so peinit recreates it in the live filesystem before starting services. A newly created directory inherits /run's descriptor; an existing directory is preserved. This step also runs when /run was already mounted. A creation failure enters recovery.

2.3.2.1 Seeding descriptors on the new filesystems #

Three of the five filesystems peinit mounts are fresh and empty: /dev/shm, /run, and /sys/fs/cgroup. Under KACS an inode with no Security Descriptor is denied to every caller, and there is nothing on a newly mounted tmpfs for a new inode to inherit from — so peinit stamps the mount root with a descriptor that grants SYSTEM and Administrators full control, inheritable by both containers and objects, and grants Everyone read and execute, inheritable by containers only:

O:SY G:SY D:(A;OICI;GA;;;SY)(A;OICI;GA;;;BA)(A;CI;GRGX;;;WD)(A;OICIIO;GA;;;S-1-3-0)

Everything created underneath — the notify socket, per-service runtime directories, the cgroup hierarchy — inherits from it; the two sockets that need a different population are stamped explicitly in step 9. This is why peinit never sets mode bits on the sockets it creates; under KACS they would mean nothing, and the descriptor is the thing that does the work. It is the same descriptor the initramfs seeds onto the root filesystem but for the inheritance flags on that last ACE, and the two are kept in step on purpose: this one inheritable ACL is, in practice, the access policy of everything under these mounts, so an ACE missing here is missing from every per-service directory under /run/services.

The Everyone ACE grants execute as well as read because on Peios execute is traverse — FILE_TRAVERSE and FILE_EXECUTE are the same bit — and an explicit chdir is the one traversal that does not get the SeChangeNotifyPrivilege bypass. A service running as anything other than SYSTEM cannot otherwise reach its own runtime directory. SYSTEM and Administrators keep GenericAll rather than read/write/execute because GenericAll carries WRITE_DAC, WRITE_OWNER and DELETE, and peinit re-stamps descriptors throughout /run.

The last ACE is CREATOR OWNER, and it is what makes the container-only Everyone ACE survivable. A file created under these mounts inherits the SYSTEM and Administrators ACEs and nothing else — and that is a non-empty DACL, so the creating token's default DACL is never consulted. Without it a service would create runtime state it could not read back. It is inherit-only, so it grants nothing on the directory it sits on; it is resolved against whoever creates each object, and carried onward down each container.

The Everyone ACE is inheritable by containers only, which is the one place this descriptor differs from the root filesystem's. What a service needs here is to walk to its own directory, and container inheritance gives it that by itself. Object inheritance would additionally put Everyone-read on every file anything creates beneath these mounts — a service's runtime state, and shared memory segments, readable by any principal through inheritance alone. The root filesystem needs object inheritance because a service has to read and execute the binaries beneath it; nothing under these three mounts is a binary.

This descriptor is not the one prelude's seed-sd writes by default. That one is narrower, and stays narrower: it also stamps /dev, where every ACE is inherited by the next hot-plugged block device, so a read ACE for Everyone there would be every filesystem descriptor on the machine bypassed by opening the raw disk.

Failure to apply the descriptor sends peinit to recovery. Without it every file peinit later creates on that filesystem would be unreachable to everything, including peinit.

/proc, /sys, and /dev are not stamped: they arrive from the initramfs already populated.

2.3.2.2 Device node policy #

/dev arrives with that same inheritable descriptor on its root and on every node, which is the right default — whatever the root grants, a disk hot-plugged later inherits, so the root must be acceptable on a raw block device — but it leaves /dev/null unusable by anyone who is not an administrator. A single inherited descriptor cannot say "/dev/null for everyone, the disks for administrators", so peinit enumerates the exceptions. Once the mounts are up it stamps each of these nodes with a descriptor of its own:

NodeDACL
/dev/null, /dev/zero, /dev/full, /dev/random, /dev/urandom, /dev/tty, /dev/ptmxD:(A;;GA;;;SY)(A;;GA;;;BA)(A;;FRFW;;;WD)

Everyone can open the node for reading and writing and can stat it; nobody but SYSTEM and Administrators can change its descriptor. Only the DACL is replaced — owner and group stay as the seed left them  — and the ACEs carry no inheritance flags, because a device node has no children. /dev/console is deliberately not on the list: it is the SYSTEM console.

The step is advisory. A node that cannot be stamped is reported as a warning and stays on the inherited default, usable by administrators and denied to everyone else; a node that does not exist is noted and skipped. Neither sends peinit to recovery.

2.3.3 Step 3: Restore the persisted random seed #

peinit restores the seed at /var/state/peinit/random-seed once /dev is available and before registryd starts. The seed is a machine-local entropy cache for the kernel CSPRNG. It is not configuration, and shipping one in a packaged image, live ISO or VM template would hand every instance of that image the same starting entropy.

If the file is absent, that is an ordinary first boot or a stateless live boot, and peinit continues silently. When a seed is present peinit mixes it into the kernel pool, preferring the interface that credits entropy for a locally persisted seed; if that fails it mixes the bytes without crediting and records the failure. A seed file that is empty, or larger than 4096 bytes, is treated as an error.

Nothing in this step can send peinit to recovery. A system with no entropy cache still boots; it starts with less entropy, which is a problem for the image builder to solve with a hardware or virtio RNG rather than with a seed baked into the image.

The initramfs can perform the same restore earlier, once the persistent root is mounted. peinit's restore stays as the fallback for initramfs images that do not participate and for boots that have no initramfs.

2.3.4 Step 4: Ensure the local machine ID #

/lcl/etc/machine-id holds a stable local install identifier used for software compatibility, log correlation and instance identity. It is not a security principal: not a credential, not a SID, not an account, and not an input to any authorization decision.

The format is 128 bits as exactly 32 lowercase hexadecimal characters followed by one newline. A valid existing file is left alone. A file that is absent, empty, all zeroes, the wrong length, not hexadecimal, or missing its trailing newline is replaced : peinit draws 128 bits from the kernel CSPRNG and writes a valid file atomically, through a temporary file and a rename, with the result flushed.

The write creates /lcl/etc/ if it is not there. This step runs before the path-provisioning machinery of step 7, and /lcl is a StrataFS view the initramfs assembled, so whether the directory exists is a property of the image rather than something peinit can assume.

Only a CSPRNG failure sends peinit to recovery. If the kernel cannot produce random bytes, nothing else on the machine can be trusted either.

An unreadable file or an unwritable path does not. The boot continues with an identifier valid for this boot only, and says so :

peinit warning: machine-id not persisted (<reason>); using an identifier
for this boot only

A read failure takes the same path as finding no file, because it leaves peinit in the same position — unable to say whether a valid identifier is on disk. It is reported rather than treated as a clean generation, because it can have replaced something valid.

This is deliberately fail-soft. The identifier is a local opaque install ID and not an authorization input, so failing a boot over it would be disproportionate — and an ephemeral ID is already the defined behavior for a stateless live boot.

Images and templates are expected to ship with no machine ID, or with an empty file as a reset marker. Clone tooling that wants a new identity removes or truncates the file and lets the next boot generate one. Stateless live boots without a persistent overlay get an ephemeral ID for that boot.

2.3.5 Step 5: Set the clock from the hardware RTC #

peinit reads the hardware clock and calls clock_settime() before registryd starts, so that timestamps on registry operations, log entries and the boot attempt counter mean something.

It opens /dev/rtc, falling back to /dev/rtc0 if that device is absent , and reads it with RTC_RD_TIME. The returned struct rtc_time is interpreted as UTC and converted to CLOCK_REALTIME seconds with zero nanoseconds.

Every failure in this step sends peinit to recovery: no openable RTC device, a failed read, a value that is invalid or before the Unix epoch, a failed clock_settime, and — deliberately — a failure to close the descriptor after a successful read. Leaking a descriptor in PID 1 during bootstrap is a symptom of something being badly wrong, not a detail to swallow.

Note

NTP corrects the clock properly later in the boot. This step only gets it into the right decade, so that early timestamps are not absurd and the timer subsystem has a wall clock to anchor to.

2.3.6 Step 6: Start registryd #

peinit holds a compiled-in definition for registryd — the only compiled-in service definition there is :

FieldValue
ImagePath/sbin/registryd
ArgumentsMachine=/var/state/loregd/Machine.hive, Users=/var/state/loregd/Users.hive
IdentitySYSTEM
ReadinessNotify
ErrorControlCritical

The hive paths are peinit's choice, not registryd's: where the machine registry lives is a boot-policy decision, and it is made here because this is the one service start that cannot consult configuration.

peinit mints a SYSTEM token including registryd's per-service SID, creates the cgroup tree, forks with the token installed, and execs /sbin/registryd through the runtime StrataFS view. Two separate timeouts bound the start, both 30 seconds: one on process setup, driven synchronously because there is no event loop yet, and one on readiness.

registryd's READY=1 means "accepting and serving registry requests", not "the process is alive" — it does not signal until its storage backend is open, its schema is validated and it can answer a read.

2.3.6.1 The schema-version guard #

After readiness, peinit ensures the base registry structure exists and then probes it. Ensuring comes first: peinit creates Machine\System, Machine\System\Services and Machine\System\Init if they are absent and stamps Machine\System\Services\SchemaVersion with the current schema version, 1. Only then does it read the value back.

The read is what verifies registryd is genuinely serving. A value that is present but not a REG_DWORD, or that is a REG_DWORD of the wrong length, fails the probe. A key or value that is absent reads as zero and passes  — the structure was created, so absence at this point means the write did not take effect, and the failure that matters is the provisioning failure, which is reported directly.

The consequence is that the guard is self-healing. An unprovisioned first boot, or a registry cleared by the recovery tools, comes up with an empty Machine\System\Services\ and boots into a Phase 2 with no services rather than into recovery.

2.3.6.2 Keeping registryd #

When registryd passes readiness and the probe, peinit retains the activation as an ordinary runtime service instance: its state, its pidfd-tracked main process, its cgroup generation and paths, its output pipe ownership, its notify generation, its job identity, and any cleanup evidence. Ownership is not dropped at the Phase 2 boundary.

During Phase 2 the registry's own definition of registryd, if there is one, is merged onto the retained activation. peinit does not create a second inactive record and does not restart registryd because a definition has appeared. If the registry definition is absent or invalid, the ordinary graph validation rules apply.

If registryd fails to start, its readiness times out, or the probe fails, peinit enters recovery. There is no Phase 2 without a registry.

2.3.7 Step 7: Autorun scripts #

Between registryd starting and path provisioning, peinit runs every non-directory entry in /lcl/policy/autorun.d, in sorted order, by absolute path , with the working directory / and PATH=/sbin:/bin . Each runs under peinit's own SYSTEM token.

The step is fail-open at every point: a missing directory, an unreadable directory, a spawn failure, and a non-zero exit are all console warnings and none of them stops the boot. Its console output bypasses the quiet policy (§2.6), because a script that ran this early and went wrong needs to be visible.

The child's standard output and standard error share one pipe. peinit drains that pipe before waiting for the child, so a script can write more than pipe capacity to either stream without blocking behind an unread second pipe. Writes reach the captured stream in pipe order; the child's own buffering still controls when those writes happen. If reading fails, peinit attempts to terminate and reap the child before reporting the failure.

2.3.8 Step 8: Provision boot-time paths #

Covered in §2.4.

2.3.9 Step 9: Infrastructure setup #

Three things, before Phase 2 begins:

  1. The control socket at /run/services/peinit/control.sock, which serves every runtime command for the lifetime of the system, stamped so that any authenticated principal can connect and every command is then checked on its own (§10.1).
  2. The jobs socket at /run/services/peinit/jobs.sock, on which any authenticated principal can submit a job once Phase 2 runs, stamped so that connecting is the submission permission (§10.7).
  3. Loopback: peinit brings up lo over netlink, because services that bind 127.0.0.1 need it.

Either socket failing to bind or to take its descriptor sends peinit to recovery  — without the first there is no way to administer the system, and a jobs socket with the wrong descriptor is either unreachable or open to everything. A loopback bring-up failure is a warning that lets Phase 2 proceed.

2.3.10 Failure summary #

FailureResponse
Root writability probe failsRecovery
A mount point cannot be createdRecovery
A peinit-owned filesystem fails to mountRecovery
A mounted filesystem cannot be stamped with its descriptorRecovery
/proc/self/mountinfo unreadable or unparseableRecovery
/proc, /sys or /dev already mounted, or EBUSYTolerated as success
A device node in the policy list cannot be stampedWarning; node keeps the inherited default
A device node in the policy list does not existNoted; boot continues
Random seed absent, oversized, empty, or unrestorableWarning; boot continues
Machine ID generation fails (CSPRNG)Recovery
Machine ID unreadable, or unwritable at its pathWarning; boot continues with an identifier for this boot only
Machine ID absent, empty, or malformedRegenerated; boot continues
Any RTC or clock failureRecovery
registryd fails to start, or setup times outRecovery
registryd readiness times outRecovery
Base registry provisioning failsRecovery
Schema-version probe returns a wrong type or lengthRecovery
An autorun script is missing, unspawnable, or exits non-zeroWarning; boot continues
A provisioning entry is malformedWarning; entry skipped
An optional provisioned path failsWarning; boot continues
A required provisioned path failsRecovery
Control socket creation or stamping failsRecovery
Jobs socket creation or stamping failsRecovery
Loopback bring-up failsWarning; boot continues

2.4 Path Provisioning

Peios / Reference / peinit / Boot

Some filesystem objects belong to no single service. A directory two packages both write into, a state file created before anything runs, a path that has to exist with a particular Security Descriptor before the first service that uses it starts — none of these has an owner in the service model, and creating them from a service's pre-exec hook makes their existence depend on start ordering.

Boot-time path provisioning is the registry-backed answer, and the equivalent of the tmpfiles.d role elsewhere. peinit applies it after registryd is serving and before any Phase 2 service is planned or started.

2.4.1 Entries #

Each child key under Machine\System\Init\ProvisionedPaths\ is one entry. Unknown values on an entry are ignored.

ValueTypeRequiredDefaultMeaning
Kindstringyes—directory or file.
Pathstringyes—Absolute path to create or verify.
Securitybinarynobuilt-inThe Peios file Security Descriptor to apply.
Requireddwordno0If 1, failing this entry prevents Phase 2.

For Kind=directory peinit ensures the path exists as a directory; for Kind=file it ensures the path exists as a regular file. In either case a path that exists with a different file type fails the entry. An existing file is opened rather than created, so provisioning never truncates one.

peinit does not create parent directories. The parent is checked, and has to already be a directory. A package that needs a hierarchy declares each directory explicitly, or depends on the package that owns the parent — which keeps the ownership of every directory traceable to a package rather than to whichever entry happened to run first.

2.4.2 Descriptors #

When Security is present, peinit applies the supplied binary descriptor. A malformed or rejected descriptor fails the entry.

When it is absent, peinit applies a built-in default :

O:SY G:SY D:(A;;GA;;;SY)(A;;GA;;;BA)(A;;FR;;;BU)

SYSTEM and Administrators get full control; ordinary users get FILE_GENERIC_READ.

2.4.3 Failure #

Entries with Required=0 are fail-soft: peinit logs and continues. Entries with Required=1 are fail-closed: peinit logs and enters recovery before Phase 2 starts.

An entry that is malformed — a missing or unrecognized Kind, a missing or relative Path, a value of the wrong type — is logged as a warning and skipped, regardless of Required. Required marks a path as essential to boot; it does not make a broken entry more dangerous than a missing one.

2.5 Phase 2

Peios / Reference / peinit / Boot

With registryd serving, peinit reads the service graph and boots the system from it. Phase 2 is entirely registry-driven.

2.5.1 Reading the definitions #

peinit reads every key under Machine\System\Services\. The reads are bounded by LCS's request timeout: if registryd hangs mid-read, peinit receives ETIMEDOUT and enters recovery.

Decoding is per key. A definition that fails to decode — an invalid service name, a malformed trigger, an unclosed quote in a command, a registry: check naming an uncacheable key, a duplicate known field, an unrecognized value for an enumerated dword — fails that service, which is marked Failed with cause ValidationError. The boot proceeds with every other definition, and anything that depended on the failed service fails in turn through the ordinary dependency propagation.

peinit holds no definition for such a service, so the entry behind it is a placeholder: status reports it Failed with cause ValidationError, marked definition-removed (§3.8), with the decode error as its description. start, restart, reload and reset are refused with UNKNOWN_SERVICE, as for any definition-removed service. The placeholder leaves with its key: a reload-config that re-reads a repaired key restores the entry, and one that finds the key deleted discards it, since Failed does not retain a definition-removed entry.

Only services carrying a boot trigger are root candidates. A service with no triggers is demand-only and is not a root, though it can still be pulled into the boot transaction as somebody's dependency. A service with Disabled=1 is excluded from the boot graph entirely, but its definition is still loaded into the in-memory model so it can be started by hand later.

2.5.2 Building and validating the graph #

The boot graph is every boot-triggered root candidate plus the transitive closure of their Requires, BindsTo, and existing non-disabled Wants dependencies. Requires and BindsTo pull their target in even if the target has no boot trigger. Wants targets come in as best-effort members; missing or disabled ones are ignored. A missing or disabled Requires or BindsTo target blocks the dependent with cause DependencyFailure, and that blocking propagates.

peinit topologically sorts the graph and validates it before starting anything. The rules are in §7.2; the outcomes that matter here are:

  • A cycle fails every service in it. A cycle involving a Critical service downgrades the boot to Safe mode without rebooting.
  • An unresolvable conflict fails both services. Same downgrade if either is Critical.
  • A missing Requires target fails the dependent.
  • Warnings — a Readiness=Alive service with dependents that require it — are logged and do not prevent boot: a [ WARN ] peinit warning: line on the console and a peinit.graph.validation.warned event under phase boot, whether or not the same graph also has findings.

2.5.3 Starting #

peinit walks the graph and starts services, parallelising wherever the graph allows, up to a configurable limit:

KeyDefaultMeaning
Machine\System\Boot\MaxParallelStarts10Services starting concurrently.

An absent key uses the default. A value of zero, a type mismatch, or a malformed payload is invalid boot configuration and sends peinit to recovery  — running the scheduler with an effective limit of zero would hang the boot rather than fail it.

As each service reaches a dependent-satisfying state — Active for Simple, Completed for Oneshot with or without RemainAfterExit, Skipped for a service whose conditions did not hold — its dependents become eligible and join the start queue. A Oneshot without RemainAfterExit passes through Completed, releasing its dependents, and then goes Inactive.

Dependents blocked on a Requires or BindsTo target wait for that target to reach a satisfying state. Dependents blocked on a Wants target wait only for it to reach any terminal state, satisfying or not — which is what makes Wants ordering rather than dependency.

2.5.3.1 The typical order #

Nothing below is hardcoded. It falls out of the dependency graph that the standard role definitions produce, and an administrator who changes a dependency gets a different order.

  1. eudev — device management. SYSTEM, with RequiredPrivileges stripped to the minimum it needs. Starts before authd exists.
  2. lpsd — the local identity database. Depends only on registryd.
  3. authd — the identity authority. Depends on registryd and lpsd. Once it is ready, token minting is available.
  4. eventd — logging and audit. Services started before it sign in to peinit's pre-eventd buffer.
  5. Networking — the first service to receive a token from authd.
  6. Application services, in dependency order.
  7. Sign-in services, last, so the system is operational before it accepts a session.

2.5.3.2 The bootstrap matrix #

ServicePhaseIdentityToken fromReadinessErrorControl
registryd1SYSTEMminted by peinitNotifyCritical
eudev2SYSTEMminted by peinit, privileges strippedAliveNormal
lpsd2SYSTEMminted by peinitNotifyCritical
authd2SYSTEMminted by peinitNotifyCritical
eventd2SYSTEMminted by peinitNotifyCritical
networking2service tokenauthdNotifyNormal
sshd2service tokenauthdAliveNormal
application services2service tokenauthdper-serviceNormal

2.5.4 Deferred starts #

A service whose trigger is boot:settled is not part of the boot plan at all. It is not a root, it does not consume the parallel-start budget, it is not counted toward boot success, and it cannot block or delay anything. peinit starts it after the plan, once the boot has stopped moving.

"Stopped moving" is precise: every service in the plan — those that were started and those that were blocked — is in a state it will not leave without help. Active, Completed, Failed, Skipped, Abandoned, and Inactive all count as settled. Starting, Reloading, Stopping and Backoff do not, because a service between restart attempts is going to produce more output.

A deadline bounds the wait:

KeyDefaultMeaning
Machine\System\Boot\SettleTimeout5Seconds before deferred services start regardless.

The deadline is measured from the moment the plan was observed. An absent key uses the default; a type mismatch or a bad length sends peinit to recovery. Zero is legal and means "start on the next turn, settled or not".

Whichever comes first — the set settling or the deadline expiring — the deferred services start, once, each independently. A start that fails is recorded and dropped: one refusing service does not stop the others and does not affect the boot. The dispatch carries a flag saying whether the deadline expired rather than the set settling, so a service that cares whether the boot was still moving can be told.

Note

The motivating case is a console sign-in prompt being scribbled over by peinit's own progress messages. That is a scheduling preference, not a dependency — the prompt does not require anything to have started, it wants the console to itself. Expressing it as a dependency would mean naming every service that might print, which changes every time the system does.

2.5.5 Boot success #

A boot is successful once every Critical service has held a dependent-satisfying state continuously for a grace period:

KeyDefaultMeaning
Machine\System\Boot\BootSuccessGrace30Seconds of held health before the boot counts.

The criterion is satisfying, not Active. A Critical Oneshot reaches Completed and never reaches Active, so a test for Active would make such a service unable to ever mark a boot successful. Skipped counts too.

Success resets the boot attempt counter to zero (§2.7). The control socket's boot command says where a boot stands: which Critical services it is waiting for, or when it will count, or that it has (§10.8).

2.5.6 Failure summary #

FailureResponse
A service definition fails to decodeThat service Failed with cause ValidationError; the rest of the boot proceeds
A registry read times outRecovery
Invalid MaxParallelStarts or SettleTimeoutRecovery
A dependency cycleAll services in it Failed; Safe mode if any is Critical (see below)
An unresolvable conflictBoth Failed; Safe mode if either is Critical (see below)
A missing Requires targetThe dependent Failed
A Critical service fails during bootRestart budget, then reboot
A non-Critical service failsFailed; its Requires dependents fail; the rest continue
authd unavailable when a service needs a tokenThat service Failed

The two Safe-mode rows carry a caveat. When the downgrade fires, peinit rebuilds the graph in Safe mode and discards the Full-mode one, so the services that caused it are not marked Failed — they are never entered into the blocked set at all. What records them is the boot-level downgrade finding described in Boot modes.

2.6 Boot Modes

Peios / Reference / peinit / Boot

peinit boots in one of three modes, forming an escalation path from normal operation to last-resort maintenance.

Full boot ---+-- success ----------------> counter reset, operational
             |
             +-- cycle w/ Critical ------> Safe mode (no reboot)
             |
             +-- conflict w/ Critical ---> Safe mode (no reboot)
             |
             +-- Critical failure -------> sync + reboot --+
                                                           |
Safe boot ---+-- success ----------------> counter reset,  |
             |   operational (reduced)                     |
             +-- Critical failure -------> sync + reboot --+
                                                           |
                             counter increments <----------+
                                        |
                             counter >= N ---------> Recovery mode
                             Phase 1 failure ------> Recovery mode

2.6.1 Full mode #

The default. Every boot-triggered service starts in dependency order, as §2.5 describes.

2.6.2 Safe mode #

Safe mode starts a reduced set. Eligibility is a filter within the boot-triggered set, not a replacement for it: a service with no boot trigger does not auto-start in Safe mode whatever its SafeMode or ErrorControl says, and remains demand-only. Within the boot-triggered set, two categories are eligible:

  • Critical services (ErrorControl=Critical) start. If one fails, the ordinary Critical failure path applies — restart budget, reboot, counter increment, eventually recovery.
  • SafeMode=1 services are attempted best-effort. If one fails, Safe mode continues without it.

ErrorControl=Critical implies SafeMode, so a Critical service does not have to declare both.

2.6.2.1 What caused the downgrade #

The rebuild discards the Full-mode graph, so a service that forced Safe mode and is then excluded from the rebuilt graph is never entered into the blocked set and never marked Failed. That is deliberate: Safe mode was never going to start it, and a Failed state would say something about its own health that is not true. status should keep meaning "this service is broken".

A service that survives into the rebuilt graph gets no such protection. Two Critical services that require each other are both eligible in Safe mode, so the rebuild contains the same cycle and blocks them both, exactly as it would anywhere else — and there is no order that could have started either.

The reason is therefore recorded at boot level rather than per service. Every finding that forced the downgrade — each critical cycle, each critical boot conflict — is written to the console and emitted as a peinit.boot.downgraded KMES event naming the services involved, an essential type the emission policy cannot switch off.

All of them are reported, not only the first. A machine can be downgraded by a cycle and a conflict at once, and an operator who fixed only the one they were shown would reboot straight back into Safe mode.

They stay available for the rest of the boot: the control socket's boot command reports the mode, why, and every finding (§10.8).

peinit rebuilds the dependency graph from scratch using only the eligible services. Dependencies on excluded services are dropped: if A depends on non-Critical B and B is excluded, A's dependency on B does not exist in the Safe mode graph. This is what makes Safe mode useful — it is a graph in which the broken parts of the configuration are not present, rather than a graph in which they are present and failing.

A successful Safe boot resets the boot attempt counter.

Note

Safe mode is purely a boot-sequencing concern. Once booted, an administrator starts anything by hand exactly as in Full mode. It is for a system whose configuration is broken but whose TCB is healthy.

2.6.2.2 Entry #

  • A cycle involving a Critical service at boot. Graph validation detects it and peinit downgrades in place, without rebooting — the cycle is a configuration error, and rebooting would find it again.
  • An unresolvable conflict involving a Critical service at boot. Same reasoning.
  • peios.safemode=1 on the kernel command line.

Safe mode is not entered because a Critical service crashed at runtime. That follows the ordinary path: restart budget, reboot, counter increment, recovery.

2.6.3 Console output #

peios.quiet=N bounds what peinit writes to the console:

ValueBehavior
0Write unconditionally.
1Do not write to a terminal held as the controlling terminal of a running service, except to announce loss of the system. This is the default.
2Additionally drop ordinary progress everywhere, while still emitting errors.

The two rules are independent, and an error is never less visible at 2 than at 1. A terminal is matched by device rather than by path, since /dev/console and /dev/ttyS<n> can name the same device ; where the device cannot be determined, peinit treats the terminal as free and writes to it. Guessing wrong in that direction costs a scrambled line, which is recoverable; guessing wrong the other way costs the operator their console output at the moment the machine is least able to explain itself. Suppressed messages are discarded rather than buffered.

The autorun step (§2.3) bypasses the policy: a script that ran that early and went wrong is worth interrupting a sign-in prompt for.

2.6.4 Kernel command line #

ParameterEffect
peios.safemode=1Force Safe mode.
peios.recovery=1Force recovery mode regardless of the counter.
peios.bootattempts=NSet the recovery threshold; 0 disables the check.
peios.quiet=NConsole verbosity, as above.
peios.notifysocket=PATHOverride the notification socket path.

A malformed value is ignored in favor of the default rather than failing the boot. Nothing exists this early to report a diagnostic to.

2.7 The Boot Attempt Counter

Peios / Reference / peinit / Boot

The counter is what turns a repeated failure into an escalation. peinit keeps it at /.peinit/boot-attempts, as a plain decimal integer in a file on the root filesystem  — deliberately not in the registry, because the registry can be the reason the boot is failing.

2.7.1 The cycle #

peinit reads the counter at startup, before selecting a boot mode. The recovery threshold is evaluated against this pre-increment value, so a default threshold of 3 admits exactly three boot attempts before recovery.

  • Absent file: treated as 0.
  • Unreadable, empty, non-decimal, carrying trailing non-whitespace data, or overflowing the counter representation: recovery. A counter that cannot be read cannot be trusted to escalate.

peinit increments once per boot, after the root is known writable and before Phase 2 begins. Incrementing before the root is known writable would silently lose the increment on a read-only root and defeat escalation entirely.

The increment happens after the mount, seed, machine ID and clock steps rather than immediately after the writability probe, because reading the kernel command line requires /proc. One consequence is that a recovery entered from a mount failure, a machine ID failure, or an unreadable command line does not advance the counter.

A write failure — a full disk, say — is treated as a counter of 0 and the boot continues. A failure to record an attempt is not itself a reason to escalate.

The counter resets to 0 on a successful Full or Safe boot, after the grace period.

The control socket's boot command reports the count this boot began with, the threshold, and whether this boot has reset the counter yet (§10.8).

2.7.2 Recovery threshold #

The threshold is peios.bootattempts=N on the kernel command line, defaulting to 3. It is a command-line value rather than a registry one because the check runs in Phase 1, before registryd is serving.

peios.bootattempts=0 disables the check entirely — the escape hatch for a system whose counter is itself the fault.

peios.recovery=1 forces recovery without consulting the counter, but does not suppress the increment.

Note

The counter catches boots where peinit runs but the system never reaches health — a crash-looping Critical service being the usual case. It deliberately does not try to catch a peinit too broken to reach its own increment. Recovery mode is itself a peinit mode, so a peinit that cannot start cannot deliver recovery either, and a higher count could not help. That failure belongs to binary integrity, not to the counter.

2.8 Recovery Mode

Peios / Reference / peinit / Boot

Recovery mode is the last resort. There is no TCB guarantee and no degraded boot to speak of — it is a maintenance environment that hands the administrator an unrestricted SYSTEM shell on the console.

2.8.1 Entry #

  • The boot attempt counter reaching the threshold (§2.7).
  • peios.recovery=1 on the kernel command line.
  • Any of the Phase 1 failures listed in §2.3, most importantly a registryd that will not start or will not serve.
  • A Phase 2 registry read that fails or times out, or invalid boot configuration.
  • A required provisioned path that cannot be created or secured.
  • The runtime loop failing on an error about supervision itself: the event wait, event source registration, a listener, the event ring refusing even the small peinit.event.dropped, shutdown finalization. An error peinit can attribute to one service is contained to that service instead and does not enter recovery (§8.2).

2.8.2 What peinit does #

peinit records the reason as a peinit.recovery.entered KMES event — essential, so no emission policy switches it off — with the reason in outcome.reason and what went wrong, in the error's own words, in outcome.detail; a Phase 2 plan that would not build adds its finding as a peinit.graph.validation.failed under phase phase2-boot , then:

  1. Completes Phase 1 steps 1–5 if they have not been reached yet.
  2. Ensures the base registry structure exists, so the shell sees a normal layout even on a system that has never been provisioned.
  3. Attempts to start registryd. A failure here is ignored — recovery delivers a shell whatever registryd's state.
  4. Skips all Phase 2 services.
  5. Starts a shell on /dev/console from a compiled-in definition, with no registry dependency: /bin/recsh if it is present and executable, otherwise /bin/sh , running as SYSTEM with a fixed environment of PATH=/sbin:/bin, TERM=linux and HOME=/. peinit does not care where either binary comes from.
  6. Logs the failure reason to the console.

If the shell exits, peinit respawns it. Recovery never exits to an unmanaged PID 1.

If neither /bin/recsh nor /bin/sh can be exec'd, peinit cannot deliver a shell at all. It logs the reason to the console, syncs, and halts — PID 1 exiting would panic the kernel. A missing shell is a binary-integrity failure and sits outside the boot-attempt machinery's remit.

The shell receives /dev/console duplicated onto its standard streams, but peinit does not call setsid() or acquire a controlling terminal for it. The shell is not a session leader, so job control is not available in the recovery shell.

Step 1 runs on every entry. The steps are individually idempotent, so completing them and ignoring the failures is what "if they have not been reached yet" amounts to in practice — including the step that failed, which by the time the operator has a shell can well succeed.

Step 3 runs only if Phase 1 has not already reached its own registryd start, and it runs at most once. A recovery entered from a Phase 2, provisioning or runtime failure starts no registryd: Phase 1 already did, and its activation is retained for the runtime. A recovery entered from the registryd start failing also starts none — the attempt has been made, and a process can have forked before the failure was reported. In both cases a second daemon would bind over the first's notify socket, which succeeds rather than reporting EADDRINUSE because the bind unlinks the path first, and would then open the same hive files behind the first daemon's back.

Where recovery does start one, it uses the settings this boot parsed, so peios.notifysocket= and peios.quiet apply to it.

Note

Recovery mode is not a degraded boot; it is a maintenance environment. There are no security protections beyond what the kernel provides. The administrator has a SYSTEM shell and the corresponding responsibility.

2.8.3 Registry diagnosis and recovery limits #

Recovery provides a console maintenance shell when one is available as described above; it does not define an offline storage-repair interface for the registryd provider. Preserve the console failure reason and source startup output, then identify the deployed provider and version, its hive declarations, and the actual database paths. See LCS and sources.

Entering Recovery does not establish that the source is stopped. As explained above, a registryd started or attempted earlier in the boot can remain active. The loregd exit contract also permits a source to keep running after storage-operation failures. Do not launch a second source against the same hive files.

The source-checked loregd implementation takes one or more HiveName=DatabasePath declarations and rejects arguments without =. It has no offline inspection, backup-recovery, or database-clearing switches and does not create an automatic startup backup. Startup WAL recovery and orphan cleanup are not backup restoration or a database-corruption repair facility. The linked references pin these findings to the implementation revision checked; identify the installed provider and revision before choosing a recovery procedure.

Offline inspection, repair, or database replacement therefore needs a procedure supported by the installed provider and version. Establish the source's state and verify the existence and coverage of a recovery copy before planning a replacement. This manual supplies no offline stop, repair or replacement sequence. Role definitions can re-supply service configuration; they do not constitute a backup of every registry value.

The ordinary Backup and restore workflow is separate: LCS coordinates operations through a working source. Backup requires a read-only snapshot transaction; restore replaces a target subtree, including descriptors, in a read-write transaction. Neither is a way to repair a source that cannot serve those operations.

Note

/bin/recsh exists so a system can ship a purpose-built recovery shell — one that bundles the offline registry tools, presents guidance, or curates a command set — without making it mandatory. /bin/sh is the floor where it is absent. peinit treats both as opaque executables.

2.8.4 Remote recovery #

Recovery requires console access: physical, IPMI, or serial. Two post-v1 features address headless servers — rolling the registry back to a last-known-good state from the recovery shell, and an emergency sshd started without registry involvement.

3.1 Services

Peios / Reference / peinit / The Service Model

A service is the primary unit of management: a definition in the registry, a runtime state, a Security Descriptor, and at most one running main process. Definitions live under Machine\System\Services\<name>, where the key name is the service name. peinit reads them at Phase 2 boot and on an explicit reload-config.

3.1.1 Names #

A service name is 1 to 128 bytes drawn from [A-Za-z0-9._-]. Any other byte makes the name invalid.

Two exclusions are deliberate. / is out because names map directly onto cgroup identifiers (§5.1) and onto registry key names, and a name containing a separator would mean something different in each. : is reserved for peinit's own synthetic naming.

3.1.2 The two types #

3.1.2.1 Simple #

A long-running daemon. peinit forks, installs a token, and execs the binary; the process is the service. When it exits, the service has stopped. This is the default and covers nearly everything — registryd, authd, sshd, application services.

Readiness comes from the Readiness field. Notify, the default, waits for READY=1. Alive treats the process as ready the moment it exists.

The service goes Active on readiness and stays Active until the process exits or something stops it.

3.1.2.2 Oneshot #

A run-to-completion task: database initialization, a schema migration, a directory that has to exist. peinit forks, installs a token, execs, and waits for the exit.

Readiness is ignored. A Oneshot's readiness is always "it exited successfully", because READY=1 is meaningless from a process whose job is to finish. Success means exit code 0, or any code listed in SuccessExitCodes.

The differences from Simple are:

  • A successful exit goes to Completed. With RemainAfterExit=1 it stays there; without, it passes through Completed to release dependents and then goes Inactive.
  • A non-zero exit goes to Failed.
  • ExecStartPost runs after the successful exit rather than after a readiness signal, and does not run at all if the Oneshot failed.
  • StartTimeout covers the entire execution, from the first pre-hook to the process exiting.

RemainAfterExit matters when the Completed state itself is the useful information — so a status query shows a migration as finished rather than as inactive.

3.1.3 Forking daemons #

peinit does not support them. A service that double-forks to daemonise itself is working around a problem that does not exist when the service manager tracks the process it spawned, and peinit tracks its child through a pidfd obtained at fork. There is no MAINPID=, and no way to point supervision at a different process.

A legacy binary that insists on double-forking is wrapped by whoever packages it — a script with a --no-daemon flag, typically. That is a packaging concern.

3.2 The Definition Schema

Peios / Reference / peinit / The Service Model

Every field a service definition can carry, with its registry type and its default. The semantics of each are in the section named alongside.

Value names are matched case-insensitively, so ImagePath and imagepath are the same field  — and therefore a definition carrying both is a duplicate, not two fields.

FieldTypeDefaultMeaning
ImagePathstringrequiredAbsolute path to the service binary.
Argumentsmulti_string—Arguments passed to the binary.
Typedword0 (Simple)0 Simple, 1 Oneshot. §3.1
Triggersmulti_string—When the service starts automatically. §3.4
Disableddword0If 1, no trigger activates the service.
SafeModedword0If 1, attempt this service in Safe mode. Implied by ErrorControl=Critical. §2.6
IdentitystringLocalServiceSYSTEM, shared LocalService/NetworkService, Service for the service's own virtual account, or a designated principal. §4.1
RequiredPrivilegesmulti_string—Privileges to keep; all others are removed. §4.5
Requiresmulti_string—Hard dependencies. §7.1
Wantsmulti_string—Soft dependencies. §7.1
BindsTomulti_string—Runtime coupling. §7.1
Conflictsmulti_string—Mutual exclusion. §7.1
Providesmulti_string—Roles this service fills: virtual names a dependency can target (network), and that peinit derives edges to. A role is a bare name — the level in network:routed comes from the depending service's readiness requirement, not from this value. §7.6
OnFailurestring—Service to start when this one fails. §6.3
ErrorControldword0 (Normal)0 Normal, 1 Critical.
RemainAfterExitdword0Oneshot only: stay Completed after a successful exit.
SuccessExitCodesmulti_string—Non-zero exit codes treated as success.
ExecStartPremulti_string—Commands run before the main binary, sequentially. §5.3
ExecStartPostmulti_string—Commands run after readiness or successful exit. §5.3
HookIdentitystring—Principal for the hook processes. Falls back to Identity. §4.1
ExecReloadstring—Reload command, or signal:<NAME>. Absent means SIGHUP. §6.5
PreStartCheckTimeoutdword5Seconds before a filesystem check helper is killed. §3.5
StartTimeoutdword30Seconds for the entire start sequence. §5.3
StopTimeoutdword10Seconds after SIGTERM before SIGKILL.
WatchdogTimeoutdword0Seconds between expected WATCHDOG=1 pings; 0 disables. §6.6
HealthCheckstring—Command run periodically. Exit 0 is healthy. §5.6
HealthCheckIntervaldword30Seconds between health checks.
HealthCheckTimeoutdword5Seconds before a health check is killed and counted failed.
HealthCheckRetriesdword3Consecutive failures before the service is unhealthy.
RestartPolicydword1 (OnFailure)0 Never, 1 OnFailure, 2 Always. §6.4
RestartMaxRetriesdword5Consecutive restarts before Failed. §6.4
RestartWindowdword120Seconds of sustained health that reset the restart counter.
RestartDelaydword1Seconds before a restart; doubles each consecutive failure, capped at 60.
Readinessdword0 (Notify)0 Notify, 1 Alive. Ignored for Oneshot.
NotifyAccessdword0 (Main)Who can send notifications. Main is the only mode. §10.5
FdStoreMaxdword0Maximum descriptors held for the service; 0 disables the store. §10.6
TimerPersistentdword1Catch up a missed timer run after a reboot. §9.3
TimerJitterdword0Maximum random delay added to each firing. §9.4
Environmentmulti_string—KEY=VALUE pairs added to the environment. §5.5
WorkingDirectorystring/Working directory for the process.
TTYPathstring—Terminal to attach as the standard streams and controlling terminal. §5.4
TTYPrecedencedword0Who wins that terminal when several services want it at once. Higher wins. Refused without a TTYPath. §11.6
RuntimeDirectoriesmulti_string—Private directories under /run, created before the main process.
LimitNOFILEdword—RLIMIT_NOFILE.
LimitCOREdword—RLIMIT_CORE, in bytes.
Conditionsmulti_string—Start-time conditions; failure skips the service. §3.5
Assertsmulti_string—Start-time assertions; failure fails the service. §3.5
DisplayNamestring—Human-readable name for status display.
Descriptionstring—What the service does.
ServiceSecuritybinaryinheritDescriptor controlling runtime operations on the service. §4.6

3.2.1 Registry types #

Schema typeRegistry type
stringREG_SZ, UTF-8
multi_stringREG_MULTI_SZ, an ordered list
dwordREG_DWORD, 32-bit unsigned
binaryREG_BINARY

A value whose registry type does not match the field's is a decode error. So is a dword carrying a value outside an enumerated field's range.

3.2.2 Schema version and forward compatibility #

Machine\System\Services\SchemaVersion is a dword, 1. peinit creates it if it is absent (§2.3).

Unknown values on a service key are ignored, which is what lets the schema grow additively: a definition written for a newer peinit still loads on an older one, minus the fields it does not understand. A newer schema version does not prevent boot.

Known fields are the opposite. A known field appearing more than once in a collected definition is a decode error rather than a last-one-wins, because a definition that says two different things about the same field has no defensible reading. Since names match case-insensitively, this catches ImagePath and imagepath in the same key.

3.2.3 What a decode failure costs #

A definition that fails to decode fails that one service, and the answer differs by caller.

At boot the key is marked Failed with cause ValidationError and the boot proceeds with every other definition. Anything that depended on the failed service fails in turn through the ordinary dependency propagation (§7.4), so the cost is bounded by what actually needed it.

On reload-config the same: that service is Failed with cause ValidationError — or, if it is running, left running with its definition marked removed — and every other definition loads (§10.4).

3.3 Field Formats

Peios / Reference / peinit / The Service Model

Rules that apply to how a field's value is written, as distinct from what it means.

3.3.1 Strings #

A string field that is present is non-empty, unless this section says otherwise for that field. Three fields treat the empty string as absence:

  • Identity — empty is the same as absent, and defaults to LocalService.
  • HookIdentity — empty is the same as absent, and falls back to the service's Identity.
  • DisplayName and Description — empty is the same as absent.

WorkingDirectory, when present, is a non-empty absolute path. Whether it exists, is a directory, and is reachable is checked when the service starts, not when the definition is read.

TTYPath is checked for emptiness before absoluteness: an empty value means no terminal, and a non-empty relative path is rejected.

3.3.2 Identity and HookIdentity #

Either a well-known principal name — SYSTEM, LocalService, NetworkService — matched case-insensitively and canonicalised, , or a literal SID string such as S-1-5-18. Anything else is passed to authd verbatim to resolve (§4.3).

3.3.3 RequiredPrivileges #

Privilege names, matched case-sensitively against the published privilege table. A name that does not match exactly fails token materialisation and therefore the service start, so SeTCBPrivilege does not start a service that SeTcbPrivilege would.

3.3.4 RuntimeDirectories #

Each entry names one directory directly under /run. Entries are non-empty relative names; an entry equal to . or .. is rejected, as is any entry containing /, \, a NUL, or a control character. A dot inside a name is fine — app.sock.d is a valid entry.

For an entry foo, peinit creates /run/foo immediately before launching the service's main process, with a descriptor granting full access to SYSTEM, Administrators, and the service's own SID. Hook processes inherit the service's environment and identity rules but do not cause provisioning — the directories belong to the main start.

If creation or descriptor assignment fails, the start fails with ParentSetupFailure.

peinit does not remove runtime directories when a service stops. /run is a boot-scoped tmpfs and the next boot clears it.

3.3.5 Environment #

Each entry is KEY=VALUE, with a non-empty key containing no NUL. An entry that does not split into that shape is a decode error.

3.3.6 SuccessExitCodes #

Each entry is a decimal integer from 0 to 255 — a process exit code. Signal names and ranges are not accepted. Code 0 is always success and does not need listing. Duplicates are collapsed.

3.3.7 Dependency and handler names #

Entries in Requires, Wants, BindsTo and Conflicts, and the value of OnFailure, are validated when the definition is read. A dependency naming something outside [A-Za-z0-9._-] is a decode error rather than an unresolved dependency discovered later  — the difference being that a typo containing an illegal character is caught immediately, while a typo that is still a legal name is caught at graph validation as a missing target.

An entry in the four list fields can carry a readiness level, written after a colon (netd:routed). The name and the level are validated separately, so the colon is not one of the illegal characters there.

OnFailure takes a bare service name and no level: it names a handler to run, not a state to wait for.

3.3.8 Timeouts and intervals #

Every timeout and interval in the schema is in whole seconds unless the field says otherwise. The two sd_notify fields that carry durations, WATCHDOG_USEC and EXTEND_TIMEOUT_USEC, are in microseconds because that is what the protocol specifies.

3.3.9 Identifiers peinit generates #

Job identifiers, operation identifiers, and every other GUID peinit mints are UUIDv7. UUIDv7 is time-ordered, so identifiers sort by creation time  — which is what keeps eventd's time-range and recency queries over jobs and operations cheap.

3.4 Triggers

Peios / Reference / peinit / The Service Model

A trigger says when a service starts by itself. Triggers are independent of service type: a Simple service can have a timer, and a Oneshot can start at boot.

Triggers is a multi_string, each entry either type or type:argument.

TriggerFormMeaning
BootbootStart during the Phase 2 boot sequence.
Deferred bootboot:settledStart once the boot set has settled, or the deadline expires. §2.5
Terminal handovertty:releasedStart when this service's TTYPath is let go of. §11.6
Timertimer:<schedule>Start on a schedule. §9.1

A service with no triggers is demand-only: it starts only when something asks for it, whether an administrator, a dependency, or an OnFailure handler.

Multiple triggers of the same type are allowed. A service with ["timer:*-*-* 02:00:00", "timer:*-*-* 14:00:00"] runs at 2am and 2pm, and each trigger is independent — its own timerfd, its own next-firing computation, its own history.

3.4.1 Arity is enforced #

boot takes no argument. boot:<something> accepts only the sub-triggers in the table above, and any other value is malformed rather than an unknown trigger type to be ignored. tty carries the same rule: the bare word names no event, and tty: accepts only released. timer with no schedule is malformed, as is timer: with an empty one.

That strictness is the point. Unknown values on a service key are ignored for forward compatibility, and if unknown trigger types were ignored too, boot:setled would be silently accepted and the service would never start. Instead it fails to decode, loudly.

3.4.2 Triggers that need a field #

tty:released is about the terminal this service names, so a definition carrying it without a TTYPath is refused rather than ignored  — it describes a service that would silently never start, and starting is the entire point of the trigger. TTYPrecedence is refused on the same grounds. Emptying TTYPath (§3.3) takes both down with it.

3.4.3 Disabled #

Disabled=1 suppresses automatic activation and nothing else. No trigger fires: not boot, not boot:settled, not tty:released, not a timer, and not any trigger type added later. A disabled service's timers are neither armed nor serviced.

The definition is still loaded into the in-memory model, and an explicit start still works. To stop a service being started at all, deny SERVICE_START in its ServiceSecurity descriptor — that is an access control question, not a trigger question, and answering it with the Disabled flag would mean a flag that anyone who can write the key can clear.

Enabling and disabling are registry writes performed by administrative tools, not peinit commands. peinit picks the change up through a registry change notification, or on the next reload-config.

3.4.4 Extensibility #

The type:argument shape is designed to grow. Path, device and event triggers slot into the same array with no schema change, because a trigger is a string in a list rather than a field of its own.

3.5 Conditions and Asserts

Peios / Reference / peinit / The Service Model

Both are start-time checks in the same type:argument form, over the same four check types. What differs is the consequence of a failure.

CheckFormPasses when
pathpath:<path>The path exists, of any type.
filefile:<path>A regular file exists there.
directorydirectory:<path>A directory exists there.
registryregistry:<key>The registry key exists.

Conditions describe when a service applies. A failed condition skips the service: it transitions to Skipped, which satisfies its dependents, because a service that does not apply has succeeded by not needing to run.

Asserts describe what a service needs. A failed assert fails the service, with cause AssertionError  — the service was expected to run and a precondition it depends on is missing.

All entries of a kind are AND'd. Conditions are evaluated first; asserts only if every condition passed. Both are evaluated before dependency resolution and before any pre-exec hook, and an entry with an empty argument or an unrecognized type is a decode error.

3.5.1 Evaluation without blocking #

peinit is single-threaded PID 1 and its event loop cannot block while a check runs. Two constraints follow, and they are why the check types behave differently from one another.

3.5.1.1 Registry checks are cache-only #

A registry: check is evaluated against the in-memory model, never by a live registry read. Accepted paths are exactly Machine\System\Services, Machine\System\Init, and Machine\System\Services\<name> with one nonempty service-name component. Init descendants, deeper Services paths, and trailing separators are decode errors, caught at load rather than silently failing at start. The same rule applies to Conditions and Asserts.

The two roots resolve as present. A registry:Machine\System\Services\<name> check is true when that service exists in the model; it does not read an arbitrary registry key. A missing service is a valid check whose result is false.

3.5.1.2 Filesystem checks run in a helper #

stat() can block uninterruptibly on hung I/O — a dead NFS mount, a failing disk controller — so peinit does not call it from the event loop. It forks a short-lived helper into a dedicated checks/ cgroup under the service's tree, using the same clone3 path as any other child. The helper stats the paths and reports over a non-blocking pipe; peinit waits on the pipe and the helper's pidfd through epoll, and never blocks.

PreStartCheckTimeout, default 5 seconds, bounds the helper. A check that does not report in time is treated as not satisfied  — the fail-safe direction, so a condition skips the service and an assert fails it. peinit then SIGKILLs the helper's cgroup and unregisters the result descriptor, and the event loop is never held up by a hung check.

3.5.2 When results are computed #

Checks are evaluated once, before the service's dependencies start, and the result is cached for the rest of that activation. A service that waits a long time for a dependency starts on the answer that was true when the wait began, not on a fresh one.

3.6 Command Strings

Peios / Reference / peinit / The Service Model

Four fields hold executable commands: ExecStartPre, ExecStartPost, the command form of ExecReload, and HealthCheck. All four are parsed the same way.

3.6.1 Parsing #

The string is split on whitespace into an argv, with double quotes grouping. There is no shell — no expansion, no substitution, no globbing, and peinit never invokes one. A command that needs shell features is wrapped in a script.

Whitespace means exactly six characters: space, horizontal tab, line feed, carriage return, form feed, and vertical tab. Every other Unicode whitespace code point is an ordinary argument character, which keeps the split independent of the Unicode version peinit was built against.

Double quotes group text into one argv element and are not retained in the result. Grouping can happen inside an argument, so --name="hello world" becomes the single entry --name=hello world. An empty quoted string is preserved as an empty argv entry.

Backslash has no escape semantics and is copied literally. A single quote is an ordinary character.

An empty or whitespace-only command is invalid, and so is an unclosed double quote.

3.6.2 The executable #

For all four fields, argv[0] is the executable path and begins with /. Relative names, empty names, and PATH-searched execution are decode errors. Everything after argv[0] is an opaque string and is not path validated.

3.6.3 ExecReload signals #

ExecReload can instead name a signal, as signal:<NAME>. The name is an exact canonical Linux signal name. Numeric values, realtime signal expressions, aliases, lowercase spellings, and names with surrounding whitespace are all invalid.

SIGKILL and SIGSTOP are invalid for reload, because a service cannot handle either as a request to re-read its configuration.

The accepted set is the standard non-realtime Linux signals other than those two:

SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGTRAP, SIGABRT, SIGBUS, SIGFPE, SIGUSR1, SIGSEGV, SIGUSR2, SIGPIPE, SIGALRM, SIGTERM, SIGSTKFLT, SIGCHLD, SIGCONT, SIGTSTP, SIGTTIN, SIGTTOU, SIGURG, SIGXCPU, SIGXFSZ, SIGVTALRM, SIGPROF, SIGWINCH, SIGIO, SIGPWR, SIGSYS.

Names are validated when the definition is read and again before delivery, and mapped to host signal numbers at that point. ExecReload absent means SIGHUP.

3.7 Configuration Generations

Peios / Reference / peinit / The Service Model

peinit operates on snapshots, not on a live view of the registry. Two generation concepts govern when a registry change takes effect.

3.7.1 The in-memory model #

peinit maintains a full in-memory model of every service definition. The registry is read synchronously exactly twice: during Phase 2 boot, before meaningful supervision has started, and during a reload-config, which an administrator initiated and which is bounded. At all other times peinit works from the model.

Note

The model exists because the event loop cannot block on a userspace service during normal supervision. In single-threaded PID 1 a blocking syscall blocks everything — child reaping, watchdog expiry, shutdown signals, every other event stops while the syscall is stuck. Reading the registry means waiting on registryd, and registryd is a service peinit supervises.

Change notifications arrive as events on a pollable descriptor. peinit subscribes to Machine\System\Services\ and Machine\System\Init\ at boot, using the LCS watch mechanism — a persistent subscription that delivers change events on a key descriptor, with an OVERFLOW event when the kernel-side queue is exceeded (Peios Kernel TRM §5).

Any drained watch event triggers a full reload of the configuration, not a targeted re-read of the changed key. That covers the OVERFLOW case by construction, and it is why an administrator writing one value causes every definition to be re-read.

3.7.2 The boot generation #

At the start of Phase 2, peinit reads all definitions, builds the dependency graph and validates it. The plan and the graph are fixed at that point, and the boot executes against them.

The watches are armed as the event loop starts, which is after the plan is fixed but while boot-plan services are still starting. A registry write during that window — from an install script, a post-hook, a package transaction — triggers a reload like any other, and the reload applies like any other, with one exception: a boot-plan service whose launch has not yet been attempted keeps the definition the plan was built from, and the new one is recorded as pending, exactly as for a running service. The boot executes against its snapshot (§2.5). Such services are listed under deferred in the reload's summary, said on the console, and recorded as peinit.config.reload.deferred. Once every planned launch has been attempted or decided against — each service terminal, or in Backoff with its dependents held for it (§6.1) — peinit runs one more reload that applies what was deferred, recorded as peinit.config.reload.applied naming the deferred services in graph.services; nothing is emitted when nothing was deferred. A service already running keeps its pinned definition as always.

3.7.3 The activation generation #

When peinit starts a service, it snapshots that service's definition. The snapshot governs the whole start lifecycle: pre-exec hooks, the token request, the readiness timeout, the initial health checks. A field changed while the service is Starting does not take effect until the next start.

A service in Inactive or Failed has no activation snapshot, so starting it uses the current model. That gives the expected behavior for the common edits:

  • A new service entry is available once the change notification is processed.
  • A timer change on an inactive service takes effect at the next trigger evaluation.
  • A dependency change takes effect on the next start for an inactive service, and on the next restart for an active one.

3.7.4 Field mutability #

Which class a field falls into depends on when its value is consumed.

3.7.4.1 Pinned to the running definition #

A change takes effect only when the service is restarted:

ImagePath, Type, Identity, RequiredPrivileges, ErrorControl, RemainAfterExit, Triggers, Disabled.

Triggers and Disabled are pinned only while the service is running. On a service that is not running, both take effect as soon as the notification is processed

 — which is what arms a timer added to an inactive service.

3.7.4.2 Applied on the next start #

A change takes effect at the next start or explicit graph reload, not while services are running:

Requires, Wants, BindsTo, Conflicts, OnFailure, Conditions, Asserts.

3.7.4.3 Reloaded at runtime #

A change takes effect at the next relevant event, with no restart:

Arguments, SuccessExitCodes, every timeout, and retry value (StartTimeout, StopTimeout, WatchdogTimeout, RestartDelay, RestartMaxRetries, RestartWindow, PreStartCheckTimeout), HealthCheck and its three parameters, RestartPolicy, Environment, WorkingDirectory, ExecStartPre, ExecStartPost, ExecReload, HookIdentity, Readiness, NotifyAccess, LimitNOFILE, LimitCORE, FdStoreMax, TTYPath, TTYPrecedence, RuntimeDirectories, Provides, TimerPersistent, TimerJitter, SafeMode, DisplayName, Description, and ServiceSecurity.

ServiceSecurity is the one whose reload is immediately observable: a change takes effect on the very next control request against that service (§4.6).

3.8 Service Removal

Peios / Reference / peinit / The Service Model

When a definition disappears from Machine\System\Services\, peinit learns of it through the ordinary change-notification path. What happens next depends on whether anything is running.

3.8.1 Not running #

An entry in Inactive, Failed, Completed, Skipped, Abandoned, or Backoff is discarded immediately. There is no process to consider.

Backoff belongs in this list rather than the next one, which is not obvious: a service between restart attempts looks like it has something pending. It does not. It has no process, and once the definition is gone there is nothing left to restart it from, so there is neither an instance to supervise nor a restart to wait for.

3.8.2 Running #

An entry in Active, Starting, Reloading, or Stopping is not killed. The running process is a job, and a job's lifecycle is independent of the definition that produced it — removing a definition stops future management, it does not terminate work in progress.

peinit marks the entry definition-removed and keeps the cached definition, solely to go on supervising the instance it already has. When that instance exits it is not restarted — RestartPolicy is moot, because there is nothing left to restart from — and peinit then discards the entry.

A definition-removed entry never has dependents. A read in which one service Requires another the read does not define is refused whole, with MissingHardDependency — so a removal that would leave a dangling hard dependency does not land at all, and the administrator has to remove the dependents first.

While an entry is definition-removed:

  • stop is accepted, so an administrator can drain it cleanly, using the cached StopTimeout;
  • start, restart, and reload are rejected with UNKNOWN_SERVICE — there is no definition to work from;
  • status reports the current runtime state with definition_removed set, so the draining instance is visible rather than silent.

definition-removed is a flag on the existing runtime state, not a state of its own. The state machine (§6.1) and the command × state matrix (§10.3) are unchanged by it.

A restart already in its stop phase is a case of its own. The stop phase still drains the existing instance; the start phase does not begin, because there is nothing to start from. When the instance exits, the operation is aborted with the reason definition_removed_during_restart_stop_leg and the entry takes the ordinary removal discard. This is the window a package upgrade opens — remove the definition, then restart the service.

Once the instance exits or is stopped, the entry — including anything in its fd store (§10.6) — is discarded. A crash counts: the exit is routed to Failed rather than into a restart, because there is no policy left to apply. The fd store goes with it, which a crash would otherwise preserve for the restart that is not going to happen.

4.1 Token Materialisation

Peios / Reference / peinit / Service Identity

Every service process runs with a KACS token that determines its identity and its access rights. peinit obtains or creates that token and installs it on the child before exec. It never shares its own token — even an Identity=SYSTEM service receives a separately materialised token of its own.

Which route the token comes from depends on the Identity field:

IdentitySourceMechanism
SYSTEMMinted by peinit from its own identitykacs_create_token. §4.2
ServiceauthdA virtual account unique to this service. §4.3
LocalService / NetworkServiceauthdA shared service account, with this service's SID as a group. §4.3
Another principalauthdA principal designated for service logon. §4.3
Absent or emptyauthdDefaults to LocalService.

peinit reads its own token with kacs_open_self_token requesting the real token rather than any impersonation, and opens it query-only: it is a template to copy from, never a thing to hand out.

4.1.1 Where a token is materialised #

Materialisation happens at the point of use, per launched process, not once per service. A service that runs a pre-exec hook, a main process, and then a health check materialises three tokens.

ContextIdentity used
Main processIdentity
ExecStartPre / ExecStartPostHookIdentity if set, otherwise Identity
Health checksIdentity, always
ExecReload external commandIdentity, always
Submitted jobsThe prepared primary token: the submitter's own, or the token the kernel attached to the submission (§8.5)

Health checks and reload commands deliberately do not honor HookIdentity. A health check reports on the service's own health and should see what the service sees; a reload command acts on the running service. HookIdentity exists for setup work — creating directories in privileged locations, running a migration — which is a different job from either.

Note

HookIdentity typically grants more than the service itself. peinit does not validate filesystem permissions on hook binaries, so where it grants elevated privileges the administrator is responsible for the hook binary and its parent directories not being writable by anything lower-privileged.

If materialisation fails at any point — authd unreachable, an identity that cannot be resolved, a KACS error — no child exists yet, and the start fails with ParentSetupFailure for the main process or PreHookFailure for a hook.

4.2 The SYSTEM Path

Peios / Reference / peinit / Service Identity

For Identity=SYSTEM, peinit mints a token itself. This is what breaks the bootstrap circle: registryd and authd need tokens, and authd — the thing that mints tokens — is one of them. eventd and lpsd took this path too until they moved to accounts of their own (Identity=Service); they now take the authd path (§4.3) and start after authd.

4.2.1 Minting #

peinit reads its own token as a template and builds a new primary token carrying the same identity: user SID S-1-5-18, the same group list, the same privilege set, the same integrity level. The mint requires SeCreateTokenPrivilege, which the boot SYSTEM token carries; the kernel refuses the call with EPERM otherwise.

Two details of the copy matter.

The logon session comes from the token's statistics. peinit takes the auth_id from the source token's TokenStatistics — not from the independent interactivity_scope field, and not from a hard-coded well-known SYSTEM LUID. The minted token therefore stays associated with the real SYSTEM logon session peinit was given at boot, while carrying its own interactivity scope, which is zero for a platform service. Substituting either of the other two values would associate platform services with a session that does not exist.

The logon SID group is dropped from the copy. The kernel re-appends the session's logon SID when it creates the token, and rejects a create whose group list already contains it. So peinit filters that group out of the template before building.

Two groups are added that the template does not carry. The per-service SID (§4.4), which is what keeps platform daemons distinguishable while they all run as SYSTEM; and the Service group S-1-5-6, which every token authd mints for a service logon carries by derivation from the logon type.

The second is load-bearing rather than cosmetic. S-1-5-6 is the grantee on anything reachable by services as a class — peinit's own notification socket first among them (§10.5) — so a SYSTEM service minted here without it would be unable to report itself ready, while an otherwise identical service on an authd-minted token could. A service is no less a service for having been started before the authority was.

The minted token carries a default DACL the template cannot supply. A token's default DACL is the DACL an object gets when the token creates it with no parent to inherit from — an abstract socket, a key under a container written without inheritable ACEs. The kernel has no fallback of its own: a token whose default DACL is empty leaves such an object with a null DACL, which grants everything to everybody. The bootstrap SYSTEM token carries D:(A;;GA;;;SY)(A;;GA;;;BA) (see Bootstrap tokens), but a token's default DACL is not a field peinit can read back from its own handle, so peinit states the same value itself and sets it on every SYSTEM token it mints. Non-SYSTEM services do not pass through here; their default DACL is the authority's, from the DefaultDacl value of the principal's policy record (§4.3).

peinit also asserts that its own token is a primary token and that its user SID really is S-1-5-18 before minting, and fails the start with a message naming what it found otherwise. PID 1 minting from something that is not the boot SYSTEM token is not a situation to proceed from.

The minted token is fully independent. The privilege restriction that follows (§4.5) operates on it alone and cannot affect peinit's own.

Note

Minting is an interim mechanism. The intended model is for peinit to derive the token from its own handle, through a KACS duplicate-with-additions operation — kernel-attested as a descendant of peinit's real token, and requiring no token-minting privilege at all. That operation does not exist in KACS yet, so peinit mints.

4.3 The authd Path

Peios / Reference / peinit / Service Identity

For any identity other than SYSTEM, the token comes from authd. peinit does not resolve identities, does not know whether a principal is local or from a domain, and does not want to: routing is authd's whole purpose.

The division is not that peinit lacks the privilege to mint — it plainly has it, and uses it for the SYSTEM path (§4.2). It is that the privilege set and integrity level an identity carries are policy, and policy is authd's. A second component deciding it in parallel is a disagreement waiting to happen, and peinit has already shipped one: its hand-written privilege bit table had four wrong entries, silently stripping privileges a service had asked to keep.

4.3.1 The request #

peinit sends a ServiceAttest on /run/logon.sock, specified as PGSS Logon §2.19. It carries two strings:

FieldValue
identityThe definition's Identity value, verbatim
serviceThe name of the service being started

authd answers with AccessGranted carrying the token as an SCM_RIGHTS descriptor, or AccessDenied. There is no credential exchange, because a service identity has no credential and must never acquire one — a machine that could authenticate its own services unattended would have to hold their secrets.

authd derives the per-service SID from service and adds it to the token, so the SID that distinguishes one service from another comes from the authority on this path rather than from peinit (§4.4). Note that authd cannot verify service: the process it names does not exist yet, so there is no token to interrogate. peinit is trusted on it, which is the reason for the restriction below.

4.3.2 This request must come from PID 1 #

authd authorizes a ServiceAttest on two facts: that the peer's token names SYSTEM, and that the peer is PID 1. The second is not redundant. SYSTEM alone is every platform daemon on the machine, so without it, compromising any one of them would yield a token for any service identity authd would mint.

That makes it a standing constraint on this crate: the connection is opened by peinit's own process and must never be opened by a forked helper. Nothing in the code enforces it. If it is ever broken the symptom is every non-SYSTEM service failing to start at boot with an authorization error, which reads like a fault in authd rather than like a refactor.

4.3.3 The token is weaker than a user's, deliberately #

An attested token is minted one rung lower on the impersonation ratchet than a credentialled logon: Impersonation rather than Delegation.

The evidence behind it does not travel. A credential a principal source verified is something another machine could in principle have checked too; peinit's word is evidence on this machine only. A service token that could be forwarded off the box on the strength of it would let one system's PID 1 act as an arbitrary account on another.

Because the level is a ratchet, nothing derived from a service's token can exceed it either.

4.3.4 Failure is a failure #

Every non-SYSTEM service start depends on authd being reachable, and every one of them fails if it is not. Only services using the SYSTEM path are unaffected; platform services such as eventd and lpsd use the authority too.

peinit orders around that dependency rather than merely suffering it. The authority declares Provides = ["authn"], and peinit derives a hard dependency on whoever fills that role for every service whose Identity — or whose HookIdentity, where it has hooks — is not SYSTEM (§7.6). Nothing is written on the consumer side: the edge comes from the same field that creates the requirement, so a new service cannot forget it.

Until that existed the ordering was left to each definition, and all three LocalService definitions in the tree omitted it — so a service needing a token routinely reached this code before the socket was bound and failed its launch with ENOENT, on most boots, recovering only through its restart policy.

This is the intended behavior rather than a limitation. The client that preceded it returned a freshly minted SYSTEM token whenever it could not do better, so a service declaring LocalService ran with peinit's entire privilege set — and status output reported it as LocalService, which is what kept the problem invisible from outside. A service that does not start is visible; a service running as the wrong principal is not.

summarize_token now refuses to describe a token as an identity it does not carry: where the declared identity predicts a user SID, a token carrying a different one fails the launch rather than being reported under the name that was asked for. It is only checked where the identity predicts a SID — a principal name is authd's to resolve, and peinit has nothing to compare it against.

4.3.5 What can be attested #

authd accepts the platform's own service identities — SYSTEM, LocalService, NetworkService, and the per-service virtual account selected by Service — which no principal source holds and for which no credential could exist.

Anything else must be designated in the principal's own record as usable for a service logon, and until that designation exists authd refuses it. So a definition naming an ordinary principal does not start. That is the property the design exists to guarantee: without it, the service manager would be an oracle that mints a credential-free token for anybody on the machine.

4.3.6 The service's own virtual account #

Identity=Service asks authd to use the per-service SID (§4.4) as the user SID, as well as including it in the token's groups. The spelling Service is case-insensitive. Each service name therefore selects a separate virtual account without creating an account in a principal source or enabling a credentialled logon.

The derived groups include Everyone (S-1-1-0), Authenticated Users (S-1-5-11), Local (S-1-2-0), and Service (S-1-5-6), together with the kernel's per-session logon SID. It does not acquire SYSTEM or LocalService membership. Privileges, integrity, owner, and default DACL still come from authd's policy evaluation; choosing a distinct user SID grants no extra privileges by itself.

With Identity=LocalService, the user SID is the shared S-1-5-19 instead. The service's own SID remains a group, so ACLs can still distinguish two services that share that account. Use Service when their user identities should also be distinct.

Service takes the same derived hard dependency on the providers of the authn role as other non-SYSTEM identities (§7.6). On the standard platform that provider is authd; an explicit Requires=authd is unnecessary.

4.3.7 The interface is authd's #

peinit speaks the protocol through libauthd, which is its definition, rather than encoding the message itself. A second implementation of a wire format that mints identity is the kind of duplication that fails silently and in the worst place.

4.4 Per-Service SIDs

Peios / Reference / peinit / Service Identity

Every service token carries a SID derived from the service's name, in its group list, alongside whatever the principal's own identity brings.

The derivation is the one KACS defines (Peios Kernel TRM §3.2). The authority is S-1-5-80. The service name is uppercased and encoded as UTF-16LE, SHA-1 is taken over those bytes, and the 20-byte digest is split into five little-endian 32-bit sub-authorities:

S-1-5-80-<sub1>-<sub2>-<sub3>-<sub4>-<sub5>

peinit computes this itself, from the name alone, with no involvement from anything else. authd computes the same value independently when it mints a token, and the two implementations are pinned against each other by a shared test vector.

4.4.1 Why they exist #

Per-service SIDs are what make access control useful when services share a principal. Every platform daemon runs as SYSTEM, and every service with no Identity runs as LocalService; without something to tell them apart, an ACL could grant a right to "LocalService" and thereby grant it to a dozen unrelated services.

With a per-service SID, an ACE can name one specific service. It costs nothing — no account, no registry entry, no allocation — because it is a hash of a name that already has to be unique.

They are load-bearing in more than access checks. peinit uses the service SID directly when it provisions a service's runtime directories, stamping /run/<name> with a descriptor that grants full access to SYSTEM, Administrators, and that service's SID and nothing else (§3.3).

4.4.2 The uppercasing rule #

The name is uppercased before encoding, using full Unicode case mapping — the one that expands ß to SS and fi to FI rather than mapping each code unit in place. peinit uppercases in the code-point domain, before the UTF-16 encoding, so any expansion happens first.

For an ASCII service name, which is every real service, the choice is invisible. It becomes visible only for a name containing a character whose uppercase form is longer than itself.

4.5 Privilege Restriction

Peios / Reference / peinit / Service Identity

RequiredPrivileges is a list of the privileges a service needs. Everything else is removed from its token before exec.

4.5.1 Subtractive only #

peinit removes privileges. It never adds one, on either path — there is no code that constructs anything but a removal. A service cannot acquire a privilege by naming it in RequiredPrivileges; if the token it was given does not have it, listing it changes nothing.

The removal targets the token's present bitmask, through KACS_IOC_ADJUST_PRIVS on the token descriptor — one kacs_priv_entry per removed privilege, carrying the privilege-removed attribute. The right required on the descriptor is KACS_TOKEN_ADJUST_PRIVS, which a freshly minted token always has.

peinit does not use KACS_IOC_RESTRICT. That builds a restricted-SID token — a different mechanism with different semantics — and does not touch the privilege bitmask at all. It is available in the bindings and would be a plausible-looking mistake.

Removing a privilege clears its present, enabled and enabled-by-default bits together, and irreversibly. The privileges that survive keep the enable state their source gave them: peinit does not enable, disable, or re-order anything. Enable policy belongs to whoever minted the token.

peinit iterates all sixty-four privilege bits rather than only the ones it has names for, so a privilege this build does not know about is stripped along with the rest. The safe direction is to remove what was not asked for, including what cannot be named.

If RequiredPrivileges is absent, peinit does not query or adjust the token at all, and the source's default privilege set stands unchanged.

4.5.2 Names #

Privilege names are matched case-sensitively against the published privilege table. A name that does not match exactly is not silently ignored: it fails token materialisation, and therefore fails the service start.

Two privileges KACS enforces are absent from the published table — SeTakeOwnershipPrivilege and SeRelabelPrivilege — and so cannot be named in RequiredPrivileges at all. A service that needs either declares nothing and takes the source token's defaults, or fails to start if it tries to name one.

4.6 Service Security Descriptors

Peios / Reference / peinit / Service Identity

A service carries two independent descriptors, and they answer different questions.

The registry key descriptor on Machine\System\Services\<name> controls who can read and write the service's definition. It is enforced by LCS at key-open time and is not peinit's concern — peinit reads definitions as SYSTEM.

The ServiceSecurity descriptor controls who can perform runtime operations on the service through the control interface. It is stored as a binary ServiceSecurity value on the same registry key, but enforced by peinit rather than by LCS.

The two are genuinely independent. An administrator might be able to query a service's status without being able to read its configuration, or the reverse. Runtime control and configuration access are separate concerns and there is no reason for one to imply the other.

4.6.1 Access rights #

RightBitGrants
SERVICE_QUERY_STATUS0x0001Query state, PID, cause, health, warnings.
SERVICE_START0x0002Start the service.
SERVICE_STOP0x0004Stop the service.
SERVICE_INTERROGATE0x0008Reload the service.
SERVICE_ALL_ACCESS0x000FThe union of the four.

Restart requires SERVICE_START and SERVICE_STOP together. Reset requires SERVICE_STOP, because clearing a Failed or Abandoned state is the tail of stopping something rather than the head of starting it.

The generic mapping peinit passes to AccessCheck:

Generic rightMaps to
GENERIC_READSERVICE_QUERY_STATUS
GENERIC_WRITESERVICE_START | SERVICE_STOP | SERVICE_INTERROGATE
GENERIC_EXECUTESERVICE_START | SERVICE_STOP | SERVICE_INTERROGATE
GENERIC_ALLSERVICE_ALL_ACCESS

4.6.2 Inheritance and the default #

A service whose definition carries no ServiceSecurity value takes the one on Machine\System\Services itself. The lookup is a single step to that key, not a walk up the hierarchy, which is exact for the flat layout definitions actually use. That includes the compiled-in registryd, which takes it once Phase 2 has read the key and on every reload after; a registry definition of registryd (§2.3) can give it a descriptor of its own like any other service.

If that key has no ServiceSecurity either, peinit applies a built-in default:

O:SY G:BA D:(A;;0x000F;;;SY)(A;;0x000F;;;BA)(A;;0x0001;;;AU) S:(AU;FA;0x000F;;;WD)

SYSTEM and Administrators both get SERVICE_ALL_ACCESS. The SACL audits every refusal, for everyone, which is what records a denial (below). An administrator who can stop any service and shut the machine down gains nothing by being unable to start one, so the default does not attempt a narrower grant; a service that wants one carries its own ServiceSecurity value.

Every authenticated principal gets SERVICE_QUERY_STATUS: what a service is doing is not, by default, a secret from the people using the machine, and a service whose state is a secret carries a ServiceSecurity that says so.

4.6.3 The check #

When a control command arrives, peinit:

  1. Takes the caller's token, captured when the connection was accepted.
  2. Resolves the target service and its ServiceSecurity descriptor. A command naming no definition and no addressable definition-removed entry returns UNKNOWN_SERVICE; peinit does not invent a descriptor to check against.
  3. Calls AccessCheck with the caller's token, that descriptor, the generic mapping above, the right the command needs, and an audit context naming the service, {kind: "service", service: {name}}.
  4. On denial, returns ACCESS_DENIED. The attempt is recorded by KACS, not by peinit: when the descriptor's SACL asks for it — and the built-in default's does — the check writes a kacs.audit.access.checked record with object.kind service, object.service.name, the caller's token, and the access requested and granted (§8.4).
  5. On grant, proceeds.

4.6.4 The SACL is the audit policy, and who can drop it #

A service's SACL decides which of its decisions are recorded. A descriptor written to the registry is used as it is: one with no SACL records nothing, and one that narrows the default's audits less.

ServiceSecurity is a whole registry value. Whoever can write it — on the service's key, or on Machine\System\Services, whose value every service without its own takes — can replace the descriptor, SACL included, without holding SeSecurityPrivilege, which is what changing an object's SACL otherwise needs. So those keys must be writable only by principals trusted to change audit policy. By default they are: both inherit the Machine hive root, which grants write to SYSTEM and Administrators alone, and Administrators hold SeSecurityPrivilege. Delegate a service through its ServiceSecurity DACL, never by loosening the key's own descriptor; and a tool that changes only the DACL must write the SACL back unchanged. The same holds for the control descriptor in Machine\System\Init (§10.2).

4.6.5 Hot reload #

ServiceSecurity changes take effect on the next control request, with no restart. A registry change notification triggers a configuration reload, and the reload re-reads every descriptor. There is no cached decision to invalidate — the check runs against the current descriptor every time.

4.6.6 Filtering, not denying #

list returns only the services the caller has SERVICE_QUERY_STATUS on. Services the caller cannot query are omitted, not denied: a caller with no query rights anywhere receives an empty list and a successful response. The denials are not surfaced to the caller; each service's SACL decides whether KACS records them.

What the filtering protects is a service's state, which is what SERVICE_QUERY_STATUS grants. That a service exists is not protected: a command naming one is answered UNKNOWN_SERVICE or ACCESS_DENIED according to whether it exists, and the definitions under Machine\System\Services are readable. A client that can read the definitions can therefore show a service list left out as one whose state the caller can not see.

4.7 The Control Descriptor

Peios / Reference / peinit / Service Identity

Three commands are not about any one service: shutting the system down, re-reading the configuration, and asking how the machine booted. They are checked against peinit's own descriptor, stored at Machine\System\Init\ControlSecurity as a binary value.

4.7.1 Access rights #

RightBitGrants
SYSTEM_SHUTDOWN0x0001Initiate poweroff, reboot, or halt.
SYSTEM_RELOAD_CONFIG0x0002Re-read all definitions from the registry.
SYSTEM_QUERY_STATUS0x0004Read peinit's own status: how this boot went, with boot (§10.2).

The generic mapping:

Generic rightMaps to
GENERIC_READSYSTEM_QUERY_STATUS
GENERIC_WRITESYSTEM_RELOAD_CONFIG
GENERIC_EXECUTESYSTEM_SHUTDOWN
GENERIC_ALLall three

GENERIC_READ maps to the one right that changes nothing, as it maps to SERVICE_QUERY_STATUS on a service. Before boot existed the control descriptor governed two actions and no queries, and GENERIC_READ on it conveyed nothing; a descriptor written then that grants GENERIC_READ now lets its holder ask how the machine booted, and nothing more.

4.7.2 The default #

Absent a value in the registry, peinit applies:

O:SY G:BA D:(A;;0x0007;;;SY)(A;;0x0007;;;BA)(A;;0x0004;;;AU)

SYSTEM and Administrators both get every right, as they both get every service right in the ServiceSecurity default (§4.6). An administrator who can stop services one at a time can already stop the system, so withholding shutdown would be theater.

Authenticated Users get SYSTEM_QUERY_STATUS and nothing else.

How a machine booted is machine status, like what /proc shows, not a secret; and it is what a person signed in to the machine needs to tell that it came up in Safe mode, or is a failed boot or two from recovery. The ServiceSecurity default lets the same group query every service for the same reason.

The default applies only while ControlSecurity is absent or malformed. A descriptor already written to the registry is used as it stands: one written before SYSTEM_QUERY_STATUS existed grants it only where it grants GENERIC_READ, GENERIC_ALL or the bit itself, and a machine that wants every signed-in user to read its boot status adds an ACE for them.

4.7.3 Loading #

peinit loads the descriptor during Phase 2 boot and hot-reloads it on registry change notification, on the same path as the service descriptors. Until it is loaded — during Phase 1 and the early part of Phase 2 — the built-in default applies, which matters because the control socket exists from Phase 1 infrastructure setup onwards.

5.1 The Cgroup Tree

Peios / Reference / peinit / Starting a Service

peinit uses cgroups v2 for exactly two things: knowing which processes belong to a service, and killing all of them at once. It does no resource accounting and sets no limits.

Every service gets a tree:

/sys/fs/cgroup/peinit/<cgroup-id>/          service root
/sys/fs/cgroup/peinit/<cgroup-id>/main/     the main process
/sys/fs/cgroup/peinit/<cgroup-id>/hooks/    hooks and reload commands
/sys/fs/cgroup/peinit/<cgroup-id>/health/   health check invocations
/sys/fs/cgroup/peinit/<cgroup-id>/checks/   pre-start filesystem check helpers

The sub-cgroups satisfy cgroups v2's "no internal processes" rule, which applies whenever controllers are enabled, and give hooks and probes containment of their own so that killing one does not touch the service.

They are not all created at once. The root and hooks/ are created when the first thing needs them — the first pre-exec hook, if there is one — and main/ and health/ when the main process launches.

5.1.1 The cgroup id #

<cgroup-id> is the service name with every byte outside [A-Za-z0-9._-] percent-encoded as % plus two uppercase hex digits. Service names are already restricted to that set (§3.1), so in practice the id equals the name.

The encoding is a defensive guarantee that distinct names always map to distinct, cgroup-safe ids. % is not itself in the safe set, so it escapes to %25 and the encoding is prefix-free. That is what makes it injective, unlike a plain substitution of / for -, under which a/b and a-b would collide.

The id is internal. The name a user sees is unchanged.

5.1.2 Generations #

A cgroup whose processes survived SIGKILL cannot be removed — rmdir on it fails with EBUSY. peinit records the leak and moves the service to a fresh tree:

/sys/fs/cgroup/peinit/<cgroup-id>%gen<N>/

Old leaked trees persist until the next reboot.

Two conditions record a leak, and both are needed because they answer different questions. cgroup.events reporting populated at the post-kill deadline says live processes remain. rmdir returning EBUSY says the tree cannot be given up, which covers that case and the ones where nothing is running but the directory still will not go. Acting on only the first left the second reusing a tree that already existed and was not empty.

The generation advances once per tree, not once per leak recorded against it. A single failed start records two cleanup deadlines — one for hooks/, one for the service tree — and a tree cleanup can report main/, hooks/, health/ and the root separately; all of those are the same tree, so the first advances the generation and the rest find themselves already behind it. Leaks are still deduplicated by path and kind, so each is recorded once.

The separator is %gen, not .gen. . is in the safe set and service names permit it, so a service literally named app.gen1 would have shared a directory with generation 1 of a service named app. % self-escapes and the encoder only ever emits it followed by two uppercase hex digits, so %g cannot occur inside an encoded id — which makes the whole path injective, not only the id.

5.2 Pre-Start Evaluation

Peios / Reference / peinit / Starting a Service

Before anything is forked, peinit evaluates the service's conditions and asserts (§3.5). The definition comes from the in-memory cache, so this never touches the registry.

  1. If the service names a TTYPath and another service is holding that terminal, it goes to Skipped with cause TtyUnavailable and the start is abandoned (§11.6). Asked first because a terminal is a fact about the machine right now, and evaluating conditions ahead of it would fork a check helper for a start that was never going to happen.
  2. Conditions are evaluated. Any failure transitions the service to Skipped and abandons the start. Skipped satisfies dependents.
  3. If every condition passed and the service has asserts, they are evaluated. Any failure transitions the service to Failed with cause AssertionError and abandons the start.

Only when all three pass does the pre-exec sequence continue.

5.2.1 Where the transition happens #

For a fresh start from Inactive, the evaluation gates the transition: the service becomes Starting only after the checks pass, so a skipped service goes straight Inactive → Skipped.

For an activation that is already Starting — the start leg of a restart, for instance — the transition has already happened, and the evaluation gates further progress instead. A restart whose conditions do not hold therefore passes through Starting on its way to Skipped, where a fresh start would not.

An assert failing takes the same route to Failed on both paths, and on both it propagates: dependents in the same graph context hear that the dependency failed (§7.3). This matters more on the restart leg than elsewhere, because an AssertionError is never restarted — where a running dependent is deliberately unaffected by a dependency crashing (§7.1), since a crash is transient and the restart policy handles it, a failed assert means the dependency is not coming back without intervention.

5.2.2 Two check kinds, two mechanisms #

registry: checks resolve against the in-memory model. Since a non-cacheable key is rejected when the definition is read, this evaluation never needs a live read.

Filesystem checks — path:, file:, directory: — run in a forked helper. peinit clones it with CLONE_PIDFD | CLONE_INTO_CGROUP into the service's checks/ sub-cgroup, exactly as it launches anything else. The helper stats the paths and writes the results to a non-blocking pipe; peinit watches the pipe and the helper's pidfd through epoll.

The terminal is re-checked when the helper's results come back, rather than the earlier answer being carried over : the helper ran in between, and a terminal can change hands while it did.

PreStartCheckTimeout bounds the helper, at 5 seconds by default. On expiry every check still outstanding is marked not satisfied — the fail-safe direction — and re-evaluated on that basis, so a condition skips the service and an assert fails it. peinit then kills the helper's cgroup and unregisters the result descriptor.

A helper that survives the kill, stuck in uninterruptible sleep, has its cgroup abandoned and recorded exactly as a leaked hook or health cgroup is (§5.7).

5.2.3 Caching #

The results are computed once, before the service's dependencies are started, and reused for the rest of that activation. A service that waits a long time on a dependency starts on the answer that was true when the wait began.

Filesystem checks are gathered in one helper run, from the conditions and the asserts together. There is only ever one run — the completion path evaluates both lists against the results it gets back, and there is no mechanism to ask for a second — so both lists' paths have to be stat'd before it. A path named in both is stat'd once.

A check with no result counts as not satisfied, which is the fail-safe direction for a timeout and is why the gather has to be complete: an omitted path is indistinguishable from a path that is not there.

5.3 The Pre-Exec Sequence

Peios / Reference / peinit / Starting a Service

Everything between "peinit decides to start service X" and "X's binary is running". The service is in Starting throughout.

5.3.1 Step 1: Arm the start timeout #

StartTimeout covers the entire remaining sequence — pre-hooks, fork, exec, and the readiness wait. A single deadline, measured from the operation's creation rather than from this point, bounds all of it.

Expiry aborts the start and kills the service's cgroup tree. The cause recorded depends on where the deadline landed : a timeout during pre-hooks is PreHookFailure; one during the readiness wait or the main process's execution is ReadinessTimeout.

5.3.2 Step 2: Provision runtime directories #

If the definition lists RuntimeDirectories, peinit creates each one under /run and applies its descriptor (§3.3) before anything else in the launch. Failure classifies as ParentSetupFailure.

5.3.3 Step 3: Run pre-exec hooks #

Each ExecStartPre command runs in sequence, forked into hooks/. A token is materialised for each at the point of use, from HookIdentity if set and Identity otherwise (§4.1); a failure there fails the hook and the service with PreHookFailure.

Any hook exiting non-zero kills the entire service cgroup tree — cleaning up whatever grandchildren the hook left — and fails the service with PreHookFailure.

When every hook has succeeded, peinit kills the hooks/ sub-cgroup before the main process starts, so a hook that forked something into the background does not become part of the service.

5.3.4 Step 4: Materialise the service token #

The main process's token, per §4.1. A failure means no child exists and the service fails with ParentSetupFailure.

If a later parent-side step fails before the fork, peinit closes the token descriptor exactly once. A failure to close is retained as cleanup evidence and does not change how the start is classified — the classification describes what went wrong with the start, and a failed close is a separate fact about the same failure.

5.3.5 Step 5: Create the cgroups and the error pipe #

The main/ and health/ sub-cgroups are created, and a pipe2(O_CLOEXEC) error pipe. The parent keeps the read end, non-blocking; the child will hold the write end.

The pipe is how the child reports a failure it hits after fork but before exec. If exec succeeds, the write end closes automatically — that is what O_CLOEXEC is for — and the parent reads EOF, which means setup succeeded. If setup fails, the child writes a structured error first.

The payload is exactly eight bytes, written with one write(2):

BytesContent
0–3little-endian u32, the child setup step identifier
4–7little-endian i32, a positive Linux errno

The child writes at most one payload — the first reportable failure — and then exits. The parent treats a non-EOF payload that is not exactly eight bytes, or carries an unknown step identifier, or an errno of zero or less, as malformed evidence and fails closed with PreExecFailure.

The step identifiers:

IdStep
1Close the read end of the error pipe
2Set the standard streams
3Reset the signal environment
4Install the service token
5Set the resource limits
6Set oom_score_adj
7Set the working directory
8reserved
9Confirm NOTIFY_SOCKET
10Inject stored descriptors
11Exec the binary
12Create a session
13Acquire the controlling terminal

Identifier 8 is reserved and never emitted : the environment is built in the parent and applied by execve, so there is no step in the child that could fail. Identifiers 12 and 13 are the two terminal steps, which occur only for a service with a TTYPath.

If pipe2 fails, no child exists and the service fails with ParentSetupFailure.

5.3.6 Step 6: Fork #

clone3(CLONE_PIDFD | CLONE_INTO_CGROUP), targeting main/. This does two things atomically: it returns a pidfd for the child, and it places the child directly into main/ at creation. There is no window in which the child exists without a pidfd, and none in which it runs or execs in peinit's own cgroup.

Placing the child at creation also avoids the alternative, which would be having the child write its own PID into cgroup.procs — something its post-installation token could not do.

A clone3 failure means no child exists: ParentSetupFailure, with EMFILE /ENFILE, EAGAIN and ENOMEM the usual causes.

peinit does not take the atomicity on trust. If clone3 reports success without setting the pidfd, or the pidfd cannot be made close-on-exec, peinit writes to cgroup.kill through the main/ directory descriptor before returning ParentSetupFailure — because by then a child does exist, running in the service's cgroup with the service's token, and the parent has no handle on it. Walking away would leave a process peinit cannot supervise, cannot stop, and has no record of, which the zero-delay cleanup that follows a ParentSetupFailure would then record as a leaked tree rather than kill.

Immediately after clone3 returns, in the parent and on either outcome, peinit closes the token descriptor and the main/ cgroup descriptor, exactly once each. The child relies on close-on-exec and its own exit instead. A failure to close is cleanup evidence and does not change how the start is classified.

5.3.7 Step 7: The parent after the fork #

  1. Close the write end of the error pipe.
  2. Register the read end with the event loop. peinit does not block on it — signals, control traffic, timers, and log pipes stay serviceable while the child's setup is pending.
  3. When the read end becomes readable or hangs up, read it non-blocking:
    • Would block: leave the source registered, the job stays in pending setup.
    • EOF: exec succeeded. Record the pidfd on the job, emit peinit.job.started, and only then apply readiness side effects such as Simple/Alive activation.
    • Data: setup failed. Parse the step and errno, log the specific failure, fail the service with PreExecFailure.

While setup is pending the job is not Running, and no dependent that waits on this service's readiness is released.

5.3.8 Steps 8 and 9 #

The child's own path is §5.4. What follows exec is the readiness wait and the post-readiness work:

  • Simple with Readiness=Notify: wait for READY=1, then Active.
  • Simple with Readiness=Alive: Active as soon as exec succeeds.
  • Oneshot: wait for the exit. Success is Completed; without RemainAfterExit it then goes Inactive once dependents are released. A non-zero exit is Failed.

On readiness or successful exit, peinit runs ExecStartPost in sequence into hooks/, releases the service's dependents, kills hooks/, and — for a Simple service only — arms the watchdog if WatchdogTimeout is non-zero and the health check timer if HealthCheck is set.

A post-hook that fails is logged and does not fail the service. The state transition to Active or Completed happens before the post-hooks run, so a service is already Active while its post-hooks are executing.

5.3.9 Failures before the fork #

Steps 2, 4, 5, and 6 can all fail with no child in existence. peinit handles all four entirely in the parent: clean up whatever cgroups were created, fail the service with ParentSetupFailure, and return the error to the caller. These are system-level resource problems — file descriptor limits, PID limits, memory, cgroup filesystem errors — rather than anything about the service.

5.4 The Child Path

Peios / Reference / peinit / Starting a Service

Between clone3 returning in the child and execve, peinit runs a straight line of setup. The path is kept minimal — no logging, no complex library calls — because it runs after a fork, where very little is safe to do.

Each step reports through the error pipe with the identifier from §5.3 if it fails, then exits: _exit(126) for a setup failure, _exit(127) for a failed exec.

The steps, in the order the child runs them:

#StepId
1Close the read end of the error pipe1
2setsid() — only with a TTYPath12
3Set the standard streams2
4ioctl(TIOCSCTTY) — only with a TTYPath13
5Reset the signal environment3
6Set RLIMIT_NOFILE and RLIMIT_CORE5
7Set oom_score_adj6
8Install the KACS token, then close its descriptor4
9Change the working directory7
10Confirm NOTIFY_SOCKET is present in the environment9
11Inject stored descriptors from fd 3 upward10
12execve11

5.4.1 The terminal steps #

setsid() comes first, and its position is load-bearing in two directions. It has to precede the stream setup, because setsid() drops any controlling terminal the child inherited — doing it afterward would throw away the terminal attached. And it has to precede TIOCSCTTY, which requires a session leader that does not already own a controlling terminal.

TIOCSCTTY is passed a literal zero argument, which is what makes it unable to steal a terminal already owned by another session.

Without a TTYPath neither step runs and the service stays in peinit's session.

5.4.2 The standard streams #

Without a TTYPath: stdin from /dev/null, stdout and stderr onto the write ends of the service's output pipes, and every inherited pipe end that is unneeded closed.

With a TTYPath: all three streams onto the opened terminal, and the /dev/null descriptor and both pipe pairs closed. A terminal-attached service's output is therefore not captured for logging — it goes to the terminal, which is the point of asking for one.

5.4.3 The signal environment #

peinit blocks every signal for its signalfd (§12.3) and the child inherits that mask across the fork. Step 5 empties the mask and resets every resettable disposition to SIG_DFL. A service starting with signals blocked, or with PID 1's handling in place, is one of the classic ways for a daemon to behave inexplicably.

5.4.4 oom_score_adj #

-1000 — OOM-immune — for an ErrorControl=Critical service, and 0 for everything else. A Critical service is one whose loss reboots the machine, so letting the OOM killer choose it would convert memory pressure into a reboot.

5.4.5 Resources before the token #

The resource limits and oom_score_adj are set while the child still holds peinit's credentials, and only then is the service token installed. Both are peinit's policy rather than authority the service holds: raising a hard limit or lowering oom_score_adj needs CAP_SYS_RESOURCE, which KACS projects from SeIncreaseQuotaPrivilege. Setting them after the install would make every Critical service, and every service with a raised limit, depend on that privilege. A RequiredPrivileges list that leaves it out would then stop the service from starting at all.

The step identifiers are unchanged by this order. They name steps, not positions.

5.4.6 The environment #

There is no step that sets the environment, which is why identifier 8 is reserved and never emitted. peinit builds the environment in the parent (§5.5) and hands it to execve as envp, so it arrives with the exec rather than being installed beforehand. Step 10 is a check rather than a set: it confirms NOTIFY_SOCKET is present in the prebuilt environment and fails with a synthetic EINVAL if it is not.

5.4.7 What the child does not inherit #

A service inherits only what peinit hands it: its standard streams and any descriptors injected from the fd store. Everything else peinit holds is created close-on-exec — the control socket and every accepted connection, the notification socket, the epoll instance, the signalfd, every timerfd, both pidfds, every pipe, and every stored descriptor until it is deliberately un-marked at injection.

The signal reset and the close-on-exec discipline together are what make a service start from a clean context rather than from PID 1's privileged one.

A descriptor opened through the Peios native file interface returns without close-on-exec set, so it does not get the discipline for free. peinit sets the flag by hand on each of those — the input devices it opens for the power button, the main/ cgroup directory descriptor, /dev/null, and the service and recovery consoles — immediately after opening them. The child duplicates its intended streams onto descriptors 0, 1 and 2 without close-on-exec, then explicitly closes the original descriptors. The streams survive exec; the original handles do not.

5.5 The Base Environment

Peios / Reference / peinit / Starting a Service

peinit constructs every service and hook process's environment from scratch, in four layers, lowest precedence first. Nothing is inherited : peinit's own startup environment holds TERM and nothing else (§2.1), and none of it is passed through.

5.5.1 Layer 1: the compiled-in base #

One variable:

VariableValue
PATH/sbin:/bin

Executables are addressed through the root-level StrataFS runtime views. Package storage paths under /usr are deliberately not on the default search path.

5.5.2 Layer 2: global environment variables #

Each value under Machine\System\Init\EnvVars\ becomes a variable: the value name is the variable name, the REG_SZ data is the value. An EnvVars\PATH overrides the compiled-in PATH; every other name adds.

A malformed entry — an empty name, or a name containing = — fails the whole layer, which at boot means recovery mode.

registryd does not receive this layer. The exemption is a trust rule, not an availability one. Write access to EnvVars\ is equivalent to compromising every service peinit starts: LD_PRELOAD, LD_LIBRARY_PATH and their relatives are not filtered, because the key's Security Descriptor is meant to be the control boundary. A key that could inject into the daemon that enforces who can write it would make that boundary self-referential.

The exemption is narrow, and matches on two things at once: the job's resolved identity is SYSTEM and its service name is registryd. A non-platform service that happens to be called registryd receives the ordinary layering. It matches on the job, so a hook of registryd's running under a non-SYSTEM HookIdentity would receive the layer; and it matches the resolved identity string, so a definition naming S-1-5-18 literally rather than SYSTEM would not be exempt.

registryd is launched in Phase 1, before EnvVars has been read at all, so the exemption is only observable on a restart.

5.5.3 Environment #

The definition's Environment entries, overriding both layers below.

5.5.4 Layer 4: protocol variables #

NOTIFY_SOCKET, always. LISTEN_FDS, LISTEN_FDNAMES and LISTEN_PID, only when descriptors are being injected — from the fd store for a service, or from a submission's attachments for a submitted job (§8.5).

These have the highest precedence. The first three are inserted after both configurable layers, and all four names are dropped from those layers before insertion, so a service cannot override NOTIFY_SOCKET and break its own notification protocol, and an EnvVars\LISTEN_FDS=3 cannot point an fd-store-less service's sd_listen_fds at whatever happens to sit at descriptor 3. The name filter is what protects the LISTEN_* set when it is not being set.

LISTEN_PID, which a conforming sd_listen_fds implementation checks against its own PID before trusting LISTEN_FDS, is appended by the child itself after the clone, because only then is the PID known; the name filter keeps a configured value from shadowing it.

5.5.5 What peinit does not set #

Not HOME, USER, LOGNAME, SHELL, or TERM. Peios identity is a KACS token — a SID — rather than a passwd entry, so there is no canonical home directory or sign-in shell to populate. A service that needs one supplies it through EnvVars\ or its own Environment; a submitted job's submitter supplies it in the submission's environment, which occupies layer 3 for a job.

5.5.6 Hooks and probes #

Hooks, health checks and reload commands are built through the same path, so they receive the identical environment: the same layers, the same NOTIFY_SOCKET, and the service's WorkingDirectory, LimitNOFILE, LimitCORE and RequiredPrivileges. They never receive LISTEN_FDS — stored descriptors go to the main process only.

5.5.7 When changes apply #

The global layer is a snapshot refreshed at boot and on reload-config, and both it and the per-service Environment take effect at a service's next start. Neither is applied to a running process.

Note

Write access to Machine\System\Init\EnvVars\ is equivalent to compromising every service on the system. peinit does not filter variable names, consistent with the registry's write-authority threat model — the key's descriptor is the boundary. The recommended default is SYSTEM full control and Administrators read-only.

5.6 Health Checks

Peios / Reference / peinit / Starting a Service

A watchdog tells peinit that a service is still ticking. A health check tells it that the service still works. They address different failures: a process can be alive and responsive to its own event loop while having lost its database connection, wedged in a bad state, or started returning errors to everyone.

5.6.1 Execution #

The health check command runs with the service's own token — never HookIdentity — so it checks the service's health from the service's own vantage point.

Each invocation runs in an ephemeral health/ sub-cgroup under the service's tree, as a child of peinit rather than of the service. When the check completes or times out, peinit kills the whole sub-cgroup, which cleans up anything the check spawned.

5.6.2 Overlap #

If the previous check is still running when the next interval fires, the new one is skipped and nothing is counted. A check exceeding HealthCheckTimeout has its sub-cgroup killed and is counted as a failure.

A launch failure — a token that could not be materialised, a fork that failed — is not counted. The invocation is recorded and the next interval schedules normally, and nothing about the service changes.

The distinction is between "the probe ran and said the service is unhealthy" and "the probe could not be run". Only the first is evidence about the service. Collapsing them meant a transient authd unavailability could kill a service outright: with HealthCheckRetries=1, a reasonable setting for a probe an operator trusts, one failed token materialisation exhausted the budget and restarted it.

5.6.3 Failure #

HealthCheckRetries consecutive failures mark the service unhealthy. An unhealthy service is restarted through the ordinary restart policy: RestartPolicy, exponential backoff and throttling all apply, exactly as for a crash. The failure count resets the moment a check succeeds.

Escalation kills the service's root cgroup rather than main/, so it takes hooks and probes with it.

5.6.4 The flap constraint #

Restart throttling is what stops a service flapping — failing checks, restarting, passing initial checks, failing again. But it only works if the failure cycle is shorter than RestartWindow, because otherwise the service stays healthy long enough between failures to reset the restart counter, RestartMaxRetries is never reached, and it restarts forever.

So this relationship has to hold:

HealthCheckRetries × HealthCheckInterval < RestartWindow

It is enforced as an error rather than a warning, in both places a definition can arrive. At boot, a violating service is blocked with cause ValidationError and never started. On reload-config, it is a validation finding, and a finding rejects the entire reload.

The constraint applies only where a check will actually run, which means Simple services. A Oneshot cannot flap through health checks because it never runs one.

A Oneshot that declares a HealthCheck is still rejected — but for declaring one at all, not for its timing. That is the thing actually wrong with the definition; reporting it as timing arithmetic let an operator adjust RestartWindow, see the definition validate, and still have a HealthCheck that does nothing.

Note

Active health checks on ErrorControl=Critical services deserve caution. A false positive eventually exhausts the restart budget and reboots the machine. Critical services — registryd, authd, lpsd, eventd — are usually better served by a passive watchdog with a generous timeout: the service knows whether it is healthy and can stop sending keepalives when it decides it is not. peinit does not prevent health checks on Critical services and applies identical semantics to them, but the escalation path ends at a reboot.

5.7 Leaked Sub-Cgroups

Peios / Reference / peinit / Starting a Service

A process in uninterruptible kernel sleep — D-state, typically a hung NFS mount or a failing disk controller — does not die when it is SIGKILLed. Its cgroup cannot be removed while it is there.

peinit detects this through cgroup.events: after sending the kill it arms a post-kill deadline, 5 seconds by default, and checks whether populated is still 1 when the deadline fires.

5.7.1 What happens depends on which cgroup it is #

For the main process, a survivor is fatal to supervision: the service transitions to Abandoned with cause ProcessUnkillable and peinit stops supervising it (§6.1).

For a health check or a hook, it is not. Those are diagnostic and setup processes; they hold no service resources — no ports, no file locks, no database connections — so a stuck one does not make the service unmanageable. peinit orphans the sub-cgroup instead:

  1. Marks it leaked, recording the path, the kind, and the time.
  2. Increments the service's cgroup generation, so the next start builds a fresh tree (§5.1).
  3. Carries on supervising the service normally.

A leaked pre-start check helper is treated the same way: its checks/ sub-cgroup is recorded and the generation bumped, which matters because otherwise the next start would build into a tree that still contains the unkillable process.

The leaked cgroup stays in the hierarchy until the next reboot.

A tree the service's next instance is already running in is not checked. A restart can relaunch before the post-kill deadline of the instance it replaced — the default restart delay is one second, the post-kill deadline five — and it relaunches into the same tree, since nothing has leaked yet to move the generation on. When the deadline fires, the tree is populated by the live instance, not by a survivor, so peinit drops the check rather than record a leak. A survivor of the killed instance that shares that tree goes unreported until the tree is next killed and checked.

5.7.2 Visibility #

Leaks are not silent. peinit both pushes one when it is detected and keeps it queryable afterward.

The push happens once, on first detection — recording is idempotent, so a leak that is re-examined on a later cleanup pass is not announced again:

  • A peinit.cgroup.leaked event on the event stream, carrying the service, the sub-cgroup path (object.cgroup.path) and its kind (object.cgroup.type: service-tree, health, hooks, or helper). When it was found is the event's own time.

  • A console line naming the same service, kind and path.

The pull side survives the moment of detection, for anyone who was not watching:

  • A status query includes a warnings array, one entry per leak, each an object with the sub-cgroup path, its kind, and the time of detection:

    {"path": "/sys/fs/cgroup/peinit/jellyfin/health", "type": "health",
    "detected_at": "2026-06-01T12:34:56.123456789Z"}
    
  • A start command on a service with leaks returns a warning in its acknowledgment, saying the service has leaked sub-cgroups from a previous generation and that this indicates an I/O problem needing investigation.

The type is the same vocabulary everywhere : health for a leaked health/ sub-cgroup, hooks for a leaked hooks/ one, helper for a pre-start check helper's checks/, and service_tree for a leaked service root — the last being the most serious, since it means the whole tree including main/ could not be reclaimed.

Whichever way it reaches you, what the leak means is the same: something underneath the service is not responding to the kernel, and no amount of restarting the service will fix it.

6.1 States

Peios / Reference / peinit / The State Machine

Every service is in exactly one state. There are ten.

StateProcess?Satisfies dependents?Meaning
InactiveNoNoNot started, or stopped cleanly and not set to restart.
StartingMaybeNoActivation in progress: checks, hooks, fork, or the readiness wait. The process can not exist yet.
ActiveYesYesRunning and ready.
ReloadingYesYesRe-reading configuration. Still satisfies dependents.
StoppingBrieflyNoSIGTERM sent, awaiting exit, or SIGKILL escalation.
CompletedNoYesOneshot only. Exited successfully.
BackoffNoNoA restart is pending; waiting out the backoff delay.
FailedNoNoExited abnormally with the restart policy exhausted or absent.
AbandonedYes, unkillablyNoSIGKILL sent and processes survived. Supervision has stopped, the cgroup is leaked.
SkippedNoYesConditions were not met. The service does not apply.

6.1.1 Dependent satisfaction #

Exactly four states satisfy dependents: Active, Reloading, Completed, and Skipped. Nothing else does, and a dependent blocked on a Requires target in any other state does not start.

Completed satisfies regardless of RemainAfterExit — a Oneshot without it passes through Completed to release its dependents on the way to Inactive, rather than skipping the state.

Skipped satisfies because a service whose conditions do not hold has succeeded by not needing to run. Treating it as a failure would make every conditional service a hazard to everything that depends on it.

Reloading satisfies because the process is still there and still serving; a reload is a service telling itself to re-read a file, not an outage. So a reload does not restart the RestartWindow clock (§6.4), clear a readiness level the service has published (§7.5), or count as its target going away to a BindsTo dependent (§7.1).

Backoff does not, and the distinction from Failed matters: a service in Backoff is going to start again, and its dependents wait rather than failing. It is the state that makes a restart something other than a transit through Failed. A dependent held this way looks exactly like a start held on a readiness level — Inactive, its start operation Pending (§8.2) — and is released when the service next reaches a dependent-satisfying state. It fails with dependency_failure only when the service gives up: its restart budget is exhausted, or it is stopped or its definition withdrawn while in Backoff.

6.1.2 Invariants #

  1. A service is in exactly one state at any moment. There is one state field and exactly one place in the implementation that assigns to it.
  2. Only the transitions in §6.2 are performed. The assignment is gated by a central allowlist, so an unlisted transition is not merely avoided by convention — it cannot be written.
  3. Only peinit transitions a service. The control socket produces operations; nothing outside peinit writes state.
  4. A service object is securable independently of its process token. The ServiceSecurity descriptor governs who can manage the service; the process token governs what the service can reach. Neither implies anything about the other.
  5. Readiness is per start generation. The generation increments on every transition into Starting, and a READY=1 carrying a stale generation is rejected — so a notification from a previous incarnation can never be mistaken for this one's.

6.2 Transitions

Peios / Reference / peinit / The State Machine

Every transition peinit performs. Anything not listed here is not performed.

FromToTrigger
InactiveStartingStart command, dependency resolution, or a timer trigger.
InactiveSkippedA condition check failed.
InactiveFailedValidation, assertion, cycle, or dependency failure — before any process existed.
StartingActiveReadiness. Simple only: READY=1 received, or the process exists under Readiness=Alive.
StartingCompletedOneshot exited successfully. Without RemainAfterExit it passes through, releasing dependents, then goes Inactive.
StartingSkippedA condition failed after the activation had already entered Starting.
StartingFailedAn assert failed after entering Starting; or a timeout, hook failure, setup failure, or an exit before readiness.
StartingBackoffA startup failure with the restart policy allowing a retry and budget remaining.
StartingStoppingAn explicit stop canceling an in-progress start. A restart on a Starting service is queued rather than canceling.
StartingFailedThe shutdown wave SIGKILLed a starting service.
ActiveReloadingExecReload issued, or SIGHUP delivered.
ActiveStoppingExplicit stop, conflict eviction, a bound dependency stopping, or shutdown.
ActiveBackoffA crash, a watchdog timeout, or health check failure, with a restart allowed and budget remaining.
ActiveFailedThe same three, with RestartPolicy=Never or the budget exhausted.
ActiveInactiveA Simple service exited successfully and RestartPolicy is not Always. Cause CleanExit.
ActiveBackoffA Simple service exited successfully and RestartPolicy=Always. Cause CleanExitRestart.
ReloadingActiveReload resolved: READY=1, the detection window expiring, the extended wait expiring, or the reload command exiting — success or failure.
ReloadingStoppingThe same triggers as Active to Stopping. The reload is canceled.
ReloadingBackoffThe main process exited during the reload, with a restart allowed.
ReloadingFailedThe same, with no restart available.
StoppingInactiveThe process exited after an explicit stop or a shutdown.
StoppingFailedThe process exited after a conflict eviction or a bound dependency stopping.
StoppingAbandonedSIGKILL sent and main/ still populated after the post-kill deadline.
StoppingStartingAn explicit start queued against a service that is still stopping. Cause ExplicitStart.
BackoffStartingThe backoff delay elapsed. Cause RestartPolicy.
BackoffInactiveAn explicit stop canceled the pending restart.
BackoffSkippedThe backoff delay elapsed and the relaunch's pre-start checks skipped the service: its terminal is now held (§11.6), or a condition do not holds.
BackoffFailedThe backoff delay elapsed and peinit could not execute the relaunch. Cause InternalError.
Starting, Active, Reloading, StoppingFailedpeinit could not carry out a step on the service and contained the error to it (§8.2). Cause InternalError.
CompletedInactiveRemainAfterExit=0 and dependents released; or an explicit stop; or shutdown clearing it.
CompletedStartingA start command or timer trigger re-running the Oneshot.
FailedStartingAn explicit start, a bound dependency recovering, or a timer trigger.
FailedInactiveA reset command clearing the state.
FailedAbandonedA service SIGKILLed by the shutdown wave whose cgroup stayed populated past the post-kill deadline.
AbandonedInactiveA reset command.
SkippedInactiveA reset command, or an explicit start clearing Skipped before it re-evaluates the conditions.

6.2.1 Things the table settles #

A restart never passes through Failed. A restart-eligible failure goes to Backoff, waits, and goes to Starting. Failed is reached only when there will be no retry: RestartPolicy=Never, an invalid policy for the cause, or an exhausted budget. This is why OnFailure (§6.3), which fires on entry to Failed, does not fire on each retry — only when the service finally fails out.

A clean exit is not a crash. A Simple service exiting zero goes to Inactive under cause CleanExit, consulting neither the restart policy nor the budget. It goes to Backoff only under RestartPolicy=Always, and then with the distinct cause CleanExitRestart, so status and events say plainly that the process succeeded and was restarted by policy rather than that anything went wrong.

A forced stop remembers why. Stopping to Failed carries the cause from the transition that started the stop — ConflictEviction or BindsToPropagation — rather than a generic failure. A service that lost a conflict and a service whose binding target went away are distinguishable afterward, which is what makes bound-dependency recovery (§7.1) possible at all.

A restart detours through Inactive. The stop leg of an administrator's restart ends in Inactive, and the start leg begins from there. The two legs meet within one turn of the event loop, and peinit answers no request mid-turn, so no query ever sees the service Inactive in between.

A crash before readiness can be retried. A Simple process that exits before signaling readiness is a ProcessCrash from Starting, and is restart-eligible like any other, rather than a terminal startup failure.

A process can outlive its service's state. Most states are reached by the main process exiting, but not all of them: a watchdog timeout, a health check escalation and the post-kill give-up all move a service on while its process is still running. The exit that follows arrives for a service in Backoff, Abandoned or another state that does not expect one.

peinit records that exit and performs no transition. The service keeps the state it had, any pending restart deadline stands, and the console reports it:

peinit: service <service> main process exited in state <state>; no action taken

This is deliberately not a fatal condition. A supervised service producing an unexpected sequence costs that service; it does not cost the machine. Treating it as a broken invariant of the runtime loop meant one crash-looping service dropped PID 1 into recovery mode and killed every session on the box.

6.2.2 Abandoned #

Resetting an Abandoned service re-checks its main/ sub-cgroup. If it has finally emptied, peinit cleans up the whole service tree — main/, hooks/, health/, then the root — and transitions to Inactive.

If it is still populated, peinit leaves the cgroup leaked, transitions to Inactive anyway, and returns this warning in the operation acknowledgment:

abandoned main cgroup for service <service> is still populated after
reset -- cgroup remains leaked; underlying D-state process requires
investigation

The warning is also written to the console, so a reset issued without reading the response still leaves a trace of the still-leaked cgroup.

The re-check targets main/. Note that the two paths into Abandoned probe different cgroups: an explicit stop checks main/, while the shutdown wave checks the service root.

6.3 Transition Causes

Peios / Reference / peinit / The State Machine

Every transition carries a cause recording why it happened. peinit tracks both the current state and the cause of the most recent transition, and the cause determines restart eligibility, OnFailure behavior, and what an administrator is told.

6.3.1 The taxonomy #

CauseLeads toMeaning
ExplicitStartStartingAn administrator, an OnFailure handler, or a boot plan started it.
ExplicitStartInactiveAn explicit start on a Skipped service, clearing it so the conditions are re-evaluated.
DependencyStartStartingStarted to satisfy another service's dependency.
RestartPolicyStartingAn automatic restart after a backoff delay.
BindsToRecoveryStartingA bound dependency returned to Active.
TimerStartingA timer trigger fired.
ExplicitStopStoppingAn administrator requested a stop.
ExplicitReloadReloading, ActiveA reload was issued and resolved.
ExplicitResetInactiveAn administrator cleared Failed, Abandoned, or Skipped.
ConflictEvictionStoppingA conflicting service started; this one lost.
BindsToPropagationStoppingA bound dependency stopped.
ShutdownWaveStopping, FailedThe system is shutting down. Active and Reloading services go to Stopping; Starting services go straight to Failed.
ProcessCrashFailed, BackoffThe main process exited unexpectedly.
CleanExitInactiveA Simple process exited successfully with a policy other than Always.
CleanExitRestartBackoffA Simple process exited successfully under RestartPolicy=Always.
ReadinessTimeoutFailed, BackoffStartTimeout expired before readiness.
WatchdogTimeoutFailed, BackoffA keepalive did not arrive in time.
HealthCheckFailureFailed, BackoffHealthCheckRetries consecutive failures.
PreHookFailureFailed, BackoffAn ExecStartPre hook exited non-zero, or its token failed, or the start timed out during hooks.
ParentSetupFailureFailed, BackoffA parent-side failure before the fork. No child was created.
PreExecFailureFailed, BackoffPost-fork setup failed before exec, reported through the error pipe.
DependencyFailureFailedA Requires dependency entered Failed.
RestartBudgetExhaustedFailedRestartMaxRetries reached.
CycleDetectedFailedThe service is part of a dependency cycle.
ValidationErrorFailedThe definition failed graph validation.
AssertionErrorFailedA start-time assert failed.
ConditionSkippedSkippedA start-time condition failed.
TtyUnavailableSkippedAnother service was holding the terminal this one names in TTYPath. §11.6
ProcessUnkillableAbandonedProcesses survived SIGKILL.
InternalErrorFailedpeinit could not carry out a step on the service — a relaunch, a job terminal, a setup status, a health probe, a deadline action. The service did nothing wrong; its operation fails with the internal_error result (§8.2).

6.3.2 Restart eligibility #

Causes fall into four classes, and the class decides whether the restart policy is consulted at all.

Restart-eligible. peinit consults RestartPolicy and the budget. If a restart is allowed and the budget holds, the service goes to Backoff and then to Starting; otherwise Failed.

ProcessCrash, WatchdogTimeout, HealthCheckFailure, ReadinessTimeout, PreHookFailure, PreExecFailure, ParentSetupFailure.

Note

The startup failures are restart-eligible because a transient problem during startup should get another go. A pre-hook that failed because a network mount was briefly unavailable deserves a retry rather than an immediate give-up.

Always-only. CleanExitRestart applies when a Simple service exits successfully and the policy is Always. It uses the same backoff and the same budget as a failure, which is what stops a daemon that exits cleanly in a tight loop from bypassing throttling entirely. It is never treated as a ProcessCrash, and both status and events make clear the process succeeded and was restarted only because the policy says so.

CleanExit is its non-restarting counterpart: straight to Inactive, consulting neither policy nor budget.

Budget-exempt. BindsToRecovery takes a service from Failed to Starting when its binding target returns. It is not subject to the policy or the budget, because the service did not fail on its own — it was stopped because its dependency went away.

Never-restart. peinit does not consult the policy at all: ExplicitStop, ExplicitReset, ShutdownWave, ConflictEviction, BindsToPropagation, ProcessUnkillable, RestartBudgetExhausted, ValidationError, CycleDetected, DependencyFailure, AssertionError, ConditionSkipped, TtyUnavailable, InternalError. Retrying cannot help with any of them.

6.3.3 OnFailure #

When a service enters Failed and its definition names an OnFailure service, peinit starts that service — with the exceptions below. OnFailure fires on entry to Failed, and Failed to Failed is not a transition, so it fires at most once per failure.

It does not fire for:

  • ShutdownWave — no new service starts during shutdown, so a fallback would be both impossible and pointless.
  • **ValidationError, CycleDetected, DependencyFailure, AssertionError ** — these are definition or graph breakage rather than runtime degradation. A broken definition cannot meaningfully trigger a fallback, and the fallback would probably sit in the same broken graph.

It fires for everything else, including ProcessCrash, WatchdogTimeout, HealthCheckFailure, the startup failures, and RestartBudgetExhausted on a non-Critical service.

For a Critical service exhausting its budget, the reboot takes precedence and no fallback is started. The suppression asks whether a reboot is owed rather than inspecting ErrorControl itself, which is the same question §6.4 puts.

OnFailure is for graceful degradation — the main web interface fails, so start a minimal emergency endpoint. It is not for monitoring or alerting, which is eventd's job.

6.3.3.1 A handler that is already running #

If the named handler is already Active — or Reloading, on its way back to Active — the failure starts nothing. A running service has no state to transition into on being started again, and it is already doing the job the failure would have asked of it, so the start resolves as satisfied: no operation is created, and no loop-guard chain entry is recorded for a cascade that did not happen.

This is the same answer the control interface gives an administrator who starts an already-running service, and it is deliberately the same test. A handler in any other state is started normally — so a Oneshot handler that ran for an earlier failure runs again for a new one, and a handler that has since failed is restarted.

6.3.3.2 The loop guard #

An OnFailure handler can fail and carry its own OnFailure, so a misconfiguration where A's handler is B and B's is A could run forever. peinit bounds the chain originating from one failure two ways: it tracks the set of services already started as handlers for that failure and will not start one already in the set, and it will not follow the chain past a fixed depth of 16. When either trips, peinit records a peinit.on-failure.suppressed event naming which (outcome.reason cycle or max-depth), and stops.

A chain entry is retired two ways.

The handler stopped needing tracking. Completed, Inactive, Skipped, or Abandoned — it ended, gave up, or became unkillable.

The handler arrived. It has been dependent-satisfying for its RestartWindow — the same window that resets a restart budget (§6.4). That is peinit's existing test for a service having genuinely taken over rather than merely come up, and it is what ends the originating failure: a later failure of that handler is a new one, starting a fresh chain.

The distinction matters in both directions. Without the second rule, a handler that runs healthily for days holds a slot forever, so a degradation path handing off through several healthy layers exhausts its own depth budget by working. But retiring on Active alone would break the guard entirely: Readiness=Alive reports Active the instant the process spawns, so two services naming each other as handlers would hand off forever, with no delay and no cost — an OnFailure start is not a restart and spends no restart budget. Only a handler that held is treated as having arrived.

6.3.4 The logging contract #

A transition into Failed, Skipped or Abandoned is written to the console, naming the service and its cause: what failed, and why. There is no per-transition event — a transition is visible through the peinit.job.* and peinit.operation.* events that carried it, not as a record of its own.

Cryptic failure messages are a defect. A reboot loop caused by a configuration error with an opaque message is the worst outcome the system has, and the cause taxonomy exists so that the "why" is never a guess.

6.4 Restart

Peios / Reference / peinit / The State Machine

When a restart-eligible cause occurs, or a Simple clean exit produces CleanExitRestart, peinit evaluates the restart policy. The outcome is either Failed, or Backoff followed by Starting.

evaluate_restart(service, cause):
    // 1. Policy.
    if cause is never-restart:
        return STAY_FAILED
    if cause == CleanExitRestart and policy != Always:
        return INVALID_CAUSE_FOR_POLICY
    if policy == Never:
        return STAY_FAILED
    if policy == OnFailure:
        // A termination counts as success only when the cause is a
        // process exit whose code is in SuccessExitCodes. Only
        // ProcessCrash and CleanExitRestart carry an exit code, and
        // CleanExitRestart was handled above. Every other eligible
        // cause has no exit code and is always a failure here.
        if cause == ProcessCrash and exit_code in success_exit_codes:
            return STAY_FAILED
    // A clean terminal logout is not a failure.
    if cause == CleanExitRestart and TTYPath is set:
        consecutive_failures = 0
        return RESTART_AFTER(min(restart_delay, 60))
    // Other Always exits fall through.

    // 2. Budget.
    if consecutive_failures >= restart_max_retries:
        cause = RestartBudgetExhausted
        if error_control == Critical:
            sync and reboot
        return STAY_FAILED

    // 3. Delay.
    delay = min(restart_delay << consecutive_failures, 60)

    // 4. Schedule.
    return RESTART_AFTER(delay)

RESTART_AFTER puts the service in Backoff for the delay; when it elapses the service transitions to Starting and the ordinary activation sequence begins, with its own fresh StartTimeout.

The elapsed backoff timer is consumed when the relaunch is admitted. If a pre-start check needs an asynchronous filesystem helper, the service remains in Backoff until that check finishes, retaining its terminal reservation. The pending check drives progress; the expired timer cannot admit another restart while it waits.

The relaunch runs the pre-start checks like any other start, and the machine can have changed while the service waited. If its terminal is now held (§11.6) or a condition do not holds, the service goes from Backoff to Skipped, with the cause the check gives, and its pending operation completes as a skip. A relaunch that peinit itself cannot execute — its bookkeeping refuses the start — takes the service from Backoff to Failed under InternalError (§6.3), fails the operation waiting on the restart with the internal_error result, and reports both on the console; it does not cost the machine.

The exit code is available only when peinit observed a process exit, and it is carried into the evaluation wherever there was one — including the pre-readiness exit, where a Simple service exits before signaling READY=1. So SuccessExitCodes means the same thing on both sides of readiness: a service that legitimately concludes "nothing to do" during startup and exits with a listed code is not restarted.

Failures with no process exit behind them — a hook that never ran, a readiness deadline, a dependency failure — carry no code, and the SuccessExitCodes branch cannot apply to them. That is not a gap: a success code is a statement about how the service's own process ended.

6.4.1 The policies #

PolicyValueBehavior
Never0Never restart. The service stays Failed.
OnFailure1Restart on a non-zero exit or a runtime failure. An exit matching SuccessExitCodes is not restarted.
Always2Restart on any failure regardless of exit code, and for a Simple service also on a successful clean exit.

For a Oneshot with RestartPolicy=Always, a successful exit is not restart-eligible. RestartPolicy governs the response to failures; a Oneshot that succeeds has done its job. It goes to Completed — and then Inactive without RemainAfterExit — whatever the policy says, and only a non-zero exit reaches the restart evaluation at all. Timer triggers are the mechanism for re-running a Oneshot on a schedule.

6.4.2 Backoff #

The delay doubles on each consecutive failure, starting from RestartDelay and capped at 60 seconds. The arithmetic is overflow-safe, so a large RestartDelay or a long failure run saturates at the cap rather than wrapping.

While a service is in Backoff it is down and does not satisfy dependents. An explicit start creates or merges into a deferred start operation, which honors the remaining delay rather than short-circuiting it;

a stop cancels the pending restart and takes the service to Inactive.

For a terminal-attached service, a successful Always exit is a normal session logout. It resets the failure counter and uses the base delay (capped at 60 seconds), without spending or exhausting the crash budget. Failed exits and startup failures still use the ordinary budget and exponential backoff.

6.4.3 The budget, and when it resets #

consecutive_failures counts consecutive restart-eligible failures. It resets to zero only after the service has stayed Active for RestartWindow seconds. It is not a count of restarts within a trailing window, and the difference is what the mechanism turns on.

peinit stamps the moment a service becomes dependent-satisfying, and clears that stamp on any transition to a non-satisfying state — so a crash restarts the clock. The reset fires when the stamp plus RestartWindow is reached with the service still Active.

A service that recovers and stays Active longer than RestartWindow between crashes therefore never exhausts its budget: each crash starts from a counter of zero.

Only failures recurring faster than the service can sustain a window of health accumulate.

Two other events also zero the counter, both of which mean the service is outside a failure run: a clean exit to Inactive, and an administrative reset. An explicit stop while in Backoff does not — the accrued failures are preserved.

Because the reset requires the service to be Active, a service that happens to be Reloading when its window boundary passes misses that reset and gets it on returning to Active.

6.4.4 Exhaustion #

Once RestartMaxRetries restarts have happened without the service sustaining a window of health, the next failure is not restarted: Failed with cause RestartBudgetExhausted. peinit then applies ErrorControl:

  • Normal — the service stays Failed.
  • Critical — peinit syncs the filesystems and reboots immediately. The reboot takes precedence over OnFailure.

The reboot does not depend on how the budget was exhausted. The paths that observe a terminal outcome for a running service — the main job ending, a health check failing or timing out, the watchdog expiring — raise it directly. Every other route reaches it through a check made once per runtime turn, which asks a single question of the service table: is a Critical service Failed with cause RestartBudgetExhausted? That covers a budget exhausted purely by startup failures — repeated ReadinessTimeout, PreHookFailure, ParentSetupFailure — where a service that can never get as far as running would otherwise have settled in Failed with neither escalation.

The OnFailure suppression asks the same question rather than inspecting ErrorControl itself, so the handler is skipped exactly when a reboot is owed and never on the strength of one that was not scheduled.

A failure during a shutdown reboots nothing (§12.2 step 2), and the handler is not started either — the machine is already going down.

6.5 Reload

Peios / Reference / peinit / The State Machine

Reload tells a service to re-read its configuration without restarting. peinit issues the reload, moves the service to Reloading, and resolves it one of three ways.

A failed reload never takes a running service out of Active. And reload never gets stuck: every path has a timeout.

6.5.1 Choosing a path #

ExecReload absent means SIGHUP to the main process. A signal:<NAME> value means that signal instead. Anything else is a command, forked into the service's hooks/ sub-cgroup under the service's own identity — never peinit's token, and HookIdentity does not apply.

6.5.2 The signal path #

There is no command exit to observe, so completion is inferred from the main process's own notifications.

start the detection window (2 seconds)

on READY=1, at any time:
    -> Active, "confirmed"

on RELOADING=1 within the window:
    cancel the window
    start the extended wait (StartTimeout)

on the window expiring with no RELOADING=1:
    -> Active, "advisory"

on the extended wait expiring with no READY=1:
    -> Active, "advisory"

The two-second window is a constant and is not configurable through the registry, directly or otherwise. It is not clamped to the operation's own deadline: a service configured with a short StartTimeout, which is a reasonable thing to do for something that starts fast, still gets its full two seconds to answer a reload. The reload operation's own lifetime already bounds the whole thing.

The extended-wait expiry means the service announced a reload and never finished one. That is what the detection protocol exists to catch — the service has wedged mid-reload or lost its handler — so it is reported rather than only returned:

peinit: service <service> signalled RELOADING=1 but never completed reload

and audited as a peinit.service.reload.timed-out event. The outcome is still carried in the operation's result for a wait=true caller, but a reload issued without waiting reports its outcome on the console as well.

A detection window expiring is a different thing and stays quiet. A service that does not implement the handshake lets it expire on every reload, and reporting that would drown the case above.

6.5.3 The command path #

The command's exit gates failure; the main process's READY=1 gates confirmation.

on the command exiting non-zero:
    -> Active, "failed"

on the command exceeding StartTimeout:
    SIGKILL the hooks/ sub-cgroup, taking its descendants
    -> Active, "failed"

on the command exiting zero:
    -> Active, "confirmed" if the main process sent READY=1 during the
       reload, otherwise "advisory"

6.5.4 Auto-detection #

The protocol needs no per-service configuration. A service that implements the notification handshake — RELOADING=1 then READY=1 — gets real lifecycle tracking. One that does not gets a brief Reloading state that resolves itself when the detection window expires. Neither has to declare which it is.

6.5.5 Interruptions #

The main process crashes while Reloading. That is a ProcessCrash, and the restart policy is consulted: Reloading to Backoff if a restart is allowed and the budget holds, Reloading to Failed otherwise. Both reload timers are canceled and any in-flight reload command is killed.

This is a different event from an external reload command exiting non-zero, which is the "failed" outcome above and leaves the main process — and the service — running.

A stop arrives while Reloading. peinit cancels the reload immediately: it drops the reload deadlines, kills any reload command's cgroup, and sends SIGTERM in the same turn, without waiting out the window or the extended wait. The service goes to Stopping and the reload operation is aborted.

6.6 The Watchdog and Timeout Extension

Peios / Reference / peinit / The State Machine

Two notification fields let a running service adjust the deadlines it is held to. Both are authenticated exactly as any other notification (§10.5), and both carry microseconds.

6.6.1 The watchdog #

WatchdogTimeout sets the interval peinit expects WATCHDOG=1 pings at. Zero, the default, disables it. Missing a ping is a WatchdogTimeout cause and takes the ordinary restart path.

A service can change the interval at runtime by sending WATCHDOG_USEC=<value>:

  • A value greater than zero updates the interval and re-arms immediately — the current timer is canceled and a fresh one starts from the moment the message was received, rather than the new interval applying only from the next ping.
  • A value of zero disables the watchdog entirely, equivalent to WatchdogTimeout=0.

The runtime value does not persist. On a restart the interval reverts to the definition's WatchdogTimeout converted to microseconds, and if that is zero the watchdog starts disabled whatever the previous incarnation had set.

WATCHDOG_USEC is honored only while the service is Active. A service that sends it while still Starting — before its own READY=1 — is ignored and gets the definition's value.

Note

Runtime watchdog updates suit a service whose phases have genuinely different latency. A database engine might want a tight five-second watchdog in normal operation and sixty seconds during a compaction pass. The service knows its own phases better than whoever wrote its definition does.

6.6.2 Timeout extension #

A service can ask for more time during a start, stop or reload by sending EXTEND_TIMEOUT_USEC=<value>.

peinit sets the current phase's deadline to expire that many microseconds from now. The extension replaces the deadline rather than adding to it — each message sets an absolute deadline computed from its own arrival — and can be sent repeatedly.

Because it replaces, a small value shortens the remaining time rather than being ignored, and a value of zero sets the deadline to now.

6.6.2.1 The caps #

The extended deadline cannot exceed four times the phase's base timeout:

PhaseBaseCeiling
StartingStartTimeoutStartTimeout × 4
StoppingStopTimeoutStopTimeout × 4
ReloadingStartTimeoutStartTimeout × 4

A value beyond the cap is clamped, not rejected — the message succeeds and the deadline becomes the maximum permitted. Because the cap is anchored to when the operation started rather than to the previous deadline, repeated messages cannot creep past it.

During shutdown an additional cap applies: the deadline cannot exceed the time remaining in the global ShutdownTimeout, and where both caps apply the stricter wins.

6.6.2.2 Where it does not apply #

A message arriving while the service is in a non-transitional state — Active, Completed, Failed — is ignored. There is no deadline to extend.

During shutdown, as at any other time, an extension moves only a deadline the service already has. A service still in a transition when the shutdown begins — starting, reloading, or stopping under an explicit stop — extends that transition's deadline, and one already stopping keeps its stop deadline, extension included, into its wave (§12.2). A service that is Active until its stop wave reaches it has no deadline to extend before then, so a request it sends earlier is ignored like any other in a non-transitional state. A service that expects its stop to take longer sends the request once its stop has begun.

Note

Timeout extension is for a service doing variable-duration work in a transition — replaying a write-ahead sign in startup, say. It sends periodic messages to prove it is making progress; if it stops sending, the last deadline fires and peinit escalates as usual. The fourfold cap is what stops a buggy service extending forever.

7.1 Relationships

Peios / Reference / peinit / Dependencies

Four relationship types. Each says something different about how two services interact at start, at stop, and on failure.

7.1.1 Requires #

A hard dependency. If A Requires B:

  • Start. B has to reach a dependent-satisfying state before A starts. If B is not running, peinit starts it with cause DependencyStart. If B enters Failed, A goes to Failed with cause DependencyFailure without attempting to start.
  • Stop. Stopping B does not stop A. This is a start-ordering constraint, not a runtime coupling.
  • Runtime failure. If B crashes while A is Active, A is unaffected and keeps running. B's own restart policy handles B.
  • Missing target. A goes to Failed with DependencyFailure, detected at graph validation.

7.1.2 Wants #

A soft dependency. If A Wants B, peinit starts B before A — with cause DependencyStart — provided B exists and is not disabled. If B fails to start, or does not exist at all, A starts anyway. There is no stop or failure effect in either direction.

The waiting rule is where the difference from Requires actually lives: a dependent blocked on a Requires target waits for it to reach a satisfying state, while a dependent blocked on a Wants target waits only for it to reach any terminal state, satisfying or not. That is what makes Wants ordering rather than dependency — "start this first if you can, but I will work without it".

7.1.3 BindsTo #

A runtime coupling. If A BindsTo B:

  • Start. Identical to Requires.
  • Stop. If B stops for any reason — explicit stop, conflict, crash, shutdown — A stops too, transitioning to Stopping with cause BindsToPropagation.
  • Recovery. When B returns to Active, peinit automatically restarts anything sitting in Failed with cause BindsToPropagation from B's stop. This is reactive rather than polled: peinit watches for the transition into Active from a non-satisfying state, and reacts to it. These restarts do not consume the restart budget — the dependent never failed on its own, it was stopped because its binding target went away.

BindsTo implies Requires. A definition can list both for clarity, and if it does, the BindsTo semantics apply.

7.1.4 Conflicts #

Mutual exclusion. Starting A while B is Active creates a stop operation for B — source ConflictResolution, cause ConflictEviction — and A does not start until B has left every state in which it could still be running.

Conflicts are symmetric. If A declares Conflicts = ["B"], starting either one stops the other; B does not have to declare it reciprocally, and peinit scans both a starting service's own conflicts and everything that declares a conflict against it.

If both A and B are boot-triggered and they conflict, graph validation detects an unresolvable conflict and fails both with ValidationError.

A missing conflict target is silently dropped — there is nothing to conflict with.

Note

Conflicts is for real mutual exclusion: two services binding the same port, or two implementations of one role where exactly one must run. It is not a way to solve resource contention that has a better answer.

7.1.5 Ordering and self-reference #

Dependencies imply start ordering, and — except for BindsTo — imply nothing about stopping. peinit starts dependencies before dependents; during shutdown it reverses the same graph and stops dependents before dependencies (§12.2), derived from the one graph rather than from a separate stop-ordering configuration.

A service can not name itself in any dependency field. peinit rejects a self-reference at graph validation as a CycleDetected failure, which is what it is — a cycle of length one.

7.2 Graph Validation

Peios / Reference / peinit / Dependencies

peinit validates the dependency graph before executing it. Validation runs once per graph build — at boot, on an administrator-requested on-demand start's transitive closure, and on a reload-config — and is never incremental.

7.2.1 Cycles #

peinit topologically sorts the graph; if the sort fails, a cycle exists. Detection returns all cycles rather than stopping at the first: each detected cycle's members are removed and the search re-run until the graph is clean.

Every service in a cycle is failed with cause CycleDetected, and the cycle path is logged so an administrator can see what to break.

If any service in a cycle is Critical, peinit downgrades to Safe mode (§2.6) rather than rebooting. The cycle is a configuration error, and rebooting would find it again.

7.2.2 Missing targets #

RelationshipA missing target means
RequiresThe dependent is failed with DependencyFailure.
BindsToThe same — treated as a missing Requires.
WantsSilently dropped.
ConflictsSilently dropped.

This holds in every mode. Safe mode drops a hard dependency on a service it excluded — that is its own rule (§2.6), and without it excluding a service would fail everything downstream and Safe mode could start almost nothing. Only that case drops. A target missing from the registry or disabled by an administrator is a configuration error rather than a Safe mode exclusion, and blocks the dependent in Safe mode exactly as in Full.

7.2.3 Validation errors #

A service that hits one is failed with cause ValidationError and never started:

  • The flap constraint, HealthCheckRetries × HealthCheckInterval < RestartWindow (§5.6).
  • An invalid timer calendar expression (§9.1). This one is checked across every definition, not only those in the graph.
  • Two boot-triggered services that conflict with each other. Both are failed. Safe mode applies if either is Critical.

7.2.4 Validation warnings #

Logged, and do not prevent boot:

  • A service using Readiness=Alive that something else depends on hard. Alive readiness means the process exists, which is no guarantee it is functional, so anything waiting on it is waiting on the wrong thing.
  • Services that need a role no service fills — in practice authn, needed by every service whose Identity is not SYSTEM. Warned about rather than failed, because a missing hard dependency rejects the whole reload transaction, and that would prevent reloading the very definition that installs the missing provider. See §7.6.

7.2.5 Multiple findings #

A service can attract more than one finding in one pass — being both in a cycle and missing a Requires target, say. The runtime state records a single primary cause, chosen by precedence:

  1. CycleDetected
  2. ValidationError
  3. DependencyFailure

The precedence affects only which cause is stored. Every other finding for the service is retained beside it, in discovery order, and the operation's failure message enumerates all of them:

CycleDetected: dependency cycle a -> b -> a (also: ValidationError:
health check interval exceeds the restart window) [2 findings]

The primary comes first and unqualified, so a service with one finding reads exactly as it always did. A higher-precedence finding arriving later demotes the previous primary rather than deleting it — breaking the cycle should not be what it takes to discover the second fault.

Every finding is also emitted as its own peinit.graph.validation.failed KMES event, carrying graph.phase boot and the finding as outcome.reason. The console lines are for whoever is watching the boot; the events are the account that survives it.

HardDependencyBlocked — blocked because a dependency is blocked — gets its own reason, hard-dependency-blocked, rather than being reported as a missing dependency, which would claim the target does not exist when it does. It has no reload-path equivalent, because reload rejects wholesale instead of propagating a block.

The reload path behaves differently, because its consequence is different. Validation there accumulates every finding, encodes each as its own event under graph.phase reload-config, and then rejects the entire reload — the previous generation stays live and the findings return to the caller (§10.4).

Boot marks individual services and continues; reload reports everything and changes nothing.

Both use the same event type deliberately: one consumer filter catches validation problems in either regime, and phase says which.

7.2.6 On-demand starts #

Before dispatching an administrator-requested on-demand start, peinit runs the shared definition validator over the services the start plan would activate. An unschedulable health check, an invalid health-check restart window or an invalid timer schedule rejects the plan with INVALID_STATE; no service from that plan is launched. This includes definitions reached through dependencies.

Definitions outside the plan, and dependencies whose running state already satisfies the request, do not make it fail. Missing or disabled hard dependencies retain the ordinary blocked-plan handling; dependency cycles retain the existing cycle refusal. Conflicting boot triggers are not themselves a reason to reject an explicit start.

This check also applies to an administrator restart when the service has no running process and the request builds an on-demand start plan. A queued administrator operation is checked when promoted into such a plan; rejection fails that operation with an invalid_state reason and leaves other queued operations eligible for promotion. It does not terminate the supervisor loop.

Internal starts from restart policy, timers, BindsTo recovery, OnFailure and TTY release retain their existing closure and cycle checks, without this additional definition-validation refusal, including when a queued internal operation is promoted. In particular, an invalid nonboot OnFailure target must not roll back the source service's transition to Failed. The stop/start leg of a restart of a running service and a deferred Backoff restart also retain their existing internal start behavior. Boot and reload-config validation remain as described above.

7.3 Graph Execution

Peios / Reference / peinit / Dependencies

Executing a graph means starting the services whose dependencies are all satisfied, and doing it again each time something becomes satisfying, until nothing is left.

execute_graph(graph, max_parallel):
    ready = services with no unsatisfied dependencies
    in_flight = 0

    while ready is not empty or in_flight > 0:
        while ready is not empty and in_flight < max_parallel:
            begin_start(ready.dequeue())
            in_flight += 1

        match wait_for_event():
            ServiceSatisfied(s):
                in_flight -= 1
                for each dependent of s:
                    if all its dependencies are satisfied:
                        ready.enqueue(dependent)

            ServiceFailed(s):
                in_flight -= 1
                propagate_failure(s)

MaxParallelStarts bounds the concurrency, counted per context as the members running.

The events are not only member completions. A dependency naming a readiness level is settled against the live service table rather than the graph's own bookkeeping, and the arrival of a LEVEL= — or the publisher leaving a dependent-satisfying state — re-runs the release for every context holding an edge on that service.

7.3.1 Execution contexts #

A graph execution is a retained object, not a transient loop. peinit holds a context carrying its members, their dependencies and their status, and there are two kinds: one boot context built from the boot plan, and an on-demand context per explicit start, built from that service's validated transitive closure.

Both use the same scheduler, the same satisfaction rules, the same failure propagation and the same parallelism, but they are distinct runtime objects — which matters because they can overlap.

An operation is associated with every context that created or adopted it. One operation can belong to more than one active on-demand context: two administrators starting different services that share a dependency both end up merged into the same already-starting operation for it, and both contexts need to hear how it turns out.

So when a pre-start outcome is terminal for an operation, peinit dispatches the corresponding graph event once per associated context. An operation with no associated context completes or fails normally, and its waiters are notified, but no graph event is dispatched.

A member whose dependent resolves without ever needing it is pruned — a dormant sub-tree is canceled rather than started, so an on-demand start that turns out not to need half its closure does not start that half.

A context is retired once every member has reached a terminal status — satisfied, failed, or pruned — which is exactly when no further graph event can be dispatched through it. Its operation associations go with it, except where an operation is also associated with a context that is still live.

Retirement happens on the operation-maintenance sweep rather than at the moment the last member goes terminal. The callers of a terminal outcome walk the graph events it produced and release the contexts those events name, so dropping a context inline would pull it out from under the rest of the same turn's work.

Without this a context and its associations persisted for the lifetime of the process. The memory was the smaller half: dispatching a terminal outcome walks every context associated with the operation, so on a long-lived machine where services are started regularly the terminal path grew steadily slower, in PID 1's single thread.

7.3.2 Failure propagation #

When a service enters Failed during graph execution:

  1. Everything that Requires or BindsTo it transitions to Failed with cause DependencyFailure.
  2. Everything that Wants it is unaffected and starts normally.
  3. Propagation is transitive: if A requires B and B requires C, and C fails, then B fails and then A fails.

7.3.3 On-demand start #

Starting a service explicitly resolves its dependencies first:

  1. Collect the transitive Requires and BindsTo closure.
  2. Collect the transitive Wants closure, best-effort.
  3. Validate the sub-graph — cycles, missing targets.
  4. Resolve conflicts, stopping whatever has to stop.
  5. Start the sub-graph with the same parallel algorithm. Dependencies started this way carry cause DependencyStart and operation source DependencyPropagation.

A service already in a satisfying state — Active, Completed, or Skipped — is not restarted. Its dependency is already met.

A disabled hard-dependency target blocks the dependent, on both paths. Disabled suppresses automatic activation and the service can still be started explicitly (§3.2) — but nobody started this one explicitly. Something that requires it did, and its administrator took it out of service deliberately, so starting it to satisfy someone else's dependency would defeat the flag by a route its description does not consider.

Starting the disabled service itself still works. That is the escape hatch, and it is unchanged.

A disabled Wants target is skipped rather than blocking anything: a soft dependency is advisory, so there is nothing to fail.

7.3.4 Shutdown ordering #

Shutdown reverses the graph: services with no dependents stop first, services that everything depends on stop last, derived by reverse topological sort from the same edges.

Only hard dependencies — Requires and BindsTo — contribute to the ordering. A Wants dependent can therefore be stopped after its target.

The ordering is entirely emergent from what the definitions declare. There is no floor and no pinning, so where the TCB services end up in the wave order depends on their declared dependencies being right.

7.4 The Boot and On-Demand Paths

Peios / Reference / peinit / Dependencies

The two ways a graph gets built differ in more than scope, and the differences are worth having in one place.

BootOn-demand
MembersEvery boot-triggered root plus its closureOne requested service plus its closure
A missing hard-dependency targetBlocks the dependentBlocks the dependent
A disabled hard-dependency targetBlocks the dependentBlocks the dependent
A validation findingThe service is failed, others continueThe start fails
Multiple findings on one serviceOnly the highest-precedence one is reported—
ConflictsTwo boot-triggered conflicting services fail bothThe conflicting service is evicted
ContextOne boot contextOne context per explicit start
Failure of the whole buildRecovery modeAn error to the caller

7.4.1 Where a definition error lands #

The three places a bad definition can be caught behave differently, and which one catches it depends on what kind of wrong it is:

  • Decoding. A definition that does not parse — an invalid name, a malformed trigger, an unclosed quote, a registry: check naming an uncacheable key, a duplicate field — is caught when the registry is read. It fails that service with ValidationError and the rest continue, at boot and on reload alike (§3.2).

  • Graph validation. A definition that parses but does not fit — a cycle, a missing target, a flap-constraint violation, an invalid calendar expression — is caught here, and fails that service at boot or the whole reload on a reload-config (§7.2).
  • Start. A definition that parses and fits but whose preconditions do not hold — a failed assert, an unresolvable identity, a missing binary — is caught when the service actually starts, and fails that activation (§5.2, §5.3).

The dividing line between the first two is whether the problem is visible in one definition on its own. Decoding sees one key at a time; validation is the first place that can see two definitions together.

7.5 Readiness Levels

Peios / Reference / peinit / Dependencies

network-online.target on systemd is famously meaningless, because "online" has no single definition. A service needing a default route and a service needing only a loopback address want different things, and one target cannot mean both.

peinit does not have an online target. A service says what it is waiting for, in the publisher's own vocabulary:

Requires = ["netd:routed"]
Wants    = ["timed:synchronised"]

netd:routed waits for netd to be active and to have published the level routed. netd on its own is unchanged — the ordinary "that service must be active" dependency.

7.5.1 The syntax #

<service>:<level>, split on the first colon. It rides on the existing Requires, Wants and BindsTo fields rather than a field of its own, because a level dependency is a service dependency with a stricter predicate: netd:routed subsumes netd. Each relationship keeps exactly the semantics it already has, applied to the stricter test.

It cannot collide with a service name. A service name can contain only letters, digits, ., _ and -, so a colon never appears in one, and no existing definition can accidentally become a level dependency.

A trailing colon — "netd:" — reads as a plain dependency on netd. It is a typo, and treating it as a request for the empty level would produce a condition nothing could ever satisfy.

7.5.2 Through a role #

The service side of the syntax can be a role instead of a name:

Requires = ["network:routed"]

network is filled by whichever service declares Provides = ["network"] — netd, on a shipped image — and peinit rewrites the entry to netd:routed before anything reads it, exactly as §7.6 resolves a role. The level rides across unchanged. Everything downstream — validation, the graph, svctl status — sees a level dependency on a service, and never learns a role was involved.

This is the form a definition should use for the network. The role is "the executor of Peios Network Policy's interface layer", and the levels are not the executor's own words but the specification's: PNP defines readiness as link, addressed and routed, and whichever service fills the role publishes those. A definition that says network:routed survives netd being replaced; one that says netd:routed does not.

Several services can fill a role; the entry then resolves to one level dependency per provider, and a Requires waits for all of them. A role no service fills is left as written and fails validation as the missing hard dependency it is, naming the role the definition wrote.

7.5.3 How a level gets there #

The service publishes it on the notification channel it already has, as LEVEL= beside READY=1 and STATUS=:

LEVEL=link
LEVEL=addressed
LEVEL=routed

All LEVEL lines in one datagram form one set: peinit atomically replaces the sender's previous set with the distinct nonempty values, before releasing any dependents, including when the same datagram carries READY=1. A datagram with no LEVEL lines leaves the set unchanged.

LEVEL= on its own clears the set. Empty values mixed with nonempty ones add no member; they do not clear other lines in the same datagram. peinit records the set against the sending service, and holds any dependent whose requested level is absent.

There is no subscription. peinit does not connect to netd's socket or timed's, does not need to find them before they exist, and carries no knowledge of their wire formats  — which matters, because PID 1 is the one process on the machine that cannot afford to fail to start.

7.5.4 Levels match set membership #

Requires = ["netd:addressed"] is satisfied when the active publisher's set contains addressed. Every member is an opaque, case-sensitive name; commas do not split a name into several levels.

peinit has no ordering over another daemon's vocabulary. A publisher that sends only LEVEL=routed does not satisfy an addressed dependent. netd knows which conditions imply others, so when routed it publishes link, addressed and routed together. A service should depend on the condition it needs, and the publisher reports every condition that holds.

7.5.5 A level is never stale #

peinit clears a service's entire level set whenever that service leaves a state that satisfies dependents. A level is a claim about a process that is making it, and one that outlived its process would hold a dependent open on a promise nobody was keeping — the exact failure the mechanism exists to prevent.

Because peinit is the process that notices a service exiting, this needs no timeout and no liveness check.

7.5.6 How the gate holds #

A level is settled at dispatch, not at planning. The plan decides what to start; whether a level is met is a live question — it can arrive after the target's own start completed (netd is active long before DHCP finishes) and be retracted while a dependent is still waiting — so the execution graph re-checks it against the service table every time it considers releasing the dependent, and holds the start until the answer is yes.

That check runs even when there is nothing to start. An already-active target is not part of the start plan, but the condition on it still is: the graph keeps a level edge to a service it is not starting, which is what makes Requires = ["netd:routed"] hold when netd is up and merely not routed yet.

Two events re-open the question. A level-set update arriving from the publisher releases every dependent whose requested level is now present — this is the only thing that can open a Requires or BindsTo gate, which take the exact level and nothing else. And the publisher leaving a state that satisfies dependents releases Wants waiters: a soft dependency waits only while someone is running who could still publish the level, and proceeds once nobody is — which keeps Wants failure-tolerant, the property that defines it.

A held start does not time out, and its StartTimeout runs from the moment the level arrives, not from when the start was asked for. Requires = ["netd:no-such-level"] holds the dependent indefinitely: the service stays inactive and the start operation stays pending, visible in svctl status as an operation that has not completed. That is the declared semantics, not a hang — the condition was never met, so the start never happened.

7.5.7 What happens on a drop #

Nothing, in this version. If a level falls away after a dependent has already started, the dependent keeps running and is not told.

That is a deliberate limit, not an oversight. The notification channel is one-way by specification (PSPU §4.16), so peinit has no way to tell a running service anything. A service that needs to react to a level changing while it runs should subscribe to the publisher directly — which is what resolvd does with netd today, and what any consumer that cares that much will want anyway, since it will need the detail rather than the fact.

peinit's contribution is the start gate: the moment when the service does not exist yet and so cannot subscribe to anything at all.

7.5.8 Published levels #

PublisherLevels
netd, as the role networklink → addressed → routed, defined by Peios Network Policy
timedunsynchronised, settling, synchronised, spike

Any service can publish a level; nothing about the mechanism is specific to these two. The vocabulary is the publisher's own — or, where the publisher fills a role a specification defines, the specification's — and needs no registration.

7.6 Derived Dependencies

Peios / Reference / peinit / Dependencies

Most dependencies are declared. One is not.

A service whose Identity is anything but SYSTEM cannot start until the authority is listening, because peinit has to ask it for a token before there is a process at all (§4.3). That is a hard dependency in every sense Requires means one.

It used to be nobody's. peinit hardcodes the socket the authority listens on, so the requirement was real on every boot, but the ordering existed only if a definition happened to declare it — and all three LocalService definitions in the tree did not. Three of three is the number that makes it a defect in the mechanism rather than in three definitions: the requirement is created by Identity, so Identity is what should produce the edge.

7.6.1 Provides #

A service names the roles it fills:

Provides = ["authn"]

A role is a virtual name — a capability, not a service. Virtual and real names share one namespace, exactly as they do for packages (PSPU §5.4): a dependency on authn is satisfied by a service literally called authn, or by any service providing it.

The indirection is the point. peinit knows it needs an authority and knows which socket to speak to, but the authority's name is registry data and none of peinit's business — an image can ship a different one. So the derived edge names the role, and peinit resolves it to whoever declares it.

Provides entries use the service-name grammar and never carry a readiness level. netd:routed names a condition on a service, and a role is not a service, so there would be nothing for the level to qualify; a level on a Provides entry is rejected rather than ignored.

The other side of a dependency can name a role, with or without a level. Requires = ["network:routed"] is rewritten to one entry per service providing network, the level carried across, before the definition set becomes a service table — the same pass, at boot and on every reload, that derives the edges below. Requires, Wants, and BindsTo are rewritten; a real service name is never mistaken for a role, a provider never gains a dependency on its own role, and a role no service fills is left as written for validation to report. See §7.5 for why the network is declared this way.

7.6.2 What peinit derives #

Before a definition set becomes a service table — at boot and on every reload, through the same code, because an edge that held until the first reload would be worse than no edge — peinit adds a Requires on each provider of authn to every service that needs the authority to launch.

A service needs it when its Identity is not SYSTEM, or when it has hooks and its HookIdentity is not SYSTEM. The second half matters: a SYSTEM service whose hooks run as LocalService materialises a token for them, and a definition that needs the authority for half its launch needs the ordering for all of it.

Three rules keep the derivation from doing damage:

  • A provider never gains a dependency on its own role. An authority declaring a non-SYSTEM identity would otherwise require itself, and a service that requires itself never starts.
  • An edge already declared is not added again, whether it was declared as Requires or BindsTo, and including one carrying a level. Requires = ["authd:ready"] already orders against the authority, and more strictly; adding a plain edge beside it would be a second edge to the same service saying less. BindsTo requires its target as well as binding to it, so the same holds for it.
  • Nothing is derived when no service fills the role. See below.

Because the result is an ordinary Requires, it needs no new kind of edge and behaves exactly like a declared one everywhere else — in graph validation, in graph execution, at shutdown, and in svctl status, where it appears as the dependency it is rather than as a hidden ordering.

Several services MAY fill one role; each becomes its own Requires, so the dependent is ordered after all of them. For authn this cannot arise — PGSS Logon §2.1 requires at most one authority on a running system — and where a future role allows several, ordering after all of them is the conservative reading and needs nothing new. peinit deliberately does not offer "wait for any one of them": that would change the release rule from every edge satisfied to every group has one satisfied, and would contradict Requires's failure rule, under which a target entering Failed fails the dependent.

7.6.3 When nothing fills the role #

An image whose services need a token and which ships no authority is broken. A reload of it produces a validation warning naming every service that cannot start, and succeeds anyway.

It deliberately does not invent an edge to a name no service answers to. That would be a missing hard dependency, and a missing hard dependency rejects an entire reload transaction — so an operator could not reload the definition that installs the authority. The image would be unrecoverable by the one mechanism meant to recover it.

The individual launches still fail, loudly, where the fault actually is: at the service that asked for a token and could not have one.

7.6.4 A role is not an online target #

§7.5 opens by rejecting network-online.target, and the objection there does not reach this mechanism. It is worth being explicit about why, because the two look alike from a distance.

The complaint about network-online.target is that "online" has no single definition: a service needing a default route and a service needing a loopback address want different things, and one name cannot mean both. The abstraction is over a condition, and the condition is ambiguous.

authn abstracts over no condition at all. It means "whoever answers ServiceAttest on the logon socket" — a protocol role, specified by PGSS Logon §2.19, which §2.1 says MUST have at most one occupant. There is exactly one thing it can mean, and what a dependent gets is the same thing it would get by naming the service directly.

network:routed passes the same test from the other direction. The role network is a position too — the executor of Peios Network Policy's interface layer — and routed is not peinit's word for "online" but the specification's word for one exact condition, a default route. The ambiguity that sinks network-online.target is absent because the condition is named, not the target.

The rule the two share: peinit does not invent vocabulary for conditions inside another service. A readiness level is the publisher's own word for its own state, or its specification's; a role is a name for a position in a protocol peinit already speaks. Neither is a target.

8.1 Jobs

Peios / Reference / peinit / Jobs and Operations

A job is one supervised process execution. Every fork peinit performs is a job: a service's main binary, a pre-exec hook, a post-exec hook, a reload command, a health check invocation, a submitted job (§8.5).

Jobs are the observable unit of what actually ran. Services are definitions carrying identity, policy, and configuration; jobs are instances. A restart creates a new job.

8.1.1 Lifecycle #

Created --> Running --> Completed
   |           |
   |           +------> Failed
   |           |
   |           +------> Abandoned
   +------------------> Failed
StateMeaning
CreatedThe job object exists but exec has not succeeded. The process can not have been forked, or it can be in pending post-fork setup with the error pipe unresolved.
RunningExec succeeded and the process is alive.
CompletedThe process exited successfully — code 0, or one in SuccessExitCodes.
FailedThe process failed, or peinit classified the job failed before the fork because parent setup failed.
AbandonedThe process survived SIGKILL.

Job states are simpler than service states because they describe a process rather than a policy. A service has Starting, Reloading, and Backoff because those are decisions; a job is running, or it finished, or it is stuck.

8.1.2 Fields #

Job {
    id:                 GUID       // UUIDv7
    service:            string?    // null for a submitted job
    job_type:           enum       // ServiceMain, PreExecHook, PostExecHook,
                                   // ReloadHook, HealthCheck, Submitted
    state:              enum
    pid:                u32?
    pidfd:              fd?
    resolved_identity:  string     // the resolved service, hook or submitter identity
    token_summary:      object     // the resulting SID, groups, privileges
    image_path:         string
    arguments:          string[]
    created_at_ns:      u64
    started_at_ns:      u64?
    ended_at_ns:        u64?
    exit_code:          i32?
    exit_signal:        i32?
    failure_cause:      string?
    cgroup_id:          string
    cgroup_generation:  u32
    activation_generation: u32
    operation_id:       GUID?      // null for a submitted job
    hook_index:         u32?
}

The rules that govern when the nullable fields are populated are what make a job record trustworthy:

  • id is assigned before the fork, so a job that never forks still has an identity.
  • pid and pidfd land on the record only once exec success is confirmed by EOF on the error pipe. Until then they are held in pending setup state and the job is Created.
  • An exit observed during that window is held, not applied. peinit resolves a reaped child to a job by PID, and inside this window no job carries the PID yet — a short-lived process can be gone before the error pipe is read. The exit is kept against its PID and replayed once the job has been started and can receive it. Discarding it would be unrecoverable: the job would be started against a PID that is already dead and reaped, and no second SIGCHLD is coming, so it would stay Running for ever. A reaped PID that matches no job and no pending setup is genuinely not peinit's — PID 1 reaps orphans it never started — and is ignored.
  • A notification sent during that window is not refused for it. A service can send READY=1 before the turn that reads its setup status. peinit reads the status first and authenticates the datagram after. If the status cannot yet be read, peinit holds the datagram until it can (§10.5).
  • A setup failure takes the job straight from Created to Failed. ended_at_ns records the classification time, failure_cause records what went wrong, and pid, pidfd, started_at_ns, exit_code and exit_signal all stay null. There was no process to have a PID or an exit status.
  • exit_code and exit_signal are populated only when peinit observed an exit — never both, since a process either exits or is killed.
  • For an Abandoned job, ended_at_ns records when peinit stopped supervising, and the exit fields stay null. Nothing exited.

resolved_identity is the identity string — SYSTEM, LocalService, a SID — that was resolved for the execution. For a submitted job it is the job identity's user SID, since no name was ever involved (§8.5). token_summary is what the resulting token actually contains. They are separate because they can differ, and the identity field exposed in status views and job events is the former.

8.1.3 Retention #

peinit tracks active jobs in memory. When a job reaches a terminal state it emits a structured event carrying the full record and then drops the job. There is no job history in peinit, and no structure that could hold one.

eventd is the historian. It consumes those events from the KMES kernel ring buffer, and a query for a service's past jobs is a query to eventd.

A submitted job is the one partial exception: its record is dropped like any other, but the jobs system keeps its own entry for a further 60 seconds so that a submitter polling for the outcome can still read it (§8.5). That entry is a retained answer, not a history.

8.1.4 The launch queues are hints #

A job awaiting launch is queued by id, in one of six queues — service main, pre-start hook, post-start hook, control, health check, and submitted. The queues hold ids; the store holds the records, and the store is the only truth.

They can therefore disagree. Any path that finishes a job in Created drops the record, and a path that does not also clear the queue leaves an id behind pointing at nothing. Requiring every such path to remember was a poor trade: there are around a dozen of them, nothing enforced it, and the cost of one omission was that peinit's runtime loop ended — which ends PID 1.

So a drain that meets an id with no record discards it and moves on to the next, rather than treating it as an error. A live entry behind a stale one still launches, so one bad id cannot stall a queue. This is why the ordering rule is worth stating plainly: keeping the queue in step is a tidiness obligation, not a correctness one.

Discarded entries are counted and reported on the work pump's turn, so a bookkeeping fault shows up as a number rather than disappearing. A count that is not zero means some path finished a job without clearing its queue entry, and that path is a defect even though it is nonfatal.

8.1.5 Ownership #

ConcernOwner
Restart policy, dependencies, health check schedule, ErrorControlService
Current state — Active, Failed, …Service
PID, pidfd, exit code, exit signalJob
Execution timestampsJob
Identity and tokenJob
cgroup assignmentJob
Log correlationJob
Submitter, job descriptor, progress, retentionSubmitted job entry (§8.5)

A service tracks its current main job's identifier, and a status query returns it.

8.2 Operations

Peios / Reference / peinit / Jobs and Operations

An operation is a requested state machine action on a service, as a first-class object. Control commands do not mutate state directly: every one creates an operation that is validated, queued, resolved against whatever else is in flight, and executed by the event loop.

Operations exist because peinit serves concurrent callers — administrative tools, automated triggers, other services. Without them, two commands arriving together collide with whatever behavior falls out; with them, the resolution is explicit and observable.

8.2.1 Lifecycle #

Pending --> Running --> Completed
  |           |
  +-> Merged  +-------> Failed
  |           |
  +-> Cancelled +-----> Aborted
  |
  +-> Failed
StateMeaning
PendingValidated and queued, waiting on a precondition.
RunningExecuting.
CompletedThe goal was reached. Start: Active for Simple, Completed, or Inactive for Oneshot. Stop: the service is stopped. Reload: the reload resolved.
FailedThe goal was not reached — or the operation's maximum lifetime expired while it was still Pending (a start peinit is holding on a dependency has no lifetime, §7.5) — or peinit could not execute it (below).
MergedMerged into an existing identical operation, whose identifier is recorded.
CanceledTerminated while Pending. It never executed.
AbortedTerminated while Running.

An operation can also fail because peinit could not execute it: the matrix admitted it and then the boundary found nothing to act on — no current main job, a transition the state machine does not permit. That is peinit's fault rather than the service's, and it is contained to the one operation. The operation fails with the result internal_error: <cause>, the service keeps the state it had, a [FAILED] console line names the service, the operation and the cause (peinit: service <service>: <type> operation <id> failed before it began: <cause>), and the runtime loop carries on. A caller waiting on the operation is answered INTERNAL_ERROR (§10.1).

The same rule covers every path that is about one service — a job terminal, a setup status, a health probe, a lifecycle deadline, a notify datagram, an event the ring refuses. An internal error there fails that service under InternalError (§6.3): its job is retired, its operation fails with internal_error: <step>: <cause>, a [FAILED] line peinit: service <service>: internal error at <step>: <cause> and a peinit.internal-error.contained event (§8.4) announce it, and the runtime loop carries on. Only an error about supervision itself — the wait, event source registration, the listeners, the event ring refusing even the small peinit.event.dropped, shutdown finalization — ends the loop and enters recovery (§2.8). A bug peinit can attribute to one service costs that service; it does not cost the machine its control socket.

A lifecycle deadline that raised is removed once its error is contained, so it is announced once, not again on every timer turn. One that peinit cannot remove is retried at most once a second, and a retry that raises the same error and changes nothing is not announced again.

Canceled and Aborted are the same idea at different points: never ran versus was running. Why it happened is a property of the event, not of the state.

Two things reach Aborted. A conflicting operation superseding this one, and a Restart whose target's definition is withdrawn while its stop leg is draining — the stop still finishes, but there is nothing to start, so the operation is aborted with the reason definition_removed_during_restart_stop_leg (§3.8).

A start that is aborted or canceled takes its readiness deadline with it: the start is not waiting for READY=1, and ending its main process is the superseding operation's job. A readiness deadline whose operation has ended by the time it comes due is dropped, not acted on.

8.2.2 Fields #

Operation {
    id:               GUID
    operation_type:   enum    // Start, Stop, Restart, Reload, Reset
    service:          string
    state:            enum
    created_at_ns:    u64
    started_at_ns:    u64?
    completed_at_ns:  u64?
    source:           enum
    caller:           token_summary?   // admin-initiated only
    result:           string?
    merged_into:      GUID?
}

8.2.3 Sources #

Why peinit created the operation:

SourceMeaning
AdminA control client asked for it.
BootThe Phase 2 boot plan.
ShutdownThe shutdown lifecycle.
DependencyPropagationA start operation created one for an unsatisfied dependency.
RestartPolicyA restart policy generated a start.
TimerA timer trigger fired.
BindsToRecoveryA bound target returned to Active.
BindsToPropagationA bound target stopped.
ConflictResolutionA conflict evicted the running service.
OnFailureA failed service's fallback handler.
TtyReleaseA service released a terminal another service was waiting for.

Graceful shutdown creates a Stop operation with source Shutdown for each participant in its stop waves (§12.2). All are requested when the plan is fixed; each starts when its wave becomes eligible. These records observe the shutdown planner. They do not enter the ordinary control queue or replace an existing administrator operation, whose retained stopping deadline still applies. A later-wave observation can fail its Pending lifetime without authorizing an early signal or canceling the service's eventual stop.

A participant that exits before its wave can complete its observation without ever starting it; a crash fails it. Once stopping, reaching Inactive completes it, while a stop timeout, global timeout or forced reboot fails any observation still live. A failed observation is not completed again when the process is subsequently reaped.

8.2.4 The types #

Start creates a job for the target. Unsatisfied dependencies produce their own start operations with source DependencyPropagation. It completes when the service reaches Active, Completed or Inactive as appropriate, or Skipped when pre-start conditions do not hold.

Stop sends SIGTERM, arms StopTimeout, escalates to SIGKILL. It completes when the service reaches Inactive, or Failed after a conflict eviction or bound-dependency propagation.

Restart is a stop then a start, tracked under one identifier across both phases, and the type stays Restart throughout for observability.

Reload issues the reload command or signal (§6.5) and completes when the reload resolves. Unlike the other lifecycle commands it defaults to not waiting — the caller gets the identifier immediately.

Reset clears Failed, Abandoned or Skipped, taking the service to Inactive. It is synchronous.

8.2.5 Timeouts #

A start, reload, or reset inherits the target's StartTimeout as its maximum lifetime; a stop inherits StopTimeout. A restart has two legs, each enforced against its own timeout, with the sum as the overall lifetime. A start the graph is holding has no lifetime while every unsatisfied dependency it waits on is a fact with no clock of its own — a readiness level not yet published (§7.5), a target in Backoff (§6.1), or a target itself held only on such facts; it stays Pending for as long as those facts are undecided, and a caller waiting on it waits with it. A dependency that is itself starting is bounded by that service's StartTimeout, and a dependent waiting on one keeps its own lifetime, measured from creation as below. When a hold ends, the released start's lifetime runs from the release. Queue time behind another operation is not a hold and still counts.

This also applies to an on-demand start whose Requires or Wants target is already in Backoff. The request is accepted and held; it does not bypass the target's remaining restart delay. Repeated requests merge into the pending operations. The target's deferred start receives its lifetime when the restart deadline releases it. If the target is stopped instead, hard dependents fail and soft dependents can proceed.

For a transitive hold, the required release point can precede the dependent's own dispatch: when its dependency becomes clocked, the dependent must receive its full lifetime even if it is still Pending, waiting for that dependency to finish. Its later dispatch must not restart that lifetime again.

The clock starts at creation, including queue time — except across a hold (§7.5), during which it does not run. From the caller's point of view they have been waiting since they sent the command, not since peinit got round to it. A start that sits Pending behind a stop for longer than StartTimeout fails without ever running.

8.2.6 Retention #

Pending and Running operations are held in memory. A terminal operation is emitted as an event and dropped after a grace period of 60 seconds — long enough for a polling client to collect the result.

peinit keeps no operation history, for the same reason it keeps no job history. eventd is the historian.

8.3 Conflict Resolution

Peios / Reference / peinit / Jobs and Operations

When a new operation is requested and one for the same service is already Pending or Running, peinit resolves the two.

8.3.1 Merging #

An operation of the same type merges. The new caller receives the existing operation's identifier, and from their point of view their request is in progress — they neither know nor need to know that it merged.

ExistingNewResolution
StartStartMerge
StopStopMerge
ReloadReloadMerge
RestartStartMerge — a restart already includes a start

Restart is not mergeable with itself. A second restart while one is in progress is queued. The one place that does not apply is a restart deferred by a backoff (§10.3): it is Pending with nothing running for a second one to queue behind, so a second restart in Backoff merges into it.

8.3.2 Cross-type #

ExistingNewResolution
Start (Pending)StopCancel the start, create the stop
Start (Running)StopAbort the start, create the stop
Start (Pending)RestartCancel the start, queue the restart
Start (Running)RestartQueue the restart
Stop (either)StartQueue the start
Stop (either)RestartQueue the restart
Restart (Pending)StopCancel the restart, create the stop
Restart (Running)StopAbort the restart, create the stop
Restart (either)RestartQueue
Reload (Pending)StopCancel the reload, create the stop
Reload (Running)StopAbort the reload, create the stop
Reload (Pending)RestartCancel the reload, create the restart
Reload (Running)RestartAbort the reload, create the restart
Anything (either)ResetReject

Combinations outside this table are rejected: a new Reload while a Start, Stop or Restart is active. A new Start while a Reload is active is not rejected — a reloading service is already where a start would take it, so the command is answered with the service's status and creates no operation, before conflict resolution is reached at all.

8.3.3 The principles #

  1. Stop wins over start. An explicit stop always takes priority. The administrator said stop, so stop; a queued start can follow.
  2. Later supersedes earlier. Start then immediately stop means the stop wins and the start is canceled, recorded as superseded.
  3. Merging is transparent. The merged caller gets the original identifier and blocks on the original operation's outcome.

Reset is rejected outright while anything is in flight, because reset means "clear a terminal state" and nothing in flight has one.

8.3.4 Dependency propagation #

When a start executes against a service with unsatisfied dependencies, peinit creates start operations for them:

  • Requires — source DependencyPropagation. If one fails, the parent operation fails with DependencyFailure.
  • Wants — source DependencyPropagation. If one fails, the parent continues.
  • BindsTo recovery — source BindsToRecovery, created when a bound target returns to Active, for dependents sitting in Failed with cause BindsToPropagation.

Dependency-created operations follow the same resolution rules as administrator-created ones. If a dependency is already starting because something else also depends on it, the operations merge — and both graph execution contexts are then associated with the one operation (§7.3).

BindsToRecovery restarts are not subject to the restart budget. They are created because a dependency returned, not because anything failed.

8.3.5 Restart policy and timers #

A restart-eligible failure creates a start operation with source RestartPolicy once the backoff delay elapses.

It goes through the ordinary validation and resolution: if an administrator has already sent a stop, or the budget is exhausted, it is rejected.

A timer firing creates an operation based on the service's current state:

TypeStateAction
OneshotInactive, Completed, FailedCreate a start, source Timer.
OneshotActive, StartingSet the pending flag. One catch-up run, no operation.
SimpleInactive, FailedCreate a start, source Timer.
SimpleActive, StartingNo-op. The firing is recorded.

The Oneshot catch-up creates its start when the current run completes. Multiple missed firings collapse into one pending run.

8.3.6 Boot and shutdown are not operations #

Boot and shutdown are modes peinit enters, which then generate per-service operations. There is no "shutdown operation" to observe or cancel. Boot-generated starts use source Boot.

Shutdown-generated stops use source Shutdown, and they are the one exception to the tables above. They are created outside conflict resolution: a Shutdown Stop does not merge into, cancel or abort an administrator's Stop or Restart already in flight, but exists beside it, so that operation keeps its identity and its retained timing (§12.2).

8.4 Event Emission

Peios / Reference / peinit / Jobs and Operations

peinit emits a structured event at every job and operation lifecycle transition, and for its own records. All of them go into the KMES kernel ring buffer through kmes_emit, encoded as msgpack per the KMES event-record format (Peios Kernel TRM §2).

There is no event socket. Structured events are not sent to eventd over any connection. eventd consumes them from the ring buffer, which is why they survive eventd being down, being restarted, or not existing yet. The only thing peinit sends eventd over a socket is service output (§11.4), which is a different path with different guarantees.

8.4.1 Names and shape #

Every type peinit writes is under its platform root, peinit, and every payload is a nested map whose fields sit at their catalog paths (PGSS §6.4): the job is object.job.guid, the service object.service.name, the client that asked subject.token.sid, the result outcome.success. A value peinit does not have is an absent key, never nil; SIDs are written in binary (bin.sid), job and operation identifiers as binary GUIDs (bin.guid) that read back as the text svctl shows, enumerated values in kebab-case (service-main, explicit-start), and times as nanoseconds since the Unix epoch.

peinit's fragment, /usr/share/evman/peinit.evman, describes every type and field, and the Events reference generates its pages from it.

No event carries a principal's name, peinit's own log wording, or Rust debug output. What a person reads is on the console; what a consumer queries is in the fields.

8.4.2 The emission policy #

Before peinit builds an event that is not essential, it asks the emission policy, Machine\Generic\Events (PGSS §6.9): a type switched off is never built, let alone written. With nothing set, a standard type is on and a verbose type is off. peinit opens one view of the policy for the life of PID 1; it needs no registry to open, decides by tier until the registry is readable, and applies a committed change to the next decision.

Four types are essential and never ask: peinit.boot.downgraded, peinit.recovery.entered, peinit.critical-service.failed, and peinit.event.dropped. Each is rare, and each is the only record of what it describes. The verbose types are peinit.job.created, peinit.job.status.reported, peinit.operation.started, peinit.operation.merged, peinit.graph.operation.ended, peinit.config.reload.deferred, peinit.notify.status.reported, and peinit.notify.progress.reported; everything else is standard. Setting Enabled = 1 on Machine\Generic\Events\peinit turns all of them on.

8.4.3 Job events #

peinit.job.created — the job object exists, before its process does. Carries the job, its type and state, its service and the activation generation it serves, the operation it serves, the executable, and the token it will run as.

peinit.job.started — exec succeeded. Adds the process ID (object.process.pid) and the cgroup (object.cgroup.path).

peinit.job.ended — the process exited or was killed, or the job ended without starting. Carries the whole record: the terminal state, outcome.success (true exactly for completed) with the failure cause as outcome.detail, the exit code or signal, the executable and arguments, the times it was created and started, its duration, and its cgroup and cgroup generation.

The token a job runs as is on each once peinit holds it: its user and group SIDs, and its present and enabled privileges as flags. A service's token is minted as its process is set up, so its peinit.job.created carries at most the user SID of a well-known identity.

peinit.job.ended cuts object.job.arguments to 32 KiB of whole arguments; object.job.arguments-truncated and object.job.arguments-count say so. An event the ring refuses outright is dropped, counted, and replaced by a peinit.event.dropped naming its type, its length, its service and job, and the error number, and a [ WARN ] line reports it; only the ring refusing that small event is fatal (§8.2). The count of drops is the console's, and the trail's is the number of those records. peinit.internal-error.contained records an error peinit contained to one service (§8.2): the step, the service, the job, and whether the service was failed. The error's text stays on the console and in the failed operation's result.

A submitted job's lifecycle rides the same three events with no service, no activation generation and no operation: the keys are absent. Two more are its own:

peinit.job.status.reported — the job reported STATUS or PROGRESS. Carries the job, the submitter's SID, and notify.status and notify.progress.* as retained after the datagram. Written at most once per job per second; a datagram inside the window updates the view and writes nothing (§8.5).

peinit.job.output.dropped — the submitter's output sink stopped draining and peinit began dropping its copy of the job's lines. Once per job, on the first drop; the record in eventd is unaffected (§11.1).

8.4.4 Operation events #

Every operation event carries the operation (object.operation.guid), its type, source and state after the transition, and its service. An operation a client's command created also carries the client as subject.token.sid; one peinit created itself has no subject.

EventAdds
peinit.operation.requested—
peinit.operation.started—
peinit.operation.endedoutcome.success, outcome.detail, object.operation.duration
peinit.operation.mergedobject.operation.merged-into.guid

peinit.operation.ended is one type for the four ways an operation can end other than merging — completed, failed, canceled while pending, aborted while running — and object.operation.state says which. outcome.success is true exactly for completed. A merged operation has no outcome of its own: the one it merged into decides it.

object.operation.duration is measured from the request, not from the start of execution — the same reasoning as the operation timeout — and is absent on a canceled operation, which never ran. What a caller waited is what matters, and queue time is part of it.

The operation's result, in the words the control interface gives a client (inactive, startup killed by shutdown), is outcome.detail, whichever way it ended. The control interface's operation view calls the same text result or error (PSPU §4).

8.4.5 Ordering #

When one runtime step produces several lifecycle events, peinit emits them in causal order before committing the retained state for that step. For a terminal pre-start graph dispatch, the terminal event for the operation whose outcome satisfied or failed the graph input precedes the events for the operations that dispatch releases, which preserve graph dispatch order.

Every operation in a graph context is requested when the context is built rather than when its turn comes, so what a release emits is peinit.operation.started.

8.4.6 Peinit's own records #

peinit's own records go through the same path:

  • peinit.on-failure.suppressed when the fallback chain guard trips;
  • peinit.graph.validation.failed and peinit.graph.validation.warned for validation findings, one per finding, and peinit.boot.downgraded for each finding that forced Safe mode;
  • peinit.config.reload.applied for an explicit reload-config and for the reload that ends the boot window, and peinit.config.reload.deferred for a reload during it (§3.7);
  • peinit.notify.rejected for a refused notification datagram, and peinit.fd-store.rejected for a refused descriptor;
  • peinit.notify.status.reported, .errno.reported, .exit-status.reported, .stopping.reported and .progress.reported for the event-emitting notification fields, the last at most once a second for each activation (§10.5);
  • peinit.cgroup.leaked the first time a sub-cgroup is found still populated after its post-kill deadline (§5.7);
  • peinit.graph.operation.ended for a graph member's terminal outcome;
  • peinit.recovery.entered for the reason peinit dropped to a recovery shell (§2.8);
  • peinit.critical-service.failed and peinit.service.abandoned from the shutdown path (§12);
  • peinit.service.reload.timed-out for a reload a service started and never confirmed (§6.5).

Records are events rather than logs, and that distinction is the point: the ring buffer persists from the moment PKM loads, so a recovery during Phase 1 is captured before the registry exists, let alone eventd.

8.4.7 Access decisions #

peinit writes no event of its own for a refused command. Every access check it makes goes through KACS AccessCheck, and KACS records the decision, as kacs.audit.access.checked, when the descriptor's SACL asks for it (PGSS §6.7). peinit's compiled-in descriptors — the default service descriptor, the control descriptor, and a submitted job's default — each carry a SACL auditing every refusal, for everyone, so a denial is recorded unless a descriptor says otherwise (§4.6, §13.4). A refusal also leaves a debugging line on the console, written only at peios.quiet=0.

So that the record says what was decided on, each check passes KACS an audit context naming its object, which the kernel copies into the record beside fields.attestation.userspace:

CheckedContextThe record carries
A service{kind: "service", service: {name}}object.kind service, object.service.name
A job, on either socket{kind: "job", job: {guid}}, the GUID in binaryobject.kind job, object.job.guid
The control door{kind: "peinit-system"}object.kind peinit-system

The rights in access.requested and access.granted are decoded against object.kind: the SERVICE_*, JOB_*, and SYSTEM_* tables (§4.6, §8.5, §10.2). job-list checks every job it might list against that job's own descriptor, so each job it leaves out is one more decision for the job's SACL.

peinit holds SeAuditPrivilege enabled for this: without it KMES refuses its events, and the access-check path writes no record (§13.2).

8.5 Submitted Jobs

Peios / Reference / peinit / Jobs and Operations

A submitted job is a supervised process whose definition arrived on the jobs socket rather than from a service definition. It has no name, no policy, and no operation: something asked for it, peinit ran it under an identity the asker was entitled to confer, and it is managed by whoever the job's own Security Descriptor admits. The protocol is PSPU §7; this chapter is how peinit implements its side.

Two shapes drive the design, and one mechanism serves both. A task — a backup, a migration — is submitted by a broker on behalf of the principal it is serving, runs to completion and reports progress on the way. A session — a per-logon host process — is submitted with a freshly issued logon token and one end of a socketpair, and lives until something stops it. Nothing in peinit distinguishes them.

8.5.1 Two doors #

The control socket is an administrator's door: its commands change the state of the system's services, and its descriptor admits the principals entitled to do that. Submitting a job is a different permission held by a different population, so it has a different socket, /run/services/peinit/jobs.sock (§10.7), with a different descriptor. The filesystem says who can submit and who can administer, separately, and peinit carries no policy of its own about either: being able to connect to the jobs socket is the permission to submit, and peinit performs no access check before a submit.

What a caller can do to a job is a third question, answered by the job's own descriptor. A submitter manages its jobs on the jobs socket; an administrator observes and stops them from the control socket with job-list, job-status and job-stop (§10.2). Both doors check the same descriptor with the same rights.

8.5.2 Two identities #

Every submission involves two identities, and peinit keeps them apart.

The submitter is the connection identity: the peer token captured once, at accept, exactly as the control socket captures it (§10.1). It is recorded on the job, it is what the quota counts against, and it is the owner of the job's descriptor. A submitter that connects while impersonating is recorded as the principal it was impersonating.

The job identity is what the process runs as. It is established in exactly one of two ways, and the boundary that does it — LinuxJobIdentityProvider — has no third:

  • No token attached. peinit opens the primary token of the connecting process through the kernel's handle on it. The handle comes from SO_PEERPIDFD at accept; the token comes from peios_token_open_process on that pidfd with QUERY | DUPLICATE. The job then has the identity a child of the submitter would have had — its primary token, with no impersonation inherited  — so a submitter that was impersonating when it connected produces a job running as itself while being recorded as a submitter under the impersonated identity. A submitter that wants the impersonated identity on the job attaches it.
  • A token attached. The kernel delivered a token with the submit message through KACS_SCM_TOKEN, having run the impersonation gates with the submitter as installer and recorded on the token the lower of the socket's level and the source's own (Peios Kernel TRM §3.5). peinit uses that token as it arrived, at QUERY | IMPERSONATE | DUPLICATE.

Either way the source is duplicated to a primary token at its own impersonation level, with TOKEN_ALL_ACCESS, and the duplicate is what the child installs. The level carries through: a job started from an Impersonation-level token cannot convey Delegation, and a submitter that needs it — for a session that will authenticate onward on its user's behalf — sets its own jobs connection to Delegation before attaching, because the attach is clamped to the socket's level.

peinit refuses, with BAD_TOKEN, a source whose impersonation level is below Impersonation  — an Identification-level token cannot pass an access check and an Anonymous one is not an identity to run a process as — and a source it cannot duplicate. It refuses nothing because of who the token names. Whether the submitter can run a job as that identity was the kernel's decision, made when the token was conveyed, and a second decision inside peinit could only disagree with the first.

There is no identity field in the definition, and no route by which a plain descriptor passed with SCM_RIGHTS becomes a job identity. A descriptor passed that way is not gated by the kernel — whoever holds an fd can pass it — and it would be the one path worth attacking.

The prepared token is a raw descriptor held on the job's entry until the launch takes its own duplicate of it (materialize_prepared_token, §4.1). A submission refused after the token was prepared closes it on the way out.

8.5.3 The submission #

submit runs in this order, and a refusal at any step leaves nothing behind — no record, no event, no quota consumed, and every descriptor the message carried closed:

  1. Parse and validate the definition against the attachment count (below). A malformed definition is INVALID_ARGUMENTS before any identity work is done.
  2. Refuse during shutdown with INVALID_STATE. The other four commands keep working while the system goes down.
  3. Establish the job identity, as above.
  4. Check the quota. peinit counts the submitter's live jobs — those not yet terminal — by submitter SID against Machine\System\Init\MaxJobsPerSubmitter, default 64. SYSTEM (S-1-5-18) is exempt. At the bound the answer is QUOTA_EXCEEDED. A job stops counting the moment it is terminal, not when its retained record is dropped.
  5. Build the job's descriptor: the one the submission supplied in SDDL, used as given, or the default (below).
  6. Create the record, the entry and the launch queue entry, in one SupervisorWork transaction.

The job is two things in peinit's state. The job record is the same JobRecord every fork gets (§8.1), with job_type: Submitted, no service, no operation, the job identity's user SID as resolved_identity, and a cgroup id under /sys/fs/cgroup/peinit/jobs/ named by the job's GUID. The entry is what the jobs system holds beside it: the submitter, the job identity's user SID and logon session, the definition, the descriptor, the prepared token, the attached descriptors with their names, the output sink, readiness and the retained STATUS and PROGRESS, any stop in progress, and once the job is terminal its outcome and retention deadline. Records are dropped when terminal, as every job's is; entries outlive them for the grace period, which is how a terminal job still answers status.

The submit is answered when the job **leaves created ** — on exec confirmation or on launch failure — and not before. The submitter's connection holds a pending wait until then, reads nothing further, and is not idle. A running job's answer carries a duplicate of the job's pidfd as SCM_RIGHTS; a failed launch is still "status": "ok", with a terminal view whose cause says why. A pidfd that cannot be duplicated is answered INTERNAL_ERROR rather than a view with the handle silently missing — the submitter was promised one, and status gives it another chance.

8.5.3.1 The definition #

FieldDefaultValidation
image_pathrequiredAbsolute, non-empty, no NUL. Not checked for existence: execve decides that, as the job's identity.
arguments[]Strings without NUL.
environment{}Keys non-empty, no =, no NUL; values no NUL.
working_directory/Absolute.
description""
timeout0, no limitNon-negative integer, seconds.
stop_timeout10Positive integer, seconds.
readinessnonenone or notify.
readiness_timeout30Non-negative integer, seconds.
success_exit_codes[]Integers 0–255.
descriptors[]One name per injected descriptor; non-empty, no :.
outputfalseRequires at least one attached descriptor.
security_descriptorthe defaultSDDL with an owner and a DACL.

descriptors has to match the attachments exactly: its length plus one if output is set equals the number of descriptors on the message. The combined size of arguments and environment is bounded at 2 MiB, below what execve accepts. Nothing here restarts, depends, probes, or schedules; a program that needs any of that is a service.

8.5.3.2 The descriptor #

Unless the submission supplied one, the descriptor is built by PeiosSystemAccessChecker from the submitter SID: owner and group the submitter; a DACL granting JOB_ALL_ACCESS to the submitter, to SYSTEM and to Administrators; nothing else; and a SACL auditing every refusal, for everyone, so a denied command on the job is recorded (§8.4).

The job identity is granted nothing. A process cannot, by virtue of running as U, see or stop a job that runs as U — a submitter that wants the principal to see its own session says so in the descriptor it supplies.

A supplied descriptor is used as given, with no default entries added — its SACL included, so one with none has its denials recorded by no one. A submitter that omits itself has locked itself out of its own job, and peinit does not prevent that. The descriptor is fixed at submission.

RightBit
JOB_QUERY0x0001
JOB_STOP0x0002
JOB_SIGNAL0x0004
JOB_ALL_ACCESS0x0007

The generic mapping is read → JOB_QUERY, write and execute → JOB_STOP | JOB_SIGNAL, all → JOB_ALL_ACCESS. Every command on either door checks against this descriptor, the submitter included, naming the job to KACS in the check's audit context; a denial is answered ACCESS_DENIED, and the descriptor's SACL decides whether KACS records it (§8.4).

8.5.4 Launch #

Queued submissions launch from the work pump, one per pump step, through the ordinary child path (§5.3, §5.4) with three differences. The token source is LaunchTokenSource::Prepared: the launch takes its own duplicate of the prepared token through materialize_prepared_token, and the entry's copy is closed once the launch has it, whatever the outcome. The attached descriptors ride as inherited descriptors, placed from 3 upward with close-on-exec cleared and LISTEN_FDS, LISTEN_FDNAMES and LISTEN_PID set, exactly as the fd store hands descriptors back to a service (§10.6).

And the environment is built as a service's is — the compiled-in base, the global layer, then the submission's environment in the place a definition's own variables occupy, then the protocol variables last, so a submitter cannot override NOTIFY_SOCKET or the LISTEN_* set (§5.5).

The cgroup is /sys/fs/cgroup/peinit/jobs/<guid>, a tree of its own rather than a service's.

Exec confirmation and failure arrive through the setup pipe as for any job. A parent-side failure — no token, no cgroup, no fork — takes the record from Created straight to Failed with cause parent_setup_failure; a child-side failure between fork and exec, or a failed exec, is pre_exec_failure. Both close everything the entry still held and try to remove the cgroup. On success the record is Running, the runtime registers the job's pipes with origin jobs/<guid>, and adopts the output sink if there is one (§11.1).

A stop on a job still queued cancels it: the launch entry is removed, the record fails before start with the stop's cause, and the answer is the terminal view. A stop that lands while setup is pending kills the cgroup and lets setup completion find the stop already recorded.

8.5.5 While it runs #

A submitted job speaks the notification socket like a service, with one difference in how it is believed: peinit routes a datagram to a service or to a submitted job by a pure PID lookup first — does any service's current main job carry this PID — and only then verifies the sender against that job's pidfd. A submitted job has no activation generation and no replacement, so the generation step does not apply. The sender is verified exactly once whichever way it was routed (§10.5).

What the fields do to a submitted job:

FieldEffect
READY=1For a notify job not yet ready: ready becomes true and the readiness timeout is disarmed. Otherwise ignored.
STATUS=Retained as status_text.
PROGRESS=Parsed as §4.19's three forms; retained as progress. A value outside the forms, T of zero or N above T is dropped, never repaired; the rest of the datagram is applied.
PROGRESS_UNIT=bytes, items or percent, retained; anything else dropped.
STOPPING=1Recorded, so a later stop sends no termination signal.
Everything elseIgnored: a job has no reload, no watchdog, no fd store.

A datagram that changed status_text, progress, or the unit is due a peinit.job.status.reported event carrying the retained values (a verbose type, written only when the emission policy turns it on) — but at most one per job per second, measured from the last event emitted for that job, so a sender updating a thousand times a second produces one event a second while the view is current on every query.

Deadlines are held on the entry and folded into the one lifecycle deadline timer the event loop arms, as SubmittedJob kinds:

DeadlineDueAction
Timeoutstarted_at + timeoutBegin a stop with cause timeout.
ReadinessTimeoutstarted_at + readiness_timeout, for a notify job not yet readyBegin a stop with cause readiness_timeout.
StopKillstop requested + stop_timeoutSIGKILL the job's cgroup.
PostKillkill + PostKillTimeoutAbandon (below), or re-arm if the cgroup is empty but the exit not yet reaped.
CgroupCleanupterminal + PostKillTimeoutRetry removing a cgroup that was busy when the job ended.

A job being stopped has only its stop deadline; a deadline that fires for a job that has already ended does nothing.

8.5.6 Stopping #

Every stop — a submitter's stop, an administrator's job-stop, a timeout, shutdown — goes through begin_submitted_stop: record the cause and the kill deadline, then SIGTERM the main process through its pidfd unless the job has already sent STOPPING=1. A second stop on a job already stopping changes nothing and does not restart the deadline; a stop on a terminal job is a no-op answered with the unchanged view.

At the kill deadline the cgroup is killed. At the post-kill deadline, a cgroup still populated means the process survived SIGKILL: the record is abandoned, the cause becomes process_unkillable, the cgroup is leaked and reported as peinit.cgroup.leaked, naming the job rather than a service, and supervision stops.

signal is the raw mechanism, deliberately: one signal, by number, to the main process through its pidfd, on a running job only. SIGKILL this way leaves whatever the job spawned and produces a failed job with exit_signal set and a null cause.

A submitter that wants the job ended uses stop.

8.5.7 Ending #

On reap, exit code 0 or one in success_exit_codes completes the job; any other code, or a signal, fails it. Then whatever the job left in its cgroup is killed and the cgroup removed; a busy cgroup schedules one CgroupCleanup retry, and a cgroup still busy after that is reported leaked. The prepared token, any attached descriptor the launch never took, and any sink the runtime never adopted are closed. The sink the runtime did adopt closes when the job's last pipe closes.

cause records what peinit decided, and stays null when the process ended of its own accord. A stop whose process handled SIGTERM and exited 0 is completed with cause explicit_stop: peinit asked, the process agreed, and both facts are recorded. A stopped job that died to the signal is failed with exit_signal set and the same cause.

The record is dropped at once, as every terminal job's is (§8.1), and peinit.job.ended carries it. The entry is retained for 60 seconds so a submitter polling for the outcome finds it, and then purged by operation maintenance; status on a purged or never-existent identifier is UNKNOWN_JOB either way. A terminal job whose cgroup cleanup is still pending is not purged until the retry has run.

8.5.8 Shutdown #

When a shutdown begins, every live submitted job is stopped at once, with cause shutdown and no ordering between them or against the service waves — a job has no dependencies to order by. A job still queued for launch is canceled with the same cause. The shutdown is not finished while a live job remains: a job's reap advances shutdown progress exactly as a service's does, and the global timeout kills every live job's cgroup along with the remaining services (§12.2). submit is refused throughout; the other four commands keep answering, because a submitter watching its jobs go down has a reason to keep looking.

8.5.9 Clients #

svctl job list|status|stop are the control socket's job commands, and svctl job submit|wait|signal speak the jobs socket, submitting as the caller's own primary token with --fd NAME=FD for descriptors and --output for a sink. libpeinit exposes the same two halves: peinit_job_status, peinit_job_list and peinit_job_stop on the control client, and <peinit/jobs.h> — a peinit_jobs_t with peinit_job_submit, peinit_jobs_status, peinit_jobs_wait, peinit_jobs_stop, and peinit_jobs_signal — with peinit_response_take_pidfd to claim the handle a submit returned.

8.6 What a Caller Sees

Peios / Reference / peinit / Jobs and Operations

Operations are how a caller observes something taking effect. This article covers what the model looks like from the outside; the wire contract itself is PSPU §4.

8.6.1 Every lifecycle command returns an identifier #

A command that creates, merges into, queues, cancels, clears, or executes an operation returns that operation's identifier. A caller can then poll it, or block on it.

Two cases return no identifier, because no operation exists: a command whose target is already in the state it asks for, and one that has no effect at all — a stop on an Inactive service. Both return the service's status instead of an acknowledgment, which is the honest answer, and which also says what else the caller can do to the service (§10.2).

Commands that never create an operation — status, list, operation-status — have their own shapes. So do the three job commands, which never create an operation either: a submitted job has no state machine to contend for, so job-stop acts on it directly and answers with the job view.

8.6.2 Waiting #

Lifecycle commands block by default until the operation is terminal. The exception is reload, which returns immediately unless asked otherwise, because a reload's outcome is often advisory and a caller usually wants the identifier rather than the wait.

A waiting connection is not idle and is never closed by the idle timeout, however long the operation runs. It is bounded by the operation's own lifetime instead.

8.6.3 Merging is invisible #

A caller whose command merged receives the surviving operation's identifier and blocks on that operation's outcome. Nothing tells them they merged, because there is nothing they could usefully do about it. The consequence worth knowing is that the identifier a caller gets back can be older than their request, and its created_at will be earlier than when they sent it — which is exactly right, because that is when the work they are waiting on actually began.

8.6.4 What an operation's result carries #

A completed stop or reset carries the resulting service state; a completed start carries the readiness that satisfied it — alive readiness: process started, notify readiness: READY=1, or the exit code for a Oneshot — rather than a state name. A failed one carries the failure reason; one that peinit could not execute (§8.2) carries internal_error: <cause>. A merged one carries the survivor's identifier. A canceled or aborted one carries why.

For a reload, the result also determines the reload's mode — whether the service confirmed the reload with a READY=1, whether peinit is merely assuming it happened, or whether it outright failed.

8.6.5 The job view #

A submitted job is reported in one shape on both sockets, the job view of PSPU §7.7: identifier, type of submitted, state, cause, submitter and identity SIDs, logon session, description, image path, pid while there is a process, ready for a notify job, exit code or signal, the retained status_text and progress, and the three timestamps. Every inapplicable field is present and null, and pid is null once the job is terminal — there is no process to name. Abandoned is the exception, and the reason for it: an abandoned job's processes survived SIGKILL and are still running, so its pid is kept.

What a submitter sees of its job on the jobs socket is exactly what an administrator sees of it in job-status, but for one field the control socket adds: granted, the job rights that caller holds on it (§10.2). And job-list is a list of the same views, filtered by JOB_QUERY on each (§10.2). A job-stop with wait registers a wait on the connection like a lifecycle command's, answered with the terminal view — or UNKNOWN_JOB, if the record was purged before the answer could be sent.

8.7 Submission and Progress Examples

Peios / Reference / peinit / Jobs and Operations

This reference expands the submitted-job operator workflow. Job implementation is in §8.5; transport is in §10.7 and the submission protocol is PSPU §7.

8.7.1 What a job runs as #

There is no identity field. A submitter cannot name an identity for its job; it can only run the job as an identity it already holds:

  • Nothing attached — the job runs as the submitting process's own primary token, exactly as a child of the submitter would. This is the common case for a tool or a service running something as itself.
  • A token attached — the submitter attaches a token to the submit message, and the kernel (through KACS) gates the attach: it verifies the submitter could act as that identity, at that impersonation level, at that moment. peinit turns the attached token into the job's primary token. This is how backupd runs a backup as its client, or a logon service starts a session as the user who authenticated — the same impersonation machinery, with the kernel as the only judge. A job whose session must convey Delegation needs the submitter to set its jobs connection to Delegation level first; a job started at Impersonation cannot be raised later.

A token below Impersonation level, or one peinit cannot duplicate, is refused with BAD_TOKEN. peinit never refuses a token because of who it names — that decision was the kernel's.

Two identities are recorded on every job, and the view shows both: the submitter (who asked — the identity the connection was made under) and the identity (who it runs as), plus the identity's logon session.

8.7.2 The definition #

A submission carries the whole job in one message: image_path (absolute; required), arguments, environment, working_directory (default /), description, timeout (seconds; 0, the default, is no limit), stop_timeout (default 10 s), readiness (none or notify, to wait for READY=1), readiness_timeout (default 30 s), success_exit_codes, a list of named descriptors to hand the job, an output flag, and optionally a security_descriptor for the job itself. There are deliberately no policy fields — no restart, dependencies, health check, or trigger. A program that needs those is a service.

peinit does not check that the program exists or is executable when it accepts the submission; that is decided at execve, by the job's own token, and a program that cannot be run becomes a failed job rather than a refused submission. The submit is answered only once the job has **left created ** — the process confirmed its exec, or starting it failed. A readiness: notify job is answered when it is running, not when it is ready; a submitter that wants to block until readiness follows with a wait.

Descriptors a submitter attaches are handed to the job from descriptor 3 with LISTEN_FDS, LISTEN_FDNAMES and LISTEN_PID set — the same convention a service uses to adopt stored descriptors, so a program written for one adopts them from the other unchanged. This is what makes a session job possible: the submitter keeps one end of a socketpair and attaches the other.

8.7.3 The job view #

Whether you ask on the jobs socket or with job status, you get the same view: the job id, type (submitted), state and cause, submitter and identity SIDs, logon_session, description, image_path, pid (while running), ready (null for a readiness: none job, otherwise whether READY=1 has arrived), status_text, progress, the exit code or signal, and the created_at /started_at/ended_at timestamps.

status_text and progress come from the job itself, through the same sd_notify socket a service uses. A job sends STATUS=Backing up /data/media for a human-readable line and PROGRESS= in one of three forms:

FormMeaningShown as
PROGRESS=NCounting, with no end in sight.A rising count.
PROGRESS=N/Counting toward an end that exists but is not yet known.A rising count, awaiting a bound.
PROGRESS=N/TN of T.A bar.

PROGRESS_UNIT=bytes|items|percent says what the numbers are. peinit keeps the latest accepted values and emits a peinit.job.status.reported event when they change, rate-limited to at most one per job per second so a chatty job cannot flood the event stream — the view always has the latest value regardless.

9.1 Calendar Expressions

Peios / Reference / peinit / Timers

A timer schedule is a calendar expression in systemd's OnCalendar format. The grammar below is what peinit parses.

DayOfWeek Year-Month-Day Hour:Minute:Second Timezone

Every field is optional, and which fields are present is worked out positionally from their shape.

FieldFormDefault if omitted
DayOfWeekweekday namesany day
DateYear-Month-Day*-*-*
TimeHour:Minute:Second00:00:00
Secondthe :Second of Time:00
Timezonean IANA namesystem-local

A time-only expression such as 02:00:00 implies the date *-*-*. Hour:Minute alone defaults the seconds to 00.

Years range 0–9999, months 1–12, days 1–31.

9.1.1 Component syntax #

Every numeric component, and the weekday, accepts:

  • Wildcard — * matches anything.
  • List — comma-separated values: 1,15.
  • Range — two values around .., inclusive: Mon..Fri, 8..17. A reversed range is a parse error rather than a wrap-around.
  • Repetition — a value or range suffixed with / and a step. value/step matches the value and every multiple of the step above it, so 0/15 in the minute field is 0, 15, 30 and 45. start..end/step walks from start to end inclusive.

Weekdays are English names, case-insensitive, abbreviated or full, and accept lists and ranges. Mon and Monday are the same day, as are Tue, Tues and Tuesday.

9.1.2 Last day of the month #

A ~ in place of the - between Month and Day counts the day from the end of the month: ~01 is the last day, ~02 the second-to-last, and so on. *-*~01 is the last day of every month; *-02~03 is the third-to-last day of February.

Repetition combines with it, and steps in the day-of-month direction — which means it walks the offset downwards, toward the end of the month. Mon *-05~07/1 covers the last seven days of May, and combined with Mon resolves to exactly one day: the last Monday in May.

Wildcards, ranges and lists are also accepted after ~, so ~* matches every day and ~03..07 the third- to seventh-to-last.

9.1.3 Named shortcuts #

ShortcutEquivalent
minutely*-*-* *:*:00
hourly*-*-* *:00:00
daily*-*-* 00:00:00
weeklyMon *-*-* 00:00:00
monthly*-*-01 00:00:00
quarterly*-01,04,07,10-01 00:00:00
semiannually*-01,07-01 00:00:00
yearly, annually*-01-01 00:00:00

Shortcut names are case-insensitive and accept a trailing timezone, so daily UTC is valid.

9.1.4 Timezones #

Timezone specifiers are IANA database names — Europe/London, US/Eastern, UTC. An expression with no timezone is interpreted in system-local time.

A name is validated when the expression is parsed and resolved again at evaluation. An unrecognized zone is a hard parse error, not a silent fallback to UTC.

9.1.5 Daylight saving #

  • Spring forward, where the clock skips an hour: a scheduled time falling inside the skipped interval does not fire. peinit moves on to the next scheduled second, then the next date. A schedule of *-03-31 01:30 Europe/London skips 2024 entirely.
  • Fall back, where an hour repeats: a scheduled time inside the repeated interval fires exactly once, on the first occurrence. On re-arming, the same civil time resolves to the same instant, which is not later than the firing that occurred, so the timer advances to the next day rather than firing again.

9.1.6 Precision #

Second-level. Unlike systemd, peinit does not accept fractional seconds — service scheduling has no use for finer granularity, and dropping it keeps the parser simpler. A fraction anywhere in the time component is a parse error.

9.1.7 Examples #

ExpressionMeaning
*-*-* 02:00:00Every day at 2am, system-local.
Mon *-*-* 00:00:00Every Monday at midnight.
*-*-1,15 12:00:00The 1st and 15th, at noon.
*-*~01 00:00:00The last day of each month, at midnight.
Mon..Fri *-*-* 09:00:00Weekdays at 9am.
*-*-* *:00/15:00Every fifteen minutes.
*-*-* 02:00:00 Europe/LondonEvery day at 2am London time.

Note

An expression that parses but can never match — *-02-30, or a fixed year already past — is not rejected at parse time. Computing its next occurrence walks forward a day at a time for ten years and then gives up, reporting no future occurrence. The horizon is there because walking the full year range would turn an unsatisfiable schedule into a boot that hangs.

9.2 Evaluation and Arming

Peios / Reference / peinit / Timers

A timer is a trigger, not a service type. A service with a timer:<schedule> trigger is an ordinary Simple or Oneshot service that peinit starts on a schedule.

9.2.1 Arming #

At boot, once the service graph is loaded, and whenever timer configuration changes, peinit computes the next firing time for every active trigger and arms a timerfd for it. Each trigger gets its own descriptor and its own computation.

A disabled service gets neither a registration nor a firing.

A schedule that fails to parse, or whose next occurrence cannot be computed, fails that trigger. Every other timer arms normally, and what did not arm is reported to the console and in the service's status. This matches how graph validation already treats an invalid schedule (§7.4), so the outcome does not depend on which of the two caught it.

The next-occurrence search looks ten years ahead and then gives up. A schedule can parse and still match nothing — *-02-30, or a fixed year already past — and the horizon turns that into a prompt error against the one service rather than a very long walk. Ten years clears the sparsest schedule that is genuinely meaningful: *-02-29 skips a century year not divisible by 400, so it can run eight years dry.

9.2.2 Firing #

handle_timer(service, trigger):
    // 1. Decide what the firing means, from the service's state.
    match (service.type, service.state):
        (Oneshot, Active | Starting):
            service.pending_timer = true      // at most one
        (Simple,  Active | Starting):
            record the firing; no action
        (Oneshot, Inactive | Completed | Failed):
            create_operation(Start, service, source = Timer)
        (Simple,  Inactive | Failed):
            create_operation(Start, service, source = Timer)

    // 2. Record when it fired.
    write the last-run timestamp to the registry   // asynchronously

    // 3. Re-arm.
    next = next_occurrence(trigger.schedule, now) + random(0, TimerJitter)
    arm an absolute CLOCK_REALTIME timerfd for next

Every other state — Backoff, Stopping, Reloading, Abandoned, Skipped — records the firing and does nothing.

A timer can outlive its service until the next reload. A service whose definition is deleted while it runs carries on, and is discarded when it stops, and nothing re-plans the timers then. A firing for a service absent from the table does nothing, records no last run, and is not armed again; the next reload leaves it out. It is never an error: an error out of a firing takes PID 1 into recovery.

No last run is recorded for a service whose definition has been deleted, whether it is still running or already gone: there is no key to record it in, and writing one would make the key again.

The last-run write happens in a forked child so that the event loop never waits on the registry  — which matters because the registry is served by registryd, a service peinit supervises, so a synchronous write would let a wedged registryd stall PID 1.

Before opening its own registry key, the child closes every inherited descriptor numbered 3 or above. It keeps standard input, output, and error; PID 1 retains its own supervision descriptors. Both the single-timer and per-trigger layouts open a fresh key for their timestamp write. A cleanup failure makes the child exit unsuccessfully and follows the same warning path as a failed registry write.

The parent returns immediately with the child's pid, and remembers it. When the child is reaped, peinit matches its exit status back to the write; a failure is reported:

peinit warning: recording the last run of timer <schedule> for service
<service> failed; it will run catch-up again after a reboot

The write stays best-effort — nothing is retried and nothing is failed over it  — but a persistent timer whose timestamp never lands runs its catch-up on every boot, and that is otherwise a symptom with no thread to pull. The outstanding-write table is bounded, so a child that somehow escapes reaping cannot grow it.

9.2.3 Oneshot pending runs #

A Oneshot that fires while it is already running sets a flag rather than queueing an operation. When it next reaches Inactive or Completed, peinit immediately creates a start operation and clears the flag.

Multiple firings during one run collapse into a single pending run. There is no queue, and the flag is per service rather than per trigger — a service with three timers that all fire during one long run still gets exactly one catch-up.

9.2.4 Multiple triggers #

Triggers on one service are independent: each has its own timerfd, its own next-firing computation, and its own last-run history. Only the Oneshot pending flag is shared.

9.2.5 Reporting #

status reports every trigger of a service that is not disabled, as it stands: the occurrence armed, the time it will fire with its jitter, and when it last fired; or, for a trigger that did not arm, why not (PSPU §4.14). list carries the soonest firing of each service.

The figures are the armed ones, given to the supervisor whenever a trigger is armed: at boot, on a reload that adds or changes the timer (an unchanged timer keeps its armed deadline), after each firing and after a clock change. A client cannot compute them itself, because the jitter is drawn at random when the trigger is armed.

When a trigger last fired is held in memory as well as the registry. It is seeded at boot from the recorded timestamp of a persistent trigger, set by each firing, including a boot catch-up, and kept across a reload for the same service and schedule. A definition deleted and made again between two reloads is the same service and schedule, and keeps it too. A non-persistent trigger, which records nothing (§9.3), reports only its firings since peinit started.

9.3 Persistence

Peios / Reference / peinit / Timers

TimerPersistent, on by default, controls whether a run missed across a reboot is caught up.

9.3.1 Where history lives #

Last-run timestamps are REG_QWORD values in the registry, written after a firing.

A service with a single timer trigger stores its timestamp as LastTimerRun on the service's own key:

Machine\System\Services\<name>\LastTimerRun

A service with multiple triggers stores one per trigger under a subkey, named by the schedule string:

Machine\System\Services\<name>\TimerState\<encoded-schedule>

A schedule contains characters — spaces, :, * — that are not valid LCS value names, so the name is the schedule with every character outside [A-Za-z0-9._-] percent-encoded, with uppercase hex digits. This is the same encoding used for cgroup ids (§5.1). The schedule *-*-* 02:00:00 is stored as:

%2A-%2A-%2A%2002%3A00%3A00

Two identical schedule strings on one service encode to the same name and therefore share one timestamp.

Timer firings are infrequent, so the write cost is negligible.

9.3.2 Catching up #

On boot, for each persistent trigger:

  1. Read the last-run timestamp.
  2. Compute the next scheduled firing after it.
  3. If that time has already passed, at least one run was missed: fire once, immediately.
  4. Compute the next future occurrence normally.

Catch-up is always a single run however many were missed. A daily timer that missed five days fires once on the next boot, not five times.

A trigger with no history at all is treated the same way, so its first boot produces one catch-up firing.

TimerPersistent=0 ignores history entirely — peinit does not even read the registry for that trigger, and computes the next occurrence from now.

9.3.3 When the timestamp is written #

The timestamp is written after the timer fires and the start is initiated, not after the service finishes. A service that crashes mid-run is not re-triggered on the next boot: the run was attempted, not missed.

A configuration reload keeps an already-armed timer when its service name, schedule string, TimerPersistent, TimerJitter, and timestamp storage layout are unchanged. Its scheduled occurrence, jittered firing time, and last firing are retained, even if the occurrence has passed while its jitter is still pending. Unrelated configuration edits and a timer's own LastTimerRun writes therefore cannot postpone that firing.

New or changed timers are armed from the current time with no catch-up, whatever TimerPersistent says. Removed or disabled triggers are unregistered. History is consulted at boot only.

Note

Timestamps for a multi-trigger service are keyed by schedule string, so changing a schedule orphans its history and the new schedule produces one spurious catch-up run. A stable trigger identifier would fix it; schedule changes are rare and one extra run is the whole cost. A single-trigger service is unaffected, since its timestamp lives at a fixed name.

9.4 Jitter and Clocks

Peios / Reference / peinit / Timers

9.4.1 Jitter #

TimerJitter, zero by default, adds a random delay to each firing. peinit draws a uniformly random whole number of seconds from zero to TimerJitter inclusive, from the kernel's random source, and adds it to the computed occurrence.

The delay is recomputed on every firing, so a daily timer with TimerJitter=900 fires at a different moment between 00:00 and 00:15 each day. With TimerJitter=0 no randomness is consulted at all.

Jitter is applied after the calendar expression is evaluated and is only ever added, so a timer never fires early — only late.

The boot catch-up firing is not jittered. It fires immediately, and jitter applies from the next armed occurrence onward.

9.4.2 Which clock #

The split is the point of this section, and it is not cosmetic.

Calendar timers are wall-clock schedules, so they are armed as absolute CLOCK_REALTIME timers: timerfd_settime with TFD_TIMER_ABSTIME | TFD_TIMER_CANCEL_ON_SET. CANCEL_ON_SET makes the descriptor's read return ECANCELED whenever the realtime clock is discontinuously changed — an NTP step, a manual set. peinit recomputes the next occurrence against the new wall clock and re-arms, which is what keeps *-*-* 02:00:00 anchored to 02:00 across clock corrections.

Interval timers are genuine relative durations and use CLOCK_MONOTONIC: the watchdog, health check intervals and timeouts, restart backoff, and the Start, Stop and Reload phase timeouts. "Wait thirty seconds" means thirty elapsed seconds regardless of what happens to the wall clock. They are not armed with CANCEL_ON_SET, correctly — a monotonic timer has no reason to be canceled by a realtime set.

These are not separate descriptors. Every interval deadline is aggregated onto one monotonic timerfd armed to the earliest of them.

**Last-run timestamps are recorded on CLOCK_REALTIME **, since they record when a timer actually fired in wall-clock terms. The same firing passes a monotonic timestamp into the operation machinery, because operation timing is elapsed time.

9.4.3 Clock events #

  • A realtime step at runtime. The armed timer is canceled; peinit recomputes against the new wall clock and re-arms. A backward step pushes the next firing later; a forward step that crosses an occurrence fires it once. If the step lands inside a jitter window, the firing happens at the un-jittered scheduled time — later than the schedule, never earlier.
  • Suspend and resume. An absolute deadline that elapsed while suspended fires once on resume. The expiration count is ignored, so a long suspend produces one firing, not one per occurrence.
  • A missed occurrence within one uptime. Fire once, then compute the next future occurrence. peinit never replays every occurrence that elapsed during a gap — the same rule as the cross-reboot catch-up.
  • A backward jump across a boot. If the last-run timestamp is in the future relative to the current wall clock at boot, peinit treats the history as unknown and fires the catch-up immediately. This check is boot-time only; there is no runtime equivalent.
  • A wrong clock at boot. A system that boots with a badly wrong clock and has NTP correct it later can fire a persistent catch-up spuriously or not at all. The runtime half is covered by CANCEL_ON_SET — once NTP corrects the clock, armed calendar timers are canceled and recomputed — but the boot-time catch-up decision has already been made by then. Short of NTP-aware rescheduling, this remains an edge.

Note

The calendar parser deserves heavy testing. Time parsing is a rich source of edge cases: month boundaries, leap years, last-day-of-month arithmetic, DST transitions and timezone database updates are all fertile ground for subtle errors, and every one of them is a bug that only appears on a particular day of a particular year.

10.1 The Control Socket

Peios / Reference / peinit / The Control Interface

peinit serves every runtime command on a Unix stream socket at /run/services/peinit/control.sock, created during Phase 1 infrastructure setup and existing for the lifetime of the system. Its wire protocol is specified in PSPU §4; this chapter is how peinit implements its side. A second socket beside it, the jobs socket, is the door for submitting jobs rather than administering services; it is §10.7.

10.1.1 Creation and protection #

The socket is created with SOCK_CLOEXEC | SOCK_NONBLOCK and a listen backlog of 32, and unlinked when peinit drops it. Accepted connections come from accept4 with both flags, so no connection descriptor is ever inherited by a service.

peinit sets no POSIX mode bits on the socket, on the notification socket, or on anything else it creates. Under KACS, mode bits are not what governs access — a Security Descriptor is — so setting them would be inert.

What governs access is the descriptor on the socket inode, which the kernel checks at connect() before any peer identity is established. peinit creates /run/services/peinit/ and stamps the control socket explicitly, after binding and before anything can connect :

O:SYG:SYD:(A;;GA;;;SY)(A;;GA;;;BA)(A;;FW;;;AU)

Every authenticated principal can connect. FW is the file-write generic right, which is what connect() on a pathname socket needs. Reaching the socket grants nothing on its own: every command is checked against the control descriptor or the target service's descriptor, with the token captured at accept (§10.2). Admitting only SYSTEM and Administrators would make that check moot for everyone else, since a descriptor that grants a principal something could never be reached by them.

The notification socket is stamped explicitly too, with a descriptor of its own that grants SYSTEM and the Service group rather than Administrators (§10.5). The jobs socket carries a broader descriptor again, because reaching it is a different permission (§10.7).

10.1.2 Connections #

peinit accepts a connection, obtains the peer's token, and only then admits it against the connection limits:

KeyDefaultMeaning
Machine\System\Init\MaxControlConnectionsPerUser16Concurrent connections one caller can hold, counted by the user SID of its token. SYSTEM is exempt.
Machine\System\Init\MaxControlConnections256Concurrent connections in all: a bound on peinit's descriptors, set well above what callers reach.
Machine\System\Init\MaxRequestSize65536Maximum request size, in bytes.
Machine\System\Init\ConnectionTimeout30Seconds before an idle connection is closed.

The per-user limit is what keeps one caller from taking the connections everyone shares: with every authenticated principal able to connect, a single overall limit would let anyone fill it and lock administrators out. SYSTEM is exempt, as it is from MaxJobsPerSubmitter, because what it does is the machine's.

A connection over either limit is closed at the socket level, before any request is read and without a response — there is no error code for it, because there is no protocol state in which to deliver one. A peer whose token cannot be obtained is closed the same way.

The jobs socket has its own three, under Machine\System\Init\: MaxJobsConnections (64), MaxJobMessageSize (32768) and JobsConnectionTimeout (30), plus a fourth bound that is the submitter's rather than the connection's, MaxJobsPerSubmitter (64). All four are read at boot and on reload-config, and are listed with the other operational keys in the registry key reference.

10.1.3 The peer token #

The token is read once, when the connection is accepted, through the kernel's peer-token socket option (getsockopt(SOL_KACS, KACS_SO_PEER_TOKEN); the Peios Kernel TRM §3.5). It is the identity the peer thread was acting under when it connected, so a peer that was impersonating is captured as the impersonated identity  — which is what makes access decisions reflect the identity a client is actually operating under rather than its underlying service identity.

Because it is captured once, a peer that changes identity mid-connection is still evaluated against the identity it connected with.

10.1.4 Idle and waiting #

A connection is idle only when it has nothing in flight. One blocked on a wait=true operation, on a job-stop with wait, or with output still buffered, is never idle and is never closed by ConnectionTimeout  — it stays open until the operation or job resolves, bounded by the operation's own timeout rather than the connection's. A job wait has no timeout of its own; it is bounded by the job.

A wait is answered when its operation reaches a terminal state, with the lifecycle acknowledgment carrying the service's state at that moment. Two cases are answered differently. An operation that failed because peinit could not execute it (§8.2) is answered with an INTERNAL_ERROR whose message carries the operation's result, not with an ok carrying an unchanged state. And an operation whose service has been discarded by the time it resolves — a stop that drained a definition-removed entry (§10.3) — is answered with the state the service last had, since there is no entry left to ask. Neither answer costs the connection or the listener.

peinit handles one frame per readiness turn, and processes no further frames from a connection while a wait is pending on it. Pipelined requests are therefore serialized behind a wait.

10.1.5 Timestamps #

Every timestamp peinit puts on the wire is derived by projecting a monotonic event stamp through the current offset between the realtime and monotonic clocks. Elapsed-time decisions stay monotonic; only the presentation is wall-clock.

10.2 Dispatch and Authorization

Peios / Reference / peinit / The Control Interface

A parsed command runs a fixed sequence before it does anything.

  1. The shutdown gate. If peinit is shutting down, everything except status, list, operation-status, boot, job-status, job-list and job-stop is rejected. boot stays open because, like the service queries, it changes nothing. The three job commands stay open because a shutdown stops every submitted job anyway (§12.2), and an administrator watching that happen, or wanting a job gone sooner than the shutdown will manage, has a reason to ask. The gate runs before the access check, so during shutdown a caller who would have been denied is told the command is invalid for the current state rather than that they lack the right.
  2. Resolve the target. A command naming no definition, and no addressable definition-removed entry, returns UNKNOWN_SERVICE; one naming no submitted job peinit holds returns UNKNOWN_JOB. peinit does not synthesise a descriptor for something that does not exist.
  3. AccessCheck. The caller's token, the target's descriptor, the generic mapping, the right the command requires (§4.6, §4.7), and an audit context naming the target: the service, the job, or the control door itself (§8.4). For a job the descriptor is the job's own and the mapping is the job mapping (§8.5).
  4. On denial, return ACCESS_DENIED. The decision is recorded by KACS, as kacs.audit.access.checked naming the caller, the target and the access requested and granted, whenever the target's descriptor has a SACL that asks for it; every descriptor peinit builds itself audits every refusal. peinit writes no event of its own. Silent denial is not acceptable; a denial an administrator cannot see is indistinguishable from a bug, which is why the defaults audit, and why a descriptor written to the registry should keep a SACL that does (§4.6).
  5. On grant, classify the command against the service's state (§10.3) and act.

10.2.1 Rights #

CommandRight
startSERVICE_START
stopSERVICE_STOP
restartSERVICE_START and SERVICE_STOP, requested as one mask
reloadSERVICE_INTERROGATE
resetSERVICE_STOP
statusSERVICE_QUERY_STATUS
listFiltered per service by SERVICE_QUERY_STATUS
operation-statusSERVICE_QUERY_STATUS on the target service
job-statusJOB_QUERY on the job
job-listFiltered per job by JOB_QUERY
job-stopJOB_STOP on the job
shutdownSYSTEM_SHUTDOWN
reload-configSYSTEM_RELOAD_CONFIG
bootSYSTEM_QUERY_STATUS on the control descriptor, which by default every authenticated principal holds (§4.7)

operation-status resolves the operation before it checks the right, so an unknown identifier is reported as unknown regardless of who asked. If the operation's service has since been discarded (§3.8), the right is checked against the ServiceSecurity the service had when the operation was created, which peinit records on the operation; a retained operation therefore stays queryable for its retention window (a2) by exactly the callers who could have queried the service.

job-status and job-stop resolve the job first too, and for them that is the whole story: UNKNOWN_JOB for an identifier that names nothing, ACCESS_DENIED for one that names a job the caller can not touch. A job identifier is unguessable, so a caller that names one was told it by something that had it, and there is no existence to hide. job-stop creates no operation; it stops the job directly (§8.5) and, with wait, registers a job wait on the connection answered by the terminal view.

10.2.2 What the caller can do #

A status response carries granted, the service rights the caller holds on the service, so that a client can offer only the commands that will be allowed rather than learn the rest from ACCESS_DENIED (PSPU §4.14). peinit finds them with step 3's AccessCheck — the caller's token, the service's ServiceSecurity, the service mapping — asking for MAXIMUM_ALLOWED instead of one right, once the query itself has been allowed, and reports the service rights among what it grants. A lifecycle command that has nothing to do answers with the status (§10.3), and that carries granted for its caller too.

Each job view on the control socket carries granted the same way: the job rights the caller holds, from the AccessCheck against the job's own descriptor with the job mapping (§8.5). job-stop with wait finds them when it is taken and keeps them on the connection's wait, because the terminal view is written by the run loop with no caller's token to hand; the descriptor is fixed at submission, so they are the same as at the answer. The jobs socket's view has no granted.

The MAXIMUM_ALLOWED check is a question, not a command. A right it does not grant is left out of granted; nothing is refused, and peinit answers the command as it would have without it.

10.2.3 Filtering #

list checks every service and partitions the result. Services the caller can query are returned; services it cannot are omitted, and the denials are left to each service's SACL rather than shown to the caller. A caller with no query rights anywhere gets an empty list and a successful response, not a denial . The filtering keeps a service's state from whoever can not query it; it does not hide that the service exists, which step 2 above already answers for any command that names one (§4.6).

Definition-removed services are listed, and the list entry does not say so. A status query on one does.

job-list is filtered the same way. The four request filters — submitter, identity, logon_session, state — narrow the candidates first; each survivor is then checked for JOB_QUERY against its own descriptor, each denial is the job's SACL's to record, and the response does not say whether a filter or a right removed an entry. Terminal jobs still within their retention are listed; a caller that wants only live ones filters by state.

10.3 The Command × State Matrix

Peios / Reference / peinit / The Control Interface

A command sent to a service in an unexpected state gets an answer, not a silent no-op. What the answer is depends on the pair.

InactiveStartingActiveReloadingStoppingCompletedBackoffFailedAbandonedSkipped
start StartMERGEALREADYALREADYQUEUEStartDEFERStartERRORStart
stop NOOPCancel+StopStopStopMERGEClearClearNOOPERRORNOOP
restart StartQUEUERestartRestartQUEUEStartRestartStartERRORStart
reload ERRORERRORReloadMERGEERRORERRORERRORERRORERRORERROR
reset NOOPERRORERRORERRORERRORERRORERRORClearClearClear
status OKOKOKOKOKOKOKOKOKOK

ALREADY — the service is already where the command would take it and no operation of that type is in flight. peinit returns the current status rather than an error.

MERGE — an operation of that type is already running. The command merges into it; the caller receives that operation's identifier and, if waiting, blocks on its outcome.

DEFER — create a Pending start operation but do not execute it until the existing backoff deadline expires. A deferred start already present is merged into.

QUEUE — the operation is queued Pending and executes after the current one completes.

NOOP — the command has no effect. peinit returns the status.

ERROR — the command is invalid for the state.

Clear — reset to Inactive.

Cancel — abort the current operation, then proceed.

10.3.1 Backoff #

Backoff is the interesting one, because the service is down with an automatic restart already pending.

  • start creates or merges into a deferred start operation and honors the remaining delay. It does not short-circuit the backoff. If the automatic restart later becomes due, it merges into the administrator's operation, so the identifier the caller holds is the

one that executes.

  • stop cancels both the pending restart and any deferred start, and the service goes Inactive. A subsequent automatic restart is refused, because the service is not in Backoff.
  • restart replaces the automatic restart with the administrator's. A Restart operation with source admin is queued Pending and honors the remaining delay exactly as a deferred start does; when the delay expires it is that operation — keeping its type, for observability — that executes, so the identifier the caller holds is the one that runs. A deferred start already pending is canceled with reason superseded_by_restart, and a second restart merges into the pending one rather than queueing behind it. Nothing is sent to the control boundary, because there is no process for it to act on.
  • reload and reset are invalid: there is no process to reload, and no terminal state to clear.

10.3.2 Skipped #

start and restart clear Skipped before they run. A Skipped service is not in a state a start can proceed from — the state machine permits Skipped -> Inactive and nothing else — so the activation performs that transition first, then re-evaluates the conditions from scratch. Both outcomes are possible: the precondition that was missing at boot can now hold, in which case the service starts; or it can still not, in which case the service is skipped again, for whatever reason applies now.

The clear is reported like any other transition, so a console watching the service sees it leave Skipped rather than appearing to jump: peinit: service X left skipped: ExplicitStart, before the start's own lines.

reset also clears Skipped, and differs only in stopping there.

10.3.3 Abandoned #

Every lifecycle command is invalid on an Abandoned service except reset, which clears it (§6.2). Nothing else is meaningful while processes that ignored SIGKILL are still in the cgroup.

10.3.4 Definition-removed services #

Independently of state, a service whose definition has been removed (§3.8) rejects start, restart and reload with UNKNOWN_SERVICE, accepts stop, and reports its state on status.

The accepted stop drains the instance with the cached StopTimeout, and the exit that ends it also discards the entry. A caller waiting on that stop is answered after the discard, with the state the service last had — Inactive, cause ExplicitStop — rather than with a lookup of an entry that has been removed. A status sent after that is UNKNOWN_SERVICE, as for any service peinit does not know.

10.4 Reload-config

Peios / Reference / peinit / The Control Interface

reload-config takes a fresh snapshot of the configuration from the registry. It does not live-update anything.

It is also the path a registry change notification takes: any drained watch event triggers the same full reload, rather than a targeted re-read of whatever changed.

10.4.1 Atomicity #

peinit reads everything first. Every registry read happens before any mutation, so a read failure returns an error with nothing touched. It then builds and validates a complete new graph in memory, and only swaps it in if validation succeeds.

If validation fails, the previous generation stays live and the findings are returned to the caller. This is where the reload path differs sharply from boot: boot marks individual services Failed and carries on, because it has to produce a running system; reload rejects the whole thing, because it has a running system already and a half-applied configuration would be worse than the one in place.

An explicit reload-config writes one peinit.config.reload.applied event either way: outcome.success, and on success the counts of what it added, updated, restored, marked removed, discarded and found undecodable; on failure why, in words, and one peinit.graph.validation.failed per finding under phase reload-config (§8.4). A reload a registry watch starts writes its findings and warnings but no peinit.config.reload.applied.

Decoding does not split: reload decodes per key exactly as boot does. A key that will not decode fails that one service with ValidationError — a placeholder entry, marked definition-removed, that status reports and nothing can start — and every other definition in the batch loads; a dependent of the failed key fails through ordinary propagation when it is next started. A service that is running when its key stops decoding keeps running with its definition marked removed, as if the key had been deleted. The reload succeeds, lists the keys in summary.undecodable, and names each key, the offending field and the problem in undecodable; each is also a peinit.graph.validation.failed event with outcome.reason validation-error under phase reload-config. A key whose name is not a service name (§3.1) is undecodable in the same way, reported under its raw name with field: name. Repairing the key restores the service on the next reload.

10.4.2 What changes #

  • Every service definition is re-read.
  • A new dependency graph is built and validated.
  • Running services are unaffected and continue on their activation generation.
  • New definitions take effect at the next start, restart, or trigger.
  • New services become available for start immediately.
  • Timer triggers are re-evaluated. Unchanged calendar timers retain their armed occurrence and jittered deadline (§9.3); new or changed timers are armed from the current time with no catch-up.

A reload also refreshes things that are not service definitions: the control descriptor, the four control socket limits, the log configuration, the shutdown settings, the global environment layer, and the eventd log socket path. It also prunes the fd stores of services that have been removed.

10.4.3 Removals and the compiled-in service #

A definition that has disappeared is handled by §3.8 — discarded if nothing is running, marked definition-removed if something is.

registryd is exempt. Its compiled-in definition survives a reload that does not mention it, and its provenance survives a registry entry that shadows it. peinit started registryd before the registry existed, and a reload finding no definition for it cannot conclude that it should stop being managed.

10.5 The Notification Socket

Peios / Reference / peinit / The Control Interface

peinit binds one Unix datagram socket for service notifications, by default at /run/services/peinit/notify.sock. Its path is an implementation detail: services receive it through NOTIFY_SOCKET and nothing hardcodes it. The kernel command line can override it with peios.notifysocket=. peinit creates the socket's directory only when it lies under /run; an overriding path anywhere else must have a parent that already exists. /run/services/peinit itself is created whichever path is in use.

There is one socket, not one per service, and the bind unlinks any stale path first.

10.5.1 The descriptor #

O:SYG:SYD:(A;;GA;;;SY)(A;;FW;;;S-1-5-6)

S-1-5-6 is the Service group, which every token minted for a service logon carries.

It is written out rather than as its SU alias, and that is deliberate rather than an oversight. The alias table lives in libpeios, which is a separately versioned package that nothing here declares a minimum version of — so an image pairing a peinit that writes SU with a libpeios that predates the alias parses this descriptor, fails, and takes PID 1 into recovery before a console exists to say why. That is not hypothetical: it is what happened the first time this descriptor was written. A literal SID has been understood by every version there has ever been. That is the right grantee because it is the population with something to say here: membership follows from having been started as a service rather than from which account a process runs under, so an ordinary user process cannot acquire it however it was launched.

FW is the file-write generic right, which is what a write to a pathname socket needs — the same reasoning as the jobs socket (§10.7). Administrators are absent, unlike the control socket: an administrator has no business asserting that a service is ready.

The descriptor is installed **by path, immediately after bind ** — before the socket is made non-blocking, given SO_PASSCRED, or polled.

It is by path because the fd form does not work on a socket. KACS exposes no fd-targeted descriptor call of its own: fd_set_sd is the path call with the target as dirfd, an empty path and AT_EMPTY_PATH, and the kernel answers EOPNOTSUPP for a socket. Stamping by fd was tried here and took PID 1 into recovery.

That leaves a window between bind and the stamp in which the socket carries what it inherited. It is safe for the same reason it is on the control socket: the parent grants services traverse and nothing else and carries no inheritable ACE, so the inherited descriptor is narrower than the one being installed. The failure direction is refusal, not exposure.

The parent directory /run/services/peinit carries a descriptor of its own, shared with the control socket that lands in it later in boot: SYSTEM and Administrators in full, and S-1-5-6 traverse only. One constant serves both because ensure_directory re-stamps a directory that already exists — two call sites installing different descriptors on one path would silently leave whichever ran last, and since the notify socket is bound first, that would be the control socket's, quietly removing the traverse services need to reach notify.sock at all.

The protocol itself is PSPU §4. What follows is how peinit decides whether to believe a datagram.

10.5.2 Authenticating a sender #

SO_PASSCRED is enabled on the socket, so every datagram arrives with a kernel-attested SCM_CREDENTIALS control message. A datagram without one is rejected outright. Descriptors for the fd store arrive alongside, as SCM_RIGHTS.

Authentication then runs five steps, and each closes a hole the previous one leaves:

  1. Find the sender. Scan for the current service-main job whose PID equals the sender's. Only a main job is ever a candidate, which is what makes NotifyAccess=Main the only mode there is — a hook or a health check cannot notify on a service's behalf.

If no service's main job carries the PID, the live submitted jobs (§8.5) are scanned instead. The routing question is asked purely by PID, before either door verifies anything, so that a sender is verified against its pidfd exactly once whichever way it is routed. 2. The job is Running. A job still in pending setup has not exec'd. 3. The job has a pidfd. 4. The pidfd still refers to that PID. This is the step that matters: PID matching alone is racy, because a PID can be recycled between the sender writing and peinit reading. The pidfd was obtained atomically at fork, so verifying the PID against it is what makes the match sound rather than probable. 5. The generation matches. A job whose activation generation is not the service's current one is a previous incarnation, and its notifications are rejected. This is invariant 5 of §6.1 in force: a READY=1 from the process that crashed cannot mark its replacement ready. A submitted job has no generation and no replacement, so for it the check stops at step 4.

Anything that fails is dropped and recorded as a peinit.notify.rejected event carrying the sender's PID (subject.process.pid), the sender's service, job and activation when peinit could attribute it, and the reason as one of a closed set of words in outcome.reason — unauthenticated-sender, generation-mismatch, malformed-line, and so on (§8.4).

The UID and GID in the credentials are parsed and never used. They are not policy inputs, and peinit does not consult them for anything — identity on Peios is a token, and the token here is established by which job the sender is, not by what UID it claims.

10.5.2.1 A sender whose job has no PID yet #

A job records its PID only when its setup status is read and shows that exec succeeded (§5.3). Until then no job carries the PID, and step 1 cannot find the sender. The setup status and the datagram reach peinit through different sources, and an event-loop turn handles them in whatever order the kernel reports them. A service that sends READY=1 immediately after exec can have its datagram handled before its own setup status.

So when a datagram's sender is a launched process whose setup status has not been processed, peinit reads that setup status before it authenticates the datagram. The status is always readable by then. The setup pipe closes at exec, before the program that sends the datagram starts running. Reading it first records the PID and pidfd on the job, or fails the launch. Authentication then runs as described above. A failed launch's sender is refused as unauthenticated-sender. Reading the setup status first changes the order, not the trust: a datagram is applied only if the job now carries the sender's PID and the job's pidfd confirms it.

Without this step, the datagram would be refused as unauthenticated-sender, and that refusal would be final. A service sends READY=1 once, so the service would wait for a readiness that had already been sent, and peinit would kill it at its start timeout.

If the setup status still cannot be read, peinit holds the datagram rather than dropping it. It applies held datagrams in arrival order, and authenticates each in full when the setup is processed. It applies them before any later datagram from the same sender. peinit holds at most sixteen datagrams for one sender. It refuses any more as setup-pending. Holding is a fallback: in normal operation, the read described above has already found the status.

10.5.3 Applying a datagram #

A datagram can carry several newline-separated lines, and peinit applies every one. Parsing happens before application and is all-or-nothing: if any line is malformed, nothing from that datagram is applied, and any descriptors it carried are dropped and closed. Partial application of an ambiguous service-control message is structurally impossible rather than merely avoided.

A rejection is recorded after authentication, so the event can name the service where one could be established.

10.5.4 What the fields do #

Most are handled elsewhere: READY=1 and RELOADING=1 in §6.5, WATCHDOG=1 and WATCHDOG_USEC and EXTEND_TIMEOUT_USEC in §6.6, STOPPING=1 in §12.2, and the fd store fields in §10.6. What each does to a submitted job — and which are ignored for one, since a job has no reload, watchdog or store — is in §8.5.

Six are event-emitting. STATUS=, ERRNO=, and EXIT_STATUS= are authenticated and then emitted as KMES events — peinit.notify.status.reported, peinit.notify.errno.reported, peinit.notify.exit-status.reported — whose payloads carry the sender as subject.service.name, subject.job.guid, subject.job.activation-generation and subject.operation.guid, alongside the value: notify.status; notify.errno, the number the service sent, negated as every errno field is; notify.exit-status. A value that is not a number is left out and the event still written. They take the same path as job and operation events, not a forward to eventd. peinit.notify.status.reported is a verbose type, written only when the emission policy turns it on (§8.4).

STOPPING=1 emits peinit.notify.stopping.reported, carrying the same attribution and no value. It is there because the field's only effect is the absence of an action — peinit suppresses the SIGTERM (§12.2) — and an absence cannot be inferred from what happened afterward. Without the event, a service that was stopping and correctly received no SIGTERM looks identical to one that should have received it and did not.

PROGRESS= and PROGRESS_UNIT= emit peinit.notify.progress.reported (a verbose type), carrying the same attribution and the progress as retained after the datagram — notify.progress.current, .total, .bounded and .unit, the fields of a submitted job's peinit.job.status.reported. A datagram carrying either yields one event, not one per line, and at most one a second for each activation: a datagram inside the second updates what a status query reports and emits nothing, so a service updating a thousand times a second produces one event a second.

READY=1 and RELOADING=1 emit nothing, deliberately: both are observable through the state transitions they cause.

STATUS= is additionally stored on the service's runtime state and exposed as status_text in a status query. It is cleared to null at the start of every activation generation, in the same step that increments the generation, so a status string cannot survive a restart and describe a process that has been removed.

PROGRESS= and PROGRESS_UNIT= are stored the same way and exposed together as progress in a status query, in the form a submitted job's view gives it: {current, total, bounded, unit}, or null until the service sends a PROGRESS=. Each is parsed as for a submitted job (§8.5): a value outside PROGRESS='s three forms, a T of zero, an N above T, or a unit other than bytes, items or percent is dropped, never repaired, and the rest of the datagram is applied. Each is replaced only by a datagram that carries it. Both are cleared with status_text, in the same step.

ERRNO= and EXIT_STATUS= are not stored. They are emitted and otherwise not retained.

10.5.5 Bounds #

A datagram is read into a fixed 64 KiB buffer, and the control message buffer is sized for 64 descriptors. Both MSG_TRUNC and MSG_CTRUNC are inspected on the way in, and a datagram that overran either buffer is refused as truncated rather than acted on in part: a larger datagram is not applied from its surviving prefix, and a send carrying more than sixty-four descriptors is not applied from the ones that fitted.

10.6 The Fd Store

Peios / Reference / peinit / The Control Interface

The fd store lets a service keep file descriptors across its own restart. It pushes them to peinit, peinit holds them, and the new process gets them back. That is what lets a stateful daemon — a web server holding a listening socket, say — restart without dropping connections it has already accepted.

FdStoreMax in the definition sets the maximum number of descriptors peinit will hold. It defaults to 0, which disables the store : most services do not need it, and holding descriptors on behalf of a service that will never ask for them back is pure cost.

10.6.1 Storing #

When an authenticated datagram carries FDSTORE=1 with descriptors attached:

  1. If FdStoreMax is 0, peinit logs the rejection and closes the descriptor.
  2. If the store already holds FdStoreMax entries, peinit logs the rejection and closes the descriptor. The existing store is not modified — a full store does not evict.
  3. FDNAME=<name> names it; an absent or empty name means stored.
  4. FDPOLL=0 marks the descriptor exempt from poll monitoring.

Either rejection emits a peinit.fd-store.rejected event carrying the service, the descriptor's name and the reason (disabled or full), so a service whose descriptors are being silently dropped can find out why.

Several descriptors can share a name. One FDSTORE=1 carrying N descriptors creates N entries under the one name, each independently subject to the limit — so the first few fit and the overflow is

rejected and closed.

peinit does not monitor stored descriptors. The FDPOLL flag is recorded and nothing reads it, so no stored descriptor is evicted for becoming invalid.

10.6.2 Removing #

FDSTOREREMOVE=1 with FDNAME=<name> removes every descriptor of that name and closes them. A name matching nothing is a no-op rather than an error.

FDSTOREREMOVE=1 without a name aborts the whole fd-store step for that datagram — so a datagram carrying both an unnamed remove and an FDSTORE=1 performs neither, and the attached descriptors are dropped and closed.

10.6.3 Injecting #

When a service restarts, peinit injects the stored descriptors during the child's pre-exec path (§5.4):

  1. They are placed consecutively from SD_LISTEN_FDS_START — descriptor 3 — upward, with close-on-exec cleared: the only sanctioned exception to the close-on-exec discipline.
  2. LISTEN_FDS is set to the count.
  3. LISTEN_FDNAMES is set to a colon-separated list of names in the same order as the descriptor numbers.
  4. The store is cleared. peinit has released them.

All three variables are omitted entirely when the store is empty. LISTEN_PID, which a conforming client checks against its own PID before trusting LISTEN_FDS, is appended by the child itself after the clone, since only then is the PID known ; a value for it from either configurable environment layer is discarded so that it cannot shadow the real one (§5.5).

A submitted job receives its attached descriptors by exactly this path (§8.5).

A listening socket that comes back this way still conveys the identity captured when the previous instance called listen() on it. peinit does not touch that : a service that wants connecting clients to see the instance actually accepting restamps the returned listeners itself (peios_socket_restamp, the Peios Kernel TRM §3.5) before it starts accepting.

Injection happens for the main process only. Hooks and health checks never receive stored descriptors.

The store is cleared on a successful injection, at the top of the started-launch handling. A launch that fails does not clear it, so the descriptors survive a failed attempt and are available to the next one.

10.6.4 Clearing #

The store is cleared, and its descriptors closed, when:

  • The service is stopped explicitly — by an administrator, or by shutdown. The distinction peinit draws is the operation's type and source together: an administrator's stop clears, and a restart-policy-sourced stop does not. The service is not coming back from an explicit stop, so the descriptors are unneeded.
  • The definition is removed and its entry finally discarded (§3.8), immediately if nothing was running and on the instance's exit otherwise.

It survives an automatic restart — crash, restart policy, new start — which is the entire point. The descriptors persist through exactly the restart the service did not choose and cannot prepare for.

Note

The LISTEN_FDS and LISTEN_FDNAMES convention is systemd's, so software already written to receive descriptors that way works unmodified. peinit's own C client library exposes the notification helpers but no descriptor-passing helper, so reaching the store from that library means constructing the control message by hand.

10.7 The Jobs Socket

Peios / Reference / peinit / The Control Interface

peinit serves job submission on a second Unix socket at /run/services/peinit/jobs.sock, created in Phase 1 infrastructure setup beside the control socket (§2.3) and existing for the lifetime of the system. Its wire protocol is PSPU §7; this article is how peinit implements the transport. What a submission is — identities, the definition, the job's life — is §8.5.

10.7.1 Why a second socket, and why sequenced packets #

The control socket's descriptor admits the principals allowed to change the system's services. Submitting a job is a different permission held by a different population, and putting the two on one socket would force one descriptor to serve both. Two sockets let the filesystem say who can submit and who can administer, separately, with no policy inside peinit.

The socket is SOCK_SEQPACKET rather than a stream because a message on it carries more than bytes: the token the job is to run as, and the descriptors it is to be given, as ancillary data. The kernel ties ancillary data to the record it was sent with, and a sequenced-packet socket makes one send one message and one identity, so peinit never has to decide which request an attached token or descriptor belongs to. The cost is that a message has a maximum size and cannot be split; a definition is small.

10.7.2 Creation and protection #

The listener is created with SOCK_CLOEXEC | SOCK_NONBLOCK and a backlog of 32; a stale path is unlinked before the bind, and connections are accepted with accept4 under the same flags. After binding, and before anything can connect, peinit stamps the socket inode :

O:SYG:SYD:(A;;GA;;;SY)(A;;GA;;;BA)(A;;FW;;;AU)

FW is the file-write generic right, which is what a Unix connect() on a pathname socket needs, so every authenticated principal can connect and SYSTEM and Administrators can additionally change the descriptor. Being able to connect is the permission to submit. The kernel checks this descriptor at connect(), and peinit performs no access check of its own before a submit ; an administrator who wants a narrower or wider population changes the descriptor on the socket, not anything in peinit. What a submitter can then do to a job is decided by the job's own descriptor (§8.5), never by this one.

A failure to bind or stamp the socket sends peinit to recovery, as the control socket's does: a system whose jobs door is missing is administrable, but one whose door exists with the wrong descriptor is either unreachable or open to everything, and neither is a state to boot into.

10.7.3 Connections #

The listener is one event source of the runtime loop; each accepted connection is another, keyed by its descriptor. On accept peinit captures the peer's identity once — the peer token, as the control socket does (§10.1), and the peer's process handle through SO_PEERPIDFD — and only then admits the connection against the limit :

KeyDefaultMeaning
Machine\System\Init\MaxJobsConnections64Concurrent connections.
Machine\System\Init\MaxJobMessageSize32768Maximum message content, in bytes. Half of KMES MaxEventSize's default, so a job whose record fills a message still has its peinit.job.ended fit the ring (§8.4).
Machine\System\Init\JobsConnectionTimeout30Seconds before an idle connection is closed.
Machine\System\Init\MaxJobsPerSubmitter64Live jobs one submitter SID can hold; SYSTEM exempt. See §8.5.

A connection over the limit, or one whose peer cannot be identified, is closed at the socket level without a response. The pidfd is held for the life of the connection, because a submit with no token attached opens the job identity through it (§8.5).

A connection carries an identity and nothing else. Closing it does not affect any job submitted on it: a job belongs to its submitter's identity, and a submitter that reconnects finds its jobs where it left them.

10.7.4 Messages #

Every message is received with room for one attached token and for 64 descriptors, the output sink included. One token is all a message can carry: the kernel refuses a second KACS_SCM_TOKEN control message at send time, so the "more than one attached token" refusal in PSPU §7.5 is enforced before peinit ever sees the record. Two truncations are told apart. Content the kernel truncated (MSG_TRUNC) is REQUEST_TOO_LARGE, and that closes the connection, since the transport has lost a record. Ancillary data the kernel could not fit (MSG_CTRUNC) is INVALID_ARGUMENTS, with the connection kept: the content is intact, but a request whose attachments were partly lost does not describe the job the submitter meant, and peinit does not act on it. Every descriptor a message carried that is not handed to a job or adopted as a sink is closed, on every path.

A response is one compact JSON object, no terminator. A submit answered with a running job carries a duplicate of the job's pidfd as SCM_RIGHTS on the response record; nothing else carries ancillary data.

Only REQUEST_TOO_LARGE closes the connection after an error. Every other error is answered and the connection kept.

10.7.5 The turn #

peinit handles one message per readiness turn on a connection, and reads nothing from a connection while a wait is pending on it, so pipelined messages serialize behind a wait.

A turn either answers at once, or records a pending wait on the connection state, or does both in the case of a refusal. Three waits exist:

WaitSet byAnswered when
SubmitsubmitThe job leaves created: exec confirmed, or the launch failed.
WaitwaitThe condition holds — terminal, or ready-or-terminal.
Stopstop with waitThe job is terminal.

Waits are flushed after the supervisor's work has been committed each turn, and again whenever a job's state moves — a launch, a reap, a canceled stop. The flush answers every satisfied wait with the job view at that moment, and for a Submit whose job is running, the pidfd. An answer that cannot be built — a job whose record was purged before the flush, or a pidfd that cannot be duplicated — is that connection's error record, UNKNOWN_JOB, or INTERNAL_ERROR; it never aborts the flush of every other wait.

A connection with a pending wait, or with a response still queued, is not idle and is never closed by JobsConnectionTimeout. A wait has no timeout of its own; it is bounded by the job, and a submitter that needs a bounded wait polls status or waits on the pidfd it was given.

10.7.6 Commands #

submit, status, wait, stop and signal, exactly as PSPU §7.8 defines them and §8.5 implements them. Every one but submit names a job and is checked against that job's descriptor with the connection's token; a denial is answered ACCESS_DENIED, and recorded by KACS as kacs.audit.access.checked naming the job when the job's descriptor audits it, as a default descriptor does (§8.4).

10.7.7 Idle and shutdown #

Idle connections are closed before and after each wait of the event loop, and the next idle deadline is folded into the loop's wait timeout. During shutdown the socket stays open: submit is refused with INVALID_STATE, and the other four commands keep answering (§12.2).

10.7.8 Timestamps #

As on the control socket (§10.1): monotonic stamps projected through the current realtime offset at the moment of answering.

10.8 The Boot Query

Peios / Reference / peinit / The Control Interface

boot tells a client how the machine booted, so that a settings app or an administrator at a shell can see that it is in Safe mode, why, and how many more failed boots stand between it and recovery. The wire shape is PSPU §4.15. This page is where peinit gets each answer.

It takes no arguments and changes nothing. It is checked against the control descriptor for SYSTEM_QUERY_STATUS, which the default grants every authenticated principal (§4.7), and it is answered during shutdown (§10.2).

10.8.1 Mode and reason #

mode is the mode Phase 2 booted in, after any downgrade: full or safe (§2.6). A Recovery boot never reaches the runtime — peinit runs the recovery shell instead (§2.8) — so there is no control socket to ask, and boot never answers recovery.

reason says why.

reasonWhen
normalA Full boot.
requestedA Safe boot asked for with peios.safemode=1.
safe_mode_downgradeA Full boot that Phase 2 downgraded to Safe: a Critical service in a dependency cycle, or in an unresolvable conflict, at boot (§2.6).

For a downgrade, downgrade carries every finding that forced it, in the words the console line and the peinit.boot.downgraded event use — all of them, not the first. peinit keeps them from the boot plan, the one place they survive the Safe-mode rebuild.

10.8.2 Attempts #

attempts is the boot attempt count (§2.7) as Phase 1 checked it against the recovery threshold: the value in /.peinit/boot-attempts before this boot's increment, or 0 if the increment could not be written, which is how Phase 1 treats a counter it cannot advance. It is the count at the start of this boot, so it does not drop to 0 when this boot is confirmed; confirmed says that.

max_attempts is the threshold: peios.bootattempts=N, or 3 when the command line does not set it. 0 means the check is off.

10.8.3 Confirmation #

A boot is confirmed when it has counted as a success: every Critical service has held a dependent-satisfying state for BootSuccessGrace seconds without a break, and peinit has reset the counter to 0 (§2.5). grace_seconds is that grace. The other fields say where the boot stands.

confirmedwaiting_onconfirms_atconfirm_errorMeaning
falsethe Critical services not holdingnullnullThe boot is waiting for them.
falseemptya timenullEvery Critical service holds; if they keep holding, the boot counts then.
trueemptynullnullThe boot has counted, and the counter is 0.
falseemptynullwhyThe grace ended but the counter could not be reset. The next boot will count this one as a failure.

confirmed is true only once the reset has been written. A grace that ends with the write failing — a full disk, say — is not a confirmed boot: the file still holds this boot's increment, and the next boot will count it, whatever its services did. The failed reset is not otherwise reported, so this is where an administrator finds it.

A confirmed boot stays confirmed. A Critical service that fails later is handled by the ordinary Critical failure path — restart budget, then reboot (§2.6) — not by un-counting the boot.

A boot with no Critical services holds from the moment Phase 2 runs, so confirms_at is known at once.

10.9 Control Client Examples

Peios / Reference / peinit / The Control Interface

These examples connect the svctl operator guide to the control interface. PSPU §4 owns the wire contract; the socket and dispatch mechanisms are in §10.1 and §10.2.

10.9.1 How the control interface works #

The socket speaks newline-delimited JSON: one request object per line, one response object per line. A request and its success response look like this:

{"command": "start", "service": "jellyfin", "wait": true}
{"status": "ok", "operation_id": "a1b2c3d4-...", "service": "jellyfin", "state": "active", "cause": "explicit_start", "warnings": []}

Two properties are worth knowing even if you only ever use svctl:

  • Every command is access-controlled. By default, anyone who is signed in can connect. When you connect, peinit captures your token from the kernel and runs AccessCheck against the target service's descriptor for every command. There is no "trust localhost," no override. Who can do what is the subject of Who can manage a service.
  • Lifecycle commands create operations. A start /stop/restart/reload/reset returns an operation_id — a GUID you can poll. Conflict resolution between concurrent commands happens at the operation layer, which is why two simultaneous start s merge instead of colliding.

10.9.2 Reading status #

status returns the full picture for one service:

{
    "status": "ok",
    "service": "jellyfin",
    "display_name": "Jellyfin",
    "description": "Media server for the living room.",
    "state": "active",
    "cause": "explicit_start",
    "status_text": "Listening on port 8096",
    "progress": null,
    "current_job": {"id": "a1b2...", "type": "service_main", "pid": 1234, "started_at": "...", "identity": "jellyfin-svc"},
    "current_operation": {"id": "e5f6...", "type": "start", "source": "admin"},
    "health": "healthy",
    "uptime_seconds": 86400,
    "definition_removed": false,
    "warnings": [],
    "timers": [],
    "granted": ["query_status", "start", "stop", "interrogate"]
}
  • display_name and description are the definition's, or null.
  • state and cause are the lifecycle pair — read them together.
  • status_text is the latest STATUS= string the service sent through sd_notify (null if never sent; cleared on each restart).
  • progress is how far the service last said it had got, from PROGRESS= and PROGRESS_UNIT=: {"current": 3, "total": 10, "bounded": true, "unit": "items"}, with total and unit null when it didn't say them. null if it never sent one; cleared on each restart.
  • current_job and current_operation are the job and operation GUIDs, or null.
  • health is healthy, unhealthy, unknown, or null (no health check).
  • definition_removed is true when the definition was deleted but an instance is still draining.
  • warnings lists leaked sub-cgroups and other operator-relevant notices.
  • timers has one entry for each timer trigger, described below.
  • granted is what you can do to this service, as peinit checks it: the rights the service's permissions give you, out of query_status, start, stop and interrogate (reload). A program shows a control only where its right is listed, rather than offering one that will be refused.

Each entry in timers describes one schedule as peinit has it armed:

{"schedule": "*-*-* 02:00:00",
 "scheduled_at": "2026-06-02T02:00:00.000000000Z",
 "fires_at": "2026-06-02T02:07:12.000000000Z",
 "last_fired_at": "2026-06-01T02:03:40.000000000Z",
 "not_armed": null}
  • scheduled_at is the schedule's next occurrence.
  • fires_at is when the timer will actually fire. It is later than scheduled_at by the random delay TimerJitter drew for this firing.
  • last_fired_at is when it last fired, or null if it has not fired since peinit started and has no recorded run.
  • not_armed is set only for a schedule peinit refused, such as one that never comes round. It gives the reason, and the times are then null.

Times are in UTC. svctl status prints them to the second:

$ svctl status logrotate
logrotate: inactive
cause: clean_exit
timers:
  *-*-* 02:00:00
    next: 2026-06-02T02:00:00Z, firing at 2026-06-02T02:07:12Z after jitter
    last fired: 2026-06-01T02:03:40Z

list returns a compact summary of every service you can query — services you lack SERVICE_QUERY_STATUS on are omitted, not denied:

{"status": "ok", "services": [
    {"service": "jellyfin", "state": "active", "cause": "explicit_start", "health": "healthy", "next_timer_at": null},
    {"service": "logrotate", "state": "inactive", "cause": "clean_exit", "health": null, "next_timer_at": "2026-06-02T02:07:12.000000000Z"}
]}

next_timer_at is the soonest fires_at of the service's timers. svctl list shows it in a NEXT TIMER column.

operation-status returns one operation by GUID; an unknown or expired GUID is the UNKNOWN_OPERATION error. (Operations are dropped after a short retention grace once terminal — long enough for a polling client to read the result, not forever.)

job status returns one submitted job's view under "job", and job list returns the views you can query under "jobs":

{"status": "ok", "job": {
    "id": "5f2a...", "type": "submitted", "state": "running", "cause": null,
    "submitter": "S-1-5-21-...-1001", "identity": "S-1-5-21-...-1001", "logon_session": 999,
    "description": "nightly backup", "image_path": "/usr/bin/backup", "pid": 4521, "ready": null,
    "exit_code": null, "exit_signal": null,
    "status_text": "Backing up /data/media", "progress": {"current": 3, "total": 5, "bounded": true, "unit": "items"},
    "created_at": "...", "started_at": "...", "ended_at": null
}}

The fields are explained in Jobs and operations. A job is retained for 60 seconds after it ends; after that its GUID is the UNKNOWN_JOB error. Like list, job list omits the jobs you lack JOB_QUERY on rather than denying them.

10.11 Client Library

Peios / Reference / peinit / The Control Interface

libpeinit.so.0 provides the C interface for service control, job submission, and service notifications. Include <peinit.h> from the development package and link with pkg-config --cflags --libs peinit. The public headers describe each function's arguments, ownership, and threading requirements.

10.11.1 Versions #

peinit_library_version() returns the package implementation version from build metadata. For source version 0.0.12, it returns "0.0.12". The string uses static library storage; callers must not free it.

peinit_abi_version() returns 0, matching the shared library's SONAME. The implementation version and ABI version have separate meanings. Updating the package does not itself change the ABI number.

10.11.2 Handles and errors #

Free each owned handle with its matching peinit_*_free function. Strings returned by response and error accessors borrow storage from that handle; use them before freeing the handle. Do not pass borrowed strings to peinit_string_free() or the C allocator.

A successful client call means the exchange completed. The service manager can still reject the command. Inspect peinit_response_is_ok() and the response error accessors before treating the requested operation as successful. Local failures return a PEINIT_ERR_* value and can provide an error handle.

10.11.3 Permissions #

The library does not grant authority. The control and jobs sockets check the calling process and the requested operation. A client cannot select an arbitrary service identity by changing a library argument.

11.1 Wiring

Peios / Reference / peinit / Output Handling

peinit is not a logging system — eventd stores, indexes, and queries logs. But peinit holds the pipes at birth. It decides where a service's output goes, and it has to cover the window before eventd exists.

11.1.1 The pipes #

Before exec, peinit creates a pipe for stdout and one for stderr with pipe2(O_CLOEXEC). The child's streams are redirected onto the write ends; peinit keeps the read ends and watches them with epoll.

The blocking discipline is asymmetric, deliberately :

  • The parent's read ends are non-blocking. PID 1 cannot afford to block on a read.
  • The child's write ends keep ordinary blocking semantics.

That second half is what makes backpressure work. When a service produces faster than peinit consumes, the kernel pipe buffer fills and the service's own write() blocks, so the service slows down. Making the write ends non-blocking would turn that into EAGAIN failures in the service, converting a flow-control mechanism into an error the service has to handle.

The child's stdin is redirected to /dev/null. peinit provides no interactive input channel; a service needing input obtains it explicitly — through a socket, or a stored descriptor — never through inherited stdin.

The epoll instance itself is close-on-exec and is never inherited.

11.1.2 Tagging #

peinit reads output line by line and tags each line with:

  • the origin,
  • the stream — stdout or stderr,
  • a CLOCK_REALTIME timestamp,
  • the job's identifier.

The origin is the service name for a main process. For a hook it is the service name, the hook kind and its index — jellyfin/ExecStartPre[0]. Reload commands are <service>/ExecReload and health checks <service>/HealthCheck. A submitted job, which has no service, is jobs/<guid>.

Health check output is captured, which is usually the only way to find out why a health check failed.

11.1.3 The output sink #

A submitted job's output is recorded like any other's; that is unconditional, and eventd is always the primary destination. A submitter can additionally ask for a copy by attaching a descriptor with output: true (§8.5). When the job's pipes are registered, the runtime adopts that descriptor as the job's sink: it is put in non-blocking mode, and every line read from either pipe is written to it as the line followed by a newline, untagged, in the order the lines were read. The two streams interleave; the sink gets what the job wrote and nothing else.

The copy is best-effort and the record is not. A write that would block drops the line for the sink only, counts it, and on the first drop for that job emits one peinit.job.output.dropped event — one per job, however many lines follow — so a submitter that sees a gap can learn it caused one. Any other write failure closes the sink at once. The sink is otherwise closed when the job's last pipe closes, after the last line has gone to it, and a sink attached to a job that never got pipes is closed without a write.

11.1.4 Terminal-attached services #

A service with a TTYPath has all three streams on its terminal, and both pipe pairs are closed in the child (§5.4). Its output is not captured at all — it goes to the terminal, which is what asking for one means.

peinit opens the terminal with read data, write data and read attributes. The last matters because the descriptor is inherited by every process the service starts, and a KACS handle answers fstat only if that right is on it: without it a session can read and write its terminal but not name it — ttyname() fails, tty reports "not a tty", and a program choosing TERM cannot tell a serial line from a virtual console. isatty() is an ioctl and works either way, which is why the gap is easy to miss.

11.2 The Pre-Eventd Buffer

Peios / Reference / peinit / Output Handling

Before eventd starts there is nowhere to send service output: eventd's log socket does not exist until eventd binds it. peinit buffers in memory until then. The buffer is bounded, and drops the oldest entries when it fills.

KeyDefaultMinimumMeaning
Machine\System\Init\PreEventdBuffer10485764096Bytes of output retained before eventd exists.

A value below the minimum keeps the default and logs a warning, rather than being honored or failing the boot (§11.3). Zero is the case that matters: a zero-capacity buffer rejects every record, so honoring it would silently discard the whole pre-eventd window.

The value is read from the registry at boot and refreshed on reload, and the buffer adopts the new capacity each time. Lowering it takes effect immediately, dropping the oldest entries until the contents fit — the same end of the buffer a steady-state overrun drops.

Dropping the oldest rather than the newest is the right way round for this buffer: the point of the window is the boot that is happening now, and the most recent output is what explains where it got to.

Note

In practice the only services that run before eventd are registryd, lpsd, authd and eudev. The first three are Peios-owned with controlled output. eudev is the real overrun risk, being verbose about device enumeration. A crash loop's output is bounded by the restart budget.

11.2.1 Audit records are not logs #

peinit's own audit records — access denials, critical failures, recovery mode entry, graph errors, security-relevant transitions — are events rather than logs. They go into the KMES kernel ring buffer, which persists from the moment PKM loads: before eventd, before the registry, before Phase 2.

So there is no pre-eventd buffer for them, and no window in which they could be lost. eventd picks them up from the ring buffer when it attaches, wherever in the boot they were emitted.

That distinction is the reason the two paths exist at all. Logs are best-effort and lossy by design; audit events are neither.

11.3 Flood Protection

Peios / Reference / peinit / Output Handling

A noisy service cannot be allowed to starve the event loop. Three bounds apply.

KeyDefaultMinimumMeaning
Machine\System\Init\MaxLogLineLength8192256Bytes per line before truncation.
Machine\System\Init\MaxLogBufferPerService655364096Bytes buffered per service pipe before backpressure.
Machine\System\Init\LogReadBytesPerEvent16384512Bytes drained from one pipe per readable event.

A value below the minimum is not honored and does not fail the boot: the compiled-in default is used and a warning is logged naming the key, the configured value and what was used instead. The same rule covers PreEventdBuffer (§11.2), and it is the rule peinit already applies to the equivalent kernel command-line knobs — a typo in a logging knob must not decide how the machine boots, and must not be silent either.

MaxLogBufferPerService's minimum is the one with an external cause: F_SETPIPE_SZ will not go below one page and rounds up regardless, so a smaller number in the registry would describe a pipe that does not exist. The other minimums are engineering judgment — the point below which the mechanism stops working rather than working differently.

A line exceeding MaxLogLineLength is truncated and marked [truncated], with the content trimmed so that content and marker together come to exactly the limit. Everything up to the next newline is then suppressed rather than emitted as a second line.

MaxLogBufferPerService is applied as the pipe's own capacity through F_SETPIPE_SZ , which is a literal reading of "bytes buffered per service pipe before backpressure" — the kernel does the buffering and the bound is where it belongs.

LogReadBytesPerEvent bounds one readable event rather than one loop iteration. A turn with several ready pipes reads up to the budget from each, bounded overall by how many events one epoll wait returns.

11.3.1 Where loss is allowed and where it is not #

At the pipe stage, peinit does not drop. It keeps reading within its budget and appends every complete line; only EAGAIN, end of file, or an error stops the read. Backpressure through the pipe is the flow-control mechanism between a service and peinit, and dropping there would replace it with silence.

Downstream of the pipe, delivery is loss-tolerant by design. The pre-eventd buffer drops its oldest entries when full, and eventd's datagram socket can drop records under load. The no-silent-drop guarantee covers reading the pipe, not delivery to eventd.

Audit events are exempt from all of it. They go through KMES.

11.3.2 Event loop fairness #

No source can starve the loop. Signals are handled at the highest priority — SIGCHLD reaping and shutdown handling take precedence over everything else in every iteration — with the shutdown deadline timer next and every other source below that, ties broken by arrival order.

The power button shares the top priority with signals , on the reasoning that someone physically pressing it is asking for the same class of attention.

11.4 The Eventd Handoff

Peios / Reference / peinit / Output Handling

When eventd reaches Active, peinit switches from buffering to forwarding.

  1. Start sending to eventd's log datagram socket, at the path from Machine\System\eventd\LogSocketPath.
  2. Replay the pre-eventd buffer, oldest first, preserving each line's timestamp and metadata. The replay is best-effort: these are datagrams on a loss-tolerant socket, so some can be dropped, and peinit does not block waiting to deliver them.
  3. Switch to real-time forwarding — new output sent as it arrives.
  4. Clear the buffer.

From there peinit is a relay: read from the pipes, tag each line, forward. Audit events continue to flow as KMES events, entirely separately.

11.4.1 Broker authentication #

eventd's log socket denies FILE_WRITE_DATA to the Service logon group before allowing SYSTEM. peinit's bootstrap token is SYSTEM without that group; every phase-2 service token carries it, including a token whose user is SYSTEM. peinit is therefore the only service-output broker.

peinit does not attach a KACS token per log datagram. The socket descriptor authenticates the broker once at send admission, and peinit derives each origin from the pipe it is draining. Avoiding ancillary token fds also preserves mixed-origin batching and the hot-path reuse described below.

11.4.2 Datagram framing and the record #

peinit sends a msgpack array of one or more records in each datagram. It takes the largest ordered prefix that fits the smaller of the PSPU portable ceiling of 262144 encoded bytes and the log socket's send buffer. It deliberately does not read eventd's larger local ceiling: fixing the producer boundary avoids registry work and means an eventd configuration change cannot invalidate peinit's batches. peinit asks for a send buffer large enough for the portable ceiling when it connects, but the kernel caps what it grants, so the socket's own limit is the one that finally bounds a batch. A successful datagram advances the replay buffer by the whole array, while a failed datagram advances it by nothing. The one exception is a batch the socket refuses as too large: a single record that cannot fit one datagram is discarded rather than replayed forever, and peinit announces the discard on the console.

Each record is a msgpack map :

KeyTypeContent
originstringThe service name, or the hook identifier.
is_errorboolTrue for stderr.
messagestringThe line.
timestampuintNanoseconds, wall clock.
job_idbinThe job's 16-byte GUID in PCDS binary layout. Omitted when absent.

The map has four or five entries depending on whether a job identifier applies.

PSPU §3.7 requires PCDS GUID layout: Data1, Data2, and Data3 are little-endian; the final eight bytes (Data4) retain their byte order. The payload is still exactly 16 bytes.

Note

[peinit 0.0.12

source](https://github.com/peios/peinit/blob/0e20fef16f3c170d8fba0e3a169b617e7b4da3aa/src/logging/msgpack.rs#L69-L82) sends RFC-order UUID bytes instead. The PCDS layout above requires the log job-ID encoding fix; check the installed peinit revision before relying on that encoding.

11.4.3 Lossy delivery #

eventd's log socket is a non-blocking Unix datagram socket. If eventd cannot drain it fast enough its SO_RCVBUF fills and the kernel drops further datagrams silently — sign ingestion deliberately exerts no backpressure on senders.

peinit therefore keeps no unbounded outbound write buffer. It sends bounded arrays of records and accepts that some datagrams can be dropped. It never blocks on a send, and never lets pending records grow without bound.

peinit creates one non-blocking datagram socket when forwarding begins, connects it to eventd, and reuses both that socket and its encoding allocation. It does not create a socket or allocate a fresh output buffer per record. When eventd becomes inactive, the connection is discarded so the next Active transition connects to the newly bound socket.

A drop and a transport failure are handled differently, and the difference is what keeps the lossy design working.

A drop is EAGAIN, EWOULDBLOCK, or ENOBUFS — the receive buffer is full and the datagram did not fit. That is the designed outcome under load, so the connection stands and forwarding continues. Live records in the dropped datagram are gone; peinit counts them and sends the next batch. Replaying the pre-eventd buffer is the one case where waiting beats dropping — those records are already held and the buffer is bounded, so the flush stops and the next turn tries again.

A transport failure is anything else: the socket path gone, the peer refusing. peinit clears the connection, keeps the unsent records in the pre-eventd buffer in order, and the end of the turn re-establishes forwarding by replaying them.

Treating a drop as a transport failure made peinit oscillate between forwarding and buffering under exactly the load the lossy socket exists to absorb, and replay records eventd can already have held — so the busier eventd got, the more work peinit made for it.

11.4.4 When eventd goes away #

peinit supervises eventd like any other service, so it sees the exit directly. It re-enables the pre-eventd buffer, and when eventd restarts and reaches Active the handoff repeats.

There is a log gap between eventd crashing and restarting, bounded by the buffer size. Events are unaffected: they land in the KMES ring buffer regardless of eventd's state, and eventd resumes consuming from the last persisted sequence when it comes back.

11.5 Console Output

Peios / Reference / peinit / Output Handling

peinit writes its own operational messages to /dev/console :

  • Phase 1 progress — mount results, registryd starting.
  • Phase 2 progress — services starting and failing, dependency errors.
  • Shutdown progress.
  • Recovery mode entry.
  • Critical service failures.

Service output is never echoed to the console. The console is for peinit's own messages; a service that wants a terminal asks for one with TTYPath.

11.5.1 The line format #

Every line carries a fixed-width outcome tag, then the component name, then the message:

[      ] peinit: phase1 starting
[  OK  ] peinit: service authd started
[ SKIP ] peinit: service resolvd skipped: DependencyFailure
[ WARN ] peinit warning: calendar timer not armed: Malformed
[FAILED] peinit: service netd failed to launch: token materialisation failed
[ CRIT ] peinit: entering recovery: BootAttempts(3)

The tag column is the point of the format. An operator scanning a boot reads down one column rather than reading sentences, and a failure stops looking exactly like the twenty lines around it.

TagMeans
[ ]Progress with no outcome yet. Holds the column while receding.
[ OK ]It worked.
[ SKIP ]Deliberately not done.
[ WARN ]Wrong, but the boot continues.
[FAILED]It did not work.
[ CRIT ]The machine is about to be lost.

An [ OK ] line reads "mounted", never "mounting": the tag already claims the outcome, so the verb has to agree with it.

11.5.1.1 Tag and severity are different axes #

The tag is presentation. Severity decides who is allowed to print. They correlate but neither determines the other — a Normal service failing and a Critical service failing both render [FAILED] while carrying different severities — and collapsing them would quietly change what peios.quiet=2 suppresses.

11.5.1.2 Color #

Tags are colored with ANSI SGR escapes: green for OK, yellow for SKIP and WARN, red for FAILED, and white-on-red for CRIT. Untagged progress is never colored.

Color is decided once, from the kernel command line, following the same rule systemd uses: on unless the command line says TERM=dumb.

peinit is PID 1 and has no inherited TERM to consult, so the command line is the only place an operator can say a console cannot render escapes. Deliberately not a peios.* token — that set is kept small on purpose, and TERM=dumb is a spelling people already know.

Color changes the bytes and never the layout, so a serial log and a virtual terminal agree about where the message starts.

11.5.1.3 The stage banner #

Before Phase 1 does any work, peinit prints a banner naming the stage and the boot mode:

  ══════════════════════════════════════════════════════════════
   peinit · real root · PID 1 · Full boot                 v0.0.1
  ══════════════════════════════════════════════════════════════

It is punctuation rather than decoration. prelude prints the matching one when the initramfs takes over, so the two mark the handover from kernel to initramfs to real root — the one thing a boot log otherwise never says out loud.

The mode is the one this boot starts in: Full boot, Safe mode, or RECOVERY MODE. A later downgrade to Safe is announced by its own message rather than by reprinting a banner, because a second banner would read as a second stage.

Naming the mode is why the kernel command line is read at the very top of run_init, before any Phase 1 work. That reverses an earlier ordering which assumed mounting the virtual filesystems is what makes /proc/cmdline readable. It is not: the mount step reads /proc/self/mountinfo first, and /proc is provided by the initramfs. One consequence — a machine with both an unreadable command line and another Phase 1 fault now reports the command line as its recovery reason.

The banner carries ordinary status severity, so peios.quiet=2 drops it along with every other kind of progress.

11.5.1.4 Who else writes to this console #

The format is shared by specification, not by shared code. peinit, prelude and the hook scripts each implement it separately, because prelude is a size-critical initramfs PID 1 with no dependencies and the hooks are shell. Changing a tag word or a width means changing it in all three.

Everything peinit runs that reaches the console is in this format, including output peinit did not write itself. Autorun scripts are captured, not left to inherit peinit's streams, and their lines are relayed under the script's own file name :

[      ] 10-apply-seeds.sh: applied 20 file(s), 92 key(s); 0 failed
[  OK  ] peinit: ran 1 autorun script(s)

Relayed lines always carry the blank tag. peinit does not know whether a given line of somebody else's output is good news — the producer knows and peinit does not, and guessing from prose is how a rename silently turns an error green. The producer's outcome is reported separately, from its exit code, which peinit does know.

Relayed lines are sanitised first. A script sharing the console could otherwise steer it with an escape sequence, and peinit's own output shares the device. Three rules apply:

  • Control characters become ?.
  • A line is cut at 512 characters.
  • A producer is capped at 200 lines, with the remainder counted.

The only lines on a normal boot that are not in this format come from outside peinit's reach entirely: the firmware's own messages before any kernel runs, and a service that owns the terminal through TTYPath writing to it directly.

11.5.2 Severity and quiet #

Each message carries a severity, and peios.quiet (§2.6) decides what that means:

  • At 0, everything is written.
  • At 1, the default, peinit stays out of a terminal held as the controlling terminal of a running service, except to announce loss of the system. Terminals are matched by device rather than by path, since /dev/console and /dev/ttyS<n> can be the same device; where the device cannot be determined peinit assumes the terminal is held.
  • At 2, ordinary progress is dropped everywhere while errors still get through.

Suppressed messages are discarded rather than buffered for later.

Shutdown progress carries ordinary status severity, so peios.quiet=2 suppresses it along with every other kind of progress.

The autorun step in Phase 1 (§2.3) bypasses the policy entirely, on the grounds that a script running that early and going wrong is worth interrupting anything for. Its lines are still tagged.

11.5.3 Phase 1 registryd failures #

One deliberate exception to "service output is never echoed to the console". peinit gives every service capture pipes and drains them in the runtime loop — but Phase 1 has no loop, so a registryd that printed exactly why it could not serve was reported to the operator as nothing but registryd readiness timeout expired before READY=1, with the reason sitting unread in a pipe.

When Phase 1 registryd fails to become ready, or says READY=1 and then cannot serve, peinit now drains those pipes and relays what it found :

[FAILED] peinit: registryd failed; what it said follows
[      ] registryd(stderr): open hive Machine: permission denied

Failure path only. On a normal boot the descriptors are retained for the runtime, which drains them into the pre-eventd buffer and on to eventd like any other service's output — so registryd's startup lines are queryable with evctl and are not on the console.

The drain is safe to run from PID 1 because the read ends are non-blocking: a registryd that is alive and silent yields EAGAIN rather than hanging the boot.

Note

peios.quiet governs peinit only. What the kernel prints is governed separately by loglevel, which shipped images set to 4. See Boot and boot modes.

11.6 Terminal Ownership

Peios / Reference / peinit / Output Handling

A TTYPath (§3.2) names a device that has exactly one owner at a time. Two services writing to the same terminal do not fail; they interleave. On a console that produces a sign-in prompt with a progress line through the middle of it, and a password echoed into whatever redrew last. So peinit hands the device to one service and makes the others wait.

11.6.1 Who is holding it #

A service holds its terminal in every state where it can still have a process on the device:

HoldingReleased
Starting, Active, Reloading, Stopping, BackoffInactive, Completed, Failed, Skipped, Abandoned

The two emphasized entries are the ones worth stating outright.

Backoff holds. A service between restart attempts is coming back, and handing its console to somebody else during the gap produces two owners a second later. This is deliberately not the "settled" rule used by boot:settled (§2.5), which also treats Backoff as still moving, but reaches it from the opposite direction.

Abandoned releases , and that one is a compromise. The process survived SIGKILL (§5.7) and can well still be writing. But peinit has no remaining way to reclaim the device from it, so treating it as held would mean the terminal is lost for the rest of the boot — and a console nobody can sign in on is worse than a console with a stuck process on it.

Nothing is stored. The holder is derived from the service table, so there is no claim to leak, to double-release, or to fall out of step with the state machine.

11.6.2 Losing the terminal #

Every start path — boot, deferred, on-demand, restart, and the completion leg after a filesystem check helper (§5.2) — asks whether the terminal is free before it asks anything else. If another service holds it, the start ends there: the service goes to Skipped with cause TtyUnavailable (§6.3), its operation completes, and its dependents are satisfied exactly as any other skip satisfies them.

Skipped rather than Failed, because nothing is wrong. Nothing is written to the console about it either  — it is the mechanism working, and the message would land on the very terminal whose new owner is at that moment drawing on it.

The check runs ahead of the service's own conditions and asserts, which is why a service queued on a busy terminal never forks a check helper.

The graph paths — the Phase 2 boot plan, and any start that brings dependencies with it — ask twice. Their pre-start check runs for every service released together before any of them has moved, so two boot-plan services naming one terminal both pass it. The question is then asked again at the moment each one would enter Starting, and by then the first holds the device: the second is skipped there, with the same cause and the same completed operation, rather than launched into a terminal that already has a session.

A relaunch from Backoff asks too, and a service whose terminal was taken while it waited goes from Backoff to Skipped (§6.2).

11.6.3 Winning the terminal #

TTYPrecedence decides who wins when several services want the same device at the same moment. Higher wins; equal precedence breaks on service name , so an operator who states no preference still gets the same machine on every boot rather than whichever definition the registry happened to enumerate first. The default is 0.

Precedence is consulted among simultaneous candidates only. A service that already holds a terminal is never preempted by a higher-precedence latecomer : taking a live terminal away from a process that is using it would lose whatever the operator was in the middle of typing.

Two places have simultaneous candidates. Deferred starts (§2.5) are dispatched highest-precedence first, so the winner takes the device and the rest are skipped. Handovers, below, pick one winner outright.

Within the Phase 2 boot plan the order is the dependency graph's, not precedence's  — a boot-plan terminal service is being written over by peinit's own progress output anyway, which is what boot:settled exists to avoid.

11.6.4 Handing it on #

A service that names a terminal and carries the tty:released trigger (§3.4) is started when that terminal comes free. peinit watches every transition out of a holding state, so it does not matter whether the holder exited cleanly, crashed, was stopped by an administrator or was evicted by a conflict — all four free the device , and the waiter is wanted after a crash more than after a clean exit, not less.

Which terminal was released is recorded on the transition, not looked up afterward, and that is load-bearing rather than tidy. A service whose definition has been removed loses its table entry the moment it reaches a state that does not retain one (§3.8) — the same moment it releases its terminal. Asking afterward which TTYPath it had gets nothing.

That is not a corner case. It is precisely what a service that retires itself does: remove its own definition so it never runs again, then exit. First-boot setup is exactly that, and before the release rode on the transition it ended by telling the operator they could sign in, on a console it had vacated and nobody had been given.

One winner per release, chosen by precedence. Starting the whole queue would have every loser immediately skipped again by the rule above: the same outcome, reached noisily, with a skipped-looking service for each.

Two services are never offered a terminal:

  • The one whose exit freed it. It has the strongest claim on its own console, so without this exclusion the highest-precedence holder restarts itself on every exit — a restart policy with no budget, and one no waiter behind it ever gets past. Relaunching a service that stopped is RestartPolicy's job (§6.4).
  • One whose definition has been removed (§3.8), since it cannot be started at all.

A waiter is usually sitting in Skipped when its turn comes, from the moment it lost the terminal. The handover starts it as an explicit start would, which is the transition that takes a service out of Skipped (§6.2) and re-evaluates its conditions.

11.6.5 Conflicts #

Conflicts (§7.1) fails both services when they meet in one boot. The services that want a terminal are the interactive ones — a sign-in prompt, an installer, a first-boot setup flow — so that answer is a machine with no way into it.

A dependency says the wrong thing twice. A sign-in prompt does not need first-boot setup to have run; it needs the console to be free, and a setup flow that failed frees it as well as one that succeeded. And naming the holder would mean rewriting every waiter each time the set of things that might take the console changed.

What is left is a queue on a device, which is what this is.

11.6.6 Fixed system-console endpoints #

When the LCS boundary reads service definitions, /dev/console in TTYPath is resolved from the last entry in /sys/class/tty/console/active. A tty0 endpoint is pinned to /dev/tty1; an explicit /dev/tty0 is also pinned to /dev/tty1. The selected system-console endpoint is cached for the boot so registry reloads and foreground VT changes do not move existing sessions. Resolution failure makes the affected definition undecodable, rather than silently opening a moving alias. Arbitration and process launch use the same resolved path.

On terminal main-process exit the runtime kills the exiting job's cgroup before releasing the terminal or scheduling its successor. Descendants belong to the session that ended, not the next sign-in attempt. Other terminal services and ordinary daemon lifecycle semantics are unaffected. An error killing the cgroup fails terminal-event processing; a new prompt must not be scheduled through that error.

11.7 Service Output Flow

Peios / Reference / peinit / Output Handling

These notes collect the output-flow explanation behind finding service logs. The preceding sections define the precise transport and limits. Service-output delivery is best-effort; KMES events use a separate finite in-memory ring, and eventd supplies persistence.

11.7.1 Capturing output #

When peinit forks a service it creates pipes for stdout and stderr, redirects the child's streams to the write ends, and keeps the read ends — monitoring them in its event loop. (The child's stdin is /dev/null; see The execution environment.) It reads output line by line and tags each line with:

  • the service name,
  • the stream (stdout or stderr),
  • a timestamp,
  • the job GUID.

The job GUID is the important one: it is what lets a later query return exactly one execution's output, never interleaved with the run before or after it. Hook output is captured too, labeled with the hook (for example jellyfin/ExecStartPre[0]), and so is health-check output — invaluable for diagnosing why a check failed. A submitted job's output is captured the same way, labeled jobs/<id>; its submitter cannot opt out of that, but can ask for a copy by attaching an output sink, to which peinit writes each line as it reads it. The copy is best-effort — lines the sink cannot take are dropped for the sink only, while forwarding to eventd continues independently, and reported once per job as an output.dropped event — and the sink never slows the job or peinit.

11.7.2 The pre-eventd buffer #

Before eventd is running there is nowhere to send logs — its socket does not exist yet. peinit therefore buffers captured output in a fixed-size in-memory pre-eventd buffer (default 1 MB); when it fills, the oldest entries are dropped.

In practice the only services that run before eventd are registryd, lpsd , authd, and eudev. The first three are Peios-owned with controlled output; eudev is the real overrun risk (verbose device enumeration), and the restart budget naturally bounds output from a crash loop.

11.7.3 Flood protection #

A noisy service must never starve peinit's event loop. Several limits enforce that:

Key (Machine\System\Init\)DefaultLimits
MaxLogLineLength8192Bytes per line; longer lines are truncated with a [truncated] marker.
MaxLogBufferPerService65536Bytes buffered per service pipe before back-pressure.

Two mechanisms back these up:

  • A per-readable-event budget. LogReadBytesPerEvent bounds the bytes drained from one pipe per readable event. A loop turn with several ready pipes can read up to that budget from each; see §11.3.
  • Back-pressure, not dropping. If a service writes faster than peinit reads, the kernel pipe buffer fills and the service's own write() calls block. This is deliberate: the service slows down. While reading the pipe, peinit does not drop output — the no-silent-drop guarantee covers reading the pipe. It is only downstream (the pre-eventd buffer, and eventd's datagram socket) that delivery becomes lossy.

Note

Signals are never starved. In every loop iteration, child reaping (SIGCHLD) and shutdown handling take priority over all other event sources, including log reading. A flood of service output can never delay peinit noticing that a service died or that the system is shutting down.

11.7.4 The eventd handoff #

When eventd reaches Active, peinit switches from buffering to forwarding:

  1. It begins sending to eventd's log datagram socket (path from Machine\System\eventd\LogSocketPath).
  2. It replays the pre-eventd buffer, oldest first, preserving each line's timestamp and metadata. This replay is best-effort — the records are datagrams on a loss-tolerant socket and some can be dropped under load; peinit never blocks waiting to deliver them.
  3. It switches to real-time forwarding — new output goes out as it arrives.
  4. It clears the buffer.

From then on peinit is a pipe relay: read lines, tag them, and forward the largest ordered batch that fits the smaller of the portable 262144-byte ceiling and the log socket's send buffer. peinit does not read eventd's larger local ceiling; see §11.4. It keeps one connected socket and reuses its encoding buffer, so normal forwarding does not create a socket or output allocation for every line. The log socket is non-blocking and loss-tolerant — if eventd cannot drain it fast enough the kernel drops further datagrams silently, because sign ingestion must never exert back-pressure on the whole system through PID 1. peinit keeps no unbounded outbound buffer and never blocks on a send to eventd.

If eventd itself crashes after starting, peinit (which supervises it like any service) notices, re-enables the pre-eventd buffer, and repeats the handoff when eventd comes back. There can be a log gap across the restart, bounded by the output buffer. Structured events use the independent KMES ring; eventd can resume reading the events that remain there. The ring can overwrite old events and does not survive reboot, so eventd supplies persistence rather than KMES. See KMES failure modes.

12.1 Triggers

Peios / Reference / peinit / Shutdown

Four paths initiate a shutdown.

12.1.1 The control socket #

A shutdown command naming a type, gated on SYSTEM_SHUTDOWN against peinit's control descriptor (§4.7):

TypeEffect
poweroffStop everything, unmount, power off.
rebootStop everything, unmount, reboot.
haltStop everything, unmount, halt — the CPU stops, the system stays powered.

12.1.2 Signals #

SignalMeaning
SIGINTReboot. The kernel sends it on Ctrl+Alt+Del.
SIGTERMPoweroff. PID 1 cannot be killed by it but can choose to act on it.
SIGPWRPoweroff. The compatibility path for environments that surface power failure or a power-button policy as a signal.

Three SIGINTs within five seconds force an immediate shutdown: no graceful stop, no ordering, SIGKILL every service cgroup, sync, reboot. The window is a sliding five seconds and the press is recorded before the already-shutting-down check, so three presses still force even after a graceful reboot has begun. That is the point — someone pressing it three times has decided the graceful path is not working.

12.1.3 The power button #

An EV_KEY / KEY_POWER press from a readable /dev/input/event* device is a graceful poweroff. Only a press — value 1 — initiates. Releases, key repeats, other keys, and other event types are ignored.

The path is fail-soft throughout: a missing /dev/input, a device that cannot be opened or registered, and a registered descriptor that later fails to read are all survivable, and a failing descriptor is removed from the event loop so repeated failures cannot spin PID 1. Losing it degrades only direct power-button handling; the socket and signal paths remain.

It is deliberately minimal. It is not a power-management policy engine and does not replace a future daemon that would translate richer policy into control socket commands.

12.1.4 Critical service failure #

A Critical service entering Failed with its restart budget exhausted means peinit syncs the filesystems and reboots immediately. This is not a graceful shutdown: there is no stop ordering, no seed save, and no unmount. The system is in an undefined state and the fastest path to a defined one is a reboot.

12.2 The Graceful Sequence

Peios / Reference / peinit / Shutdown

12.2.1 Step 1: Enter the shutdown state #

peinit sets an internal flag. While it is set, no new service starts. Control commands other than status, list, operation-status, job-status, job-list, and job-stop are rejected as invalid for the current state.

Every live submitted job (§8.5) is stopped at this point too: SIGTERM to each — unless it has already sent STOPPING=1 — with cause shutdown, its own stop_timeout to the kill, and no ordering between jobs or against the service waves, because a job has no dependencies to order by. A job still queued for launch is canceled with the same

cause. submit is refused for the rest of the shutdown; status, wait, stop and signal keep answering, as do the control socket's job-status, job-list and job-stop.

Timer triggers are disarmed. The timerfds stay armed and keep firing — peinit gates the handler rather than the fd, matching how every other event source is handled — but a firing during the shutdown window is classified as a no-op and nothing is started or queued.

The gate matters more than the rule reads. The states a timer firing would start from are Inactive, Completed and Failed, precisely the states step 3 classifies as not participating, so a firing would create a service after the plan was fixed: in no wave, not waited for, and not reached by the global-timeout sweep, still holding files open when peinit reaches the unmount step.

12.2.2 Critical #

A Critical service failing during shutdown is recorded but does not trigger a reboot. The system is already going down, and rebooting from here would loop.

12.2.3 Step 3: Classify #

Completed services — Oneshots with RemainAfterExit — have no process and are transitioned to Inactive, releasing the dependency relationships they were holding so their dependents can be stopped cleanly.

The rest are classified for stop eligibility:

  • Active and Reloading are graceful-stop eligible and enter the waves.
  • Stopping services are already on a stop path. They join the waves for ordering and timeout purposes, but do not receive another SIGTERM.
  • Starting services are not eligible. peinit cancels the startup, SIGKILLs the service cgroup if one exists, and transitions them to Failed with cause ShutdownWave while post-kill verification is pending. A cgroup still populated after the post-kill timeout takes the service to Abandoned with cause ProcessUnkillable and the cgroup is leaked. A Starting service whose job never forked skips the check and goes straight to Failed.
  • Inactive, Failed, Skipped, Backoff, and Abandoned do not participate. Abandoned cgroups stay leaked and shutdown continues.

12.2.4 Step 4: Stop in reverse dependency order #

peinit builds the reverse dependency graph over hard dependencies and stops in waves:

  1. Each eligible service receives SIGTERM. Already-stopping ones do not.
  2. Each has StopTimeout to exit.
  3. On expiry, SIGKILL to the service's entire cgroup.
  4. No service is stopped until everything depending on it has stopped.

The compiled-in Phase 1 service, registryd, stops in a wave of its own after every other participant, though no definition declares a dependency on it. Every service defined in the registry rests on it, as it started before any of them; stopped by the graph alone it would land in the first wave and go while the services still running needed it. The rule follows the definition's compiled-in provenance, not its name.

A participant the service table does not have counts as stopped. A service whose definition is withdrawn while it runs is kept until it stops and then discarded (first-boot setup withdraws its own service this way), and the plan fixed at step 3 still names it. Waiting for it would hold its wave open for good.

A service that sent STOPPING=1 does not receive a SIGTERM at all: it has already said it is shutting down, and peinit goes straight to the stop deadline. The notification is acknowledged as a peinit.notify.stopping.reported event (§10.5), which is what makes the suppressed SIGTERM legible afterward rather than looking like one peinit failed to send.

12.2.4.1 Observing the waves #

Every stop-wave participant receives its own Shutdown -sourced Stop record when the shutdown plan is fixed. Its requested event records the intent; its started event records when the participant's wave becomes eligible, including when an existing stop is adopted without another SIGTERM. The records and their identifiers are visible through the ordinary operation queries and peinit.operation.* events.

A service that exits cleanly before its wave completes its Pending observation without a started event. A crash before the wave fails it. For a service already stopping, reaching Inactive completes the observation; a stop timeout, global timeout, or forced reboot fails it. Post-kill abandonment does not produce a second terminal result for an observation already failed at the kill. Starting services retain their existing startup-failure records, and Completed services cleared without a process do not receive stop observations.

An administrator Stop or Restart already in flight keeps its identity and its original timing evidence. The shutdown observation is separate; it neither supersedes that record nor queues a second control command.

12.2.4.2 Timing an already-stopping service #

peinit does not reset an already-Stopping service's clock, either when shutdown begins or when its wave becomes eligible. It uses the timing evidence retained from the stop path that put the service in Stopping:

  • If a Stop operation, or a Restart executing its stop leg, is in flight, that operation's retained timing governs.
  • Otherwise peinit uses service-level evidence, which carries the cause that initiated the transition — ExplicitStop, ShutdownWave, ConflictEviction, or BindsToPropagation.

peinit requires the evidence to be present, to belong to a service actually in Stopping, to carry a cause matching the service's current cause, to name one of those four causes, and not to describe a deadline earlier than its own start.

Evidence that is missing, stale, or ambiguous fails closed rather than being guessed at. A stop that began before the shutdown has already spent part of its own clock, and inventing a fresh budget here would hand the service a second full StopTimeout.

Failing closed costs that one participant, not the shutdown. A service whose evidence cannot substantiate a deadline is given no graceful period at all: its deadline is already due, so the timeout scan escalates it to SIGKILL on its wave, and the console says which way the evidence was unusable:

peinit: shutdown cannot substantiate a stop timeout for <service>
(<reason>); killing it without a graceful period

Every other participant keeps its full StopTimeout, and the shutdown runs to completion.

An operation whose lifetime expires while it is still Pending — a later-wave stop waiting for its dependencies — fails that operation and its waiters. It does not authorize signaling the service before its wave is eligible. Shutdown owns the signaling; the operation object is an observation of it.

12.2.5 Step 5: Global timeout #

KeyDefaultMeaning
Machine\System\Boot\ShutdownTimeout90Seconds for the whole sequence.
Machine\System\Boot\PostKillTimeout5Seconds for a cgroup to drain after SIGKILL.

On expiry, every remaining participant's cgroup is killed, anything that does not drain within the post-kill timeout is marked Abandoned with its cgroup leaked, and shutdown continues regardless. Live submitted jobs are killed in the same sweep, whatever phase their stop had reached, and abandoned on the same terms.

The global timeout fires once. What its sweep killed is then governed by the post-kill timeout alone: sweeping again would kill the survivors again and push their post-kill checks back each time, so nothing would ever be abandoned and the sequence would never reach step 6.

The console says what the sequence was waiting for when the timeout fired, and, after any later timeout turn that leaves it still waiting, what remains: participants with their state and wave, pending stop and post-kill checks, and live jobs.

peinit: shutdown global timeout expired waiting for lpsd (Active, wave 1), job <id>
peinit: shutdown still waiting for post-kill check of lpsd

Submitted jobs are named on the console as they are stopped, killed and abandoned: peinit: shutdown stopping job <id>, killing job <id>, and abandoned job <id>.

The sequence does not move to step 6 while a submitted job is live. A job's reap advances shutdown progress exactly as a service's does, so a session that exits promptly on SIGTERM costs the shutdown nothing, and one that does not costs it stop_timeout and the post-kill grace.

12.2.6 Step 6: Save the random seed #

After every service has stopped and before any unmount, peinit writes a fresh seed to /var/state/peinit/random-seed for the next boot: 512 bytes from the kernel CSPRNG on this machine, never copied from an image, protected so that only SYSTEM-equivalent authority can read or replace it.

The write is crash-conscious: a temporary file on the same filesystem, written, flushed, atomically renamed over the old seed, and the containing directory flushed. A failure is recorded and shutdown continues.

The forced and Critical-reboot paths skip it, along with the unmount step, and go directly to sync and the final action.

12.2.7 Step 7: Unmount #

  1. Snapshot the mount table first, from /proc/self/mountinfo.
  2. Attempt to unmount every remaining non-root mount in the namespace — not only what peinit mounted, so the Phase 1 set is covered by construction.
  3. Process in descending path depth, so children go before parents.
  4. A mount point already gone is a successful no-op.
  5. On failure, attempt a read-only remount. If that fails too, record it and continue.
  6. The root is never unmounted, but is remounted read-only at the end. A failure there is recorded and does not stop step 8.

12.2.8 Step 8: Sync and the final action #

This step is irreversible. Cleanup failures retained from steps 6 and 7 affect diagnostics only and never block it.

  1. sync(). Called on all three paths — graceful, forced, and Critical reboot.
  2. reboot(2) with RB_POWER_OFF, RB_AUTOBOOT, or RB_HALT_SYSTEM.
  3. If reboot(2) returns, the final action failed. peinit enters a minimal failed-shutdown state, keeps PID 1 alive, records the failure, and retries the same action no more than once a second. It does not restart services and does not enter recovery mode — finalization has begun and there is nothing to go back to.

12.2.9 Shutdown during boot #

A shutdown requested while Phase 2 is still running takes effect immediately, through the same classification: Starting services are SIGKILLed, services that reached Active are stopped gracefully, and the boot is abandoned.

12.3 Signals

Peios / Reference / peinit / Shutdown

PID 1 handles every signal through a signalfd. All signals are blocked and read from the event loop. So peinit installs no signal handlers of its own, and nothing peinit writes has to be async-signal-safe.

/proc/1/status does report two caught signals, SIGSEGV and SIGBUS. They are the Rust runtime's stack-overflow guard, which runs on an alternate stack and touches nothing peinit owns, so the reasoning above is unaffected.

12.3.1 Setup #

peinit builds a mask containing every blockable signal in the supported range — SIGKILL and SIGSTOP are not blockable and are never delivered through a signalfd — and installs it with rt_sigprocmask(SIG_BLOCK, ...) before entering the main event loop. It then creates the descriptor with signalfd4(-1, mask, ...), using the same mask, with SFD_CLOEXEC | SFD_NONBLOCK.

If any part of that fails — blocking, creating the descriptor, retaining it, registering it with the event loop — peinit fails closed. There is no fallback to asynchronous handlers, because a PID 1 with handlers installed where it expected a signalfd is a PID 1 whose assumptions about what can interrupt it are wrong.

The mask is inherited across fork, which is why every child resets it before exec (§5.4).

12.3.2 The signals #

SignalBehavior
SIGCHLDReap children with waitpid. Match them to tracked jobs; also reap orphans belonging to nothing.
SIGINTReboot. Three within five seconds forces one.
SIGTERMPoweroff.
SIGPWRPoweroff.
SIGHUPIgnored. PID 1 has no controlling terminal.
SIGPIPEIgnored. A broken pipe on the control socket cannot be allowed to kill PID 1.

Everything else is ignored. The kernel protects PID 1 from fatal signals, so no signal can kill it.

12.3.3 Reaping #

peinit reaps with waitpid(-1, ..., WNOHANG) in a drain loop, and normalizes the wait status before any service or job policy sees it:

  • An exited child carries its exact exit code, 0–255.
  • A signaled child carries the terminating signal number and whether the core-dump bit was set.

  • A stopped or continued status is invalid on this path, because peinit never asks for them. Observing one fails closed rather than being interpreted.

That last rule matters more than it looks. A stopped child reported as an exit would be read as a service that had terminated, and peinit would act on a process that is merely paused.

As PID 1, peinit also reaps processes nobody is tracking — orphans reparented to it — and reports them as untracked rather than trying to attribute them to a service.

12.4 Finalization

Peios / Reference / peinit / Shutdown

Three shutdown paths reach the kernel, and they do different amounts of work on the way.

PathStop wavesSeed saveUnmountSyncFinal action
GracefulYesYesYesYesYes
Forced — three SIGINTsNo, SIGKILL everythingNoNoYesYes
Critical service failureNoNoNoYesYes

The two abrupt paths are required to reach sync() and the final kernel action with minimal additional work, and skipping the seed and the unmounts is what "minimal" means. A machine that is rebooting because its audit daemon died has nothing to gain from a tidy unmount and something to lose from the time it takes.

12.4.1 What survives a failure #

Steps 6 and 7 — the seed and the unmounts — retain their failures as evidence rather than acting on them. Every one is recorded, none of them blocks step 8, and none of them enters recovery mode. By this point there is nothing to recover to: services have stopped and the filesystems are on their way down.

12.4.2 If the final action returns #

reboot(2) does not return on success. If it does, the final action failed, and peinit enters a minimal failed-shutdown state:

  • PID 1 stays alive. It has to — PID 1 exiting panics the kernel.
  • The failure is recorded.
  • The same action is retried, no more than once a second.
  • Services are not restarted, and recovery mode is not entered.

There is no way back from here. Finalization has begun, the services are gone and the filesystems are read-only; the only correct behavior is to keep trying the one thing that would end it.

RB_HALT_SYSTEM does not return either, so this state is only reachable for a genuine failure rather than for the halt case.

12.4.3 A note on the mount table #

The unmount step re-reads /proc/self/mountinfo when checking whether a mount point that returned ENOENT or EINVAL is really gone. Depth ordering puts the depth-one mounts last, alphabetically — /dev, /proc, /run, /sys — so /proc is unmounted before /run and /sys are attempted. Neither of those answers ENOENT or EINVAL in practice — /sys unmounts, and /run either unmounts or is busy — so the check never runs for them. It is a latent hazard rather than a live one: if either ever did answer that way, the check could not read the file it needs, and the shutdown would record a cleanup failure and attempt a pointless read-only remount.

13.1 Trust Boundaries

Peios / Reference / peinit / Security

peinit sits at two.

13.1.1 Kernel to peinit #

peinit is the first userspace process, and the kernel gives it a SYSTEM token — S-1-5-18, every privilege. This is the root of trust for all userspace identity on the system.

peinit does not drop that token and does not authenticate to anything. Its identity is axiomatic: there is no authority above it in userspace that could vouch for it, and the kernel handing it the boot token is the vouching.

13.1.2 peinit to services #

peinit creates service processes with specific identities and reduced privileges. The trust runs one way. peinit trusts the kernel because it has no alternative; services trust peinit because peinit gave them their identity. Services do not trust each other — KACS mediates every access between them, and nothing peinit does creates a relationship between two services beyond the ordering their definitions asked for.

13.1.3 The TCB #

peinit is part of the Trusted Computing Base, alongside the kernel, KACS, LCS, KMES, registryd, authd, lpsd and eventd. A compromise of any of them compromises the system.

That list is not decoration. It is why registryd is exempt from the global environment layer (§5.5) — a component in the TCB cannot be configurable by a mechanism it is itself the enforcement point for — and it is why eventd is Critical, since a TCB whose audit trail can be silently stopped is not one.

13.1.4 Filesystem enforcement #

KACS enforces Security Descriptors on filesystem access. peinit's Phase 1 descriptor seeding (§2.3) exists precisely because of it: a freshly mounted tmpfs carries no descriptor, and under DENY_MISSING every inode on it would be unreachable to everything — including peinit — until something stamps a descriptor it can inherit from.

That enforcement has no bypass. There is no owner exemption, no privilege that overrides a missing descriptor, and no root escape , which is what makes the seeding step fatal on failure rather than advisory.

FACS extends the model further, and until it lands the filesystem layer still relies partly on conventional trust — correct packaging, controlled binary paths — for the objects nothing has stamped.

13.2 Peinit's Privileges

Peios / Reference / peinit / Security

peinit runs as SYSTEM with every privilege for the lifetime of the system. What it actually exercises is narrower.

Privilege or capabilityUsed for
SeCreateTokenPrivilegeMinting SYSTEM tokens for platform services during bootstrap, before authd exists (§4.2).
SeTcbPrivilegeRequesting tokens from authd on a service's behalf, and installing a primary token on a child whose identity differs from peinit's own — a service's, or a submitted job's.
SeAuditPrivilegeWriting events: KMES refuses an emit from a token without it enabled. And recording access decisions: an AccessCheck peinit runs writes the kacs.audit.access.checked record its descriptor's SACL asks for only while the caller holds it enabled (§8.4).
Token duplicationTurning a job identity into the primary token a submitted job runs as (§8.5): opening the submitter's own primary through its pidfd, or taking the token the kernel attached, and duplicating either to a primary. SYSTEM holds full access on every token's default descriptor, which is what makes the duplicate permitted.
Process creationFork and exec, inherent to PID 1.
cgroup managementCreating and destroying trees under /sys/fs/cgroup/peinit/.
Signal deliverySIGTERM and SIGKILL to managed processes.
Mount operationsThe Phase 1 virtual filesystems.

peinit verifies the three privileges at startup, before Phase 1 does anything that needs them, and fails to recovery naming which is missing :

peinit: required privileges are not held: Token("peinit is missing
required privilege(s): SeCreateTokenPrivilege")

Present and enabled — a privilege the token carries but has not enabled is not usable, and would fail identically to being absent. SeAuditPrivilege is the exception: held but disabled, peinit enables it before checking, rather than run with no events and no record of who was refused what. The boot SYSTEM token PID 1 runs as holds every privilege enabled, so on a token the kernel made the check passes and changes nothing.

The check earns its place by what it replaces. A missing SeCreateTokenPrivilege used to surface as an EPERM from the first token mint, which is the first service start — registryd, in Phase 1 step 6. So a peinit that could not mint tokens entered recovery reporting what read as a registryd problem, and nothing anywhere named the privilege.

SeImpersonatePrivilege is not required and not checked, even though it appears in the requirement list peinit was specified against. It is not used. peinit passes the peer's token descriptor to AccessCheck directly rather than impersonating the caller and evaluating as them, so the privilege that would be needed to impersonate is not needed at all. The same holds on the jobs socket: peinit never impersonates a submitter, and the identity a job runs as is one the kernel already verified the submitter could convey.

For non-platform services peinit creates no tokens. It installs the ones authd minted. It mints only for the SYSTEM platform services it starts during bootstrap, before authd is available.

Note

Minting is interim. The intended model derives a service's token from peinit's own handle through a KACS duplicate-with-additions operation — kernel-attested as a descendant of peinit's real token, and needing no minting privilege. That would let peinit drop SeCreateTokenPrivilege entirely, which is the point: the privilege to mint arbitrary tokens is the strongest thing peinit holds and the one it has the least use for.

13.3 The Attack Surface

Peios / Reference / peinit / Security

SurfaceReachable byControlsProtected by
Control socketEvery authenticated principal, by defaultService lifecycle, shutdown, observing, and stopping jobsThe peer token and AccessCheck against the target's descriptor for every command; a per-user connection limit
Jobs socketEvery authenticated principal, by defaultRunning a program under supervision as an identity the submitter holds; managing the jobs it submittedThe socket inode's descriptor, which is the whole of the submission permission; the kernel's gating of the attached token; the job's own descriptor for every later command; a per-submitter quota
Notification socketAnything that can connectService readiness, watchdog, stored descriptorsThe socket inode's descriptor, then PID matching verified through a pidfd, plus the start generation
Registry keysAnything with registry accessDefinitions, triggers, configurationRegistry key descriptors, enforced by LCS
Machine\System\Init\EnvVars\Anything with registry accessThe environment of every serviceThat key's descriptor, and nothing else — variable names are not filtered
Service cgroupspeinitProcess tracking and clean killOwnership of the hierarchy
Phase 1 mountspeinitVirtual filesystem availabilityHardcoded, no external input
/lcl/policy/autorun.dWhatever can write itArbitrary code as SYSTEM in early bootThe directory's descriptor
Boot attempt counterWhatever can write /.peinit/Recovery mode entryThat file's descriptor

13.3.1 What the socket descriptors mean in practice #

The control socket admits every authenticated principal (§10.1), and what each can then do is decided per command by the control descriptor and each service's own. The ACCESS_DENIED path and the KACS audit record it produces are therefore reachable by anyone who can sign in: a caller can make as many kacs.audit.access.checked records as it has refused commands to send, because the default SACLs ask for one per refusal; a descriptor whose SACL audits less makes fewer. So is peinit's request parser, which bounds every request by MaxRequestSize before parsing it. What one caller can hold open is bounded by MaxControlConnectionsPerUser, so no one caller can fill the connections everyone shares.

The notification socket is stamped for SYSTEM and for the Service group S-1-5-6 (§10.5) — every process started as a service, and nothing else. Administrators are deliberately absent from it: an administrator has no business asserting that a service is ready, and the two sockets have different populations however alike their paths look.

A connection to the notification socket from any other principal is refused at connect(), by the filesystem, before peinit ever obtains a peer token — which means no audit event records it.

The jobs socket is deliberately wider: FILE_WRITE_DATA for Authenticated Users, full control for SYSTEM and Administrators (§10.7). Connecting is the submission permission, and peinit adds no check of its own behind it. What bounds the population that can reach it is that descriptor, and what bounds what any one submitter can do is the quota and the rule that a job runs only as an identity the kernel verified the submitter held. The ACCESS_DENIED path is reachable here — it is how a submitter learns it can not touch another submitter's job — and every such denial is the job's SACL's to record: under a job's default descriptor, KACS records each as kacs.audit.access.checked naming the job (§8.4).

These moved together with §4.3, and had to. A service resolved to a non-SYSTEM identity could not have reached the notification socket to report that it had started, so making identity real while the socket stayed SYSTEM-only would have broken every non-SYSTEM service's readiness protocol at once. What makes the pair work is that the tokens peinit mints for itself now carry S-1-5-6 as well, so a SYSTEM service and a LocalService one are on the same footing here.

13.3.2 The autorun directory #

The Phase 1 autorun step (§2.3) executes every file in /lcl/policy/autorun.d as SYSTEM, before path provisioning and before any service. It is fail-open by design, so nothing about a script going wrong stops the boot.

Its only protection is the descriptor on that directory. Anything that can write there executes as SYSTEM at the earliest point in userspace that exists.

13.4 Security Invariants

Peios / Reference / peinit / Security

Properties peinit does not violate.

1. peinit does not grant privileges it was not asked to grant. RequiredPrivileges is subtractive. peinit removes privileges and never adds one — there is no code path that constructs anything but a removal (§4.5).

2. peinit does not bypass AccessCheck for control operations. Every control command reaches a check against the appropriate descriptor. There is no backdoor, no override flag, and no "trust localhost". Every command on a submitted job, on either socket, is checked against the job's own descriptor — the submitter included, and the job identity excluded unless the descriptor says otherwise (§8.5).

3. peinit does not expose one service's state to another without access control. list returns only what the caller can query, and status is checked per service; job-list and job-status are checked per job (§10.2).

4. No access denial is silent by default. Every check names its object to KACS in an audit context, and every descriptor peinit builds itself — the default service descriptor, the control descriptor, a submitted job's default — carries a SACL auditing every refusal, so a failed AccessCheck is recorded by KACS as kacs.audit.access.checked with the caller, the object and the access requested and granted (§8.4). A descriptor written to the registry or supplied with a job is honored as it is, SACL included; whoever can write one is trusted with that object's audit policy (§4.6). The MAXIMUM_ALLOWED check that fills a response's granted refuses nothing (§10.2).

5. The control descriptor, the ServiceSecurity descriptors, and the per-job descriptors are the only policy inputs for runtime access control. peinit consults no configuration file, no environment variable, and no hardcoded principal list. The only inputs to AccessCheck are those descriptors — the first two sourced from the registry with a compiled-in default, the third fixed at submission from the submitter's SID or the SDDL it supplied. Who can submit is not a policy input at all: it is the jobs socket's file descriptor, decided by the filesystem before peinit sees the connection.

6. peinit does not share its SYSTEM token. It opens its own token query-only, as a template, and never installs it on a child. Even an Identity=SYSTEM service gets a separately minted token.

7. peinit does not drop its SYSTEM identity. PID 1 runs as SYSTEM for the lifetime of the system. Only the forked child installs a token; peinit never installs one on itself.

8. Identity is deterministic, and the dangerous case is never implicit. Every service runs with a known identity. SYSTEM has to be declared explicitly; an absent or empty Identity means LocalService.

The identity parser maps an absent or empty value to LocalService. It selects SYSTEM only when the definition names it. After authd mints a token, peinit checks that its user SID matches the declared identity. A mismatch fails the launch (§4.3).

9. A submitted job runs only as an identity the kernel verified its submitter could convey. There is no identity field, no route from a plain descriptor to a job identity, and no token opened through a PID or descriptor the submitter named. The job identity is the connecting process's own primary — reached through the kernel's handle on that process — or the token the kernel attached to the message after running the impersonation gates with the submitter as installer. peinit never re-derives that decision and never refuses a token for who it names (§8.5).

14.1 Losing the Registry

Peios / Reference / peinit / Failure Modes

peinit depends on the registry once, hard, and then never again in the same way. The difference between those two situations is most of what this section is about.

14.1.1 Phase #

registryd failing to start, failing readiness, or failing the schema-version probe sends peinit to recovery mode immediately. There is no Phase 2 without a registry and nothing useful to degrade to. The counter is incremented, so a persistently broken registryd burns boot attempts even though every one of them fails the same way.

The recovery shell reached from this failure does not have registryd running, and the offline tools (§2.8) are what an administrator has. A Phase 1 failure earlier than the registryd step is different: recovery starts a registryd of its own there (§2.8).

14.1.2 Phase #

A registry read that fails or times out during the definition read sends peinit to recovery, for the same reason: there is no graph to boot.

14.1.3 At runtime #

This is where the design pays off. peinit holds a complete in-memory model and does not read the registry during normal supervision, so registryd going away does not stop peinit supervising anything. Services keep running, restarts keep working, the control socket keeps answering, and timers keep firing.

What stops working is anything that needs new configuration: reload-config fails. Change notifications stop arriving, and a timer's last-run timestamp cannot be written — so a persistent timer can produce a spurious catch-up on the next boot.

registryd itself is a Critical service , so its failure takes the ordinary Critical path: restart budget, then sync and reboot. peinit does not have to handle a permanently absent registryd at runtime, because the system reboots first.

14.1.4 A definition that will not decode #

One definition that fails to decode fails that definition (§3.2). At boot the key is marked Failed with cause ValidationError and every other service starts normally; on a reload the key is failed the same way and every other definition loads. One malformed key does not stop unrelated definitions in the same batch from taking effect, and a boot has no previous generation to fall back to anyway, so refusing everything would mean not booting at all over a single malformed key — which is what it used to do.

14.2 Losing a Dependency

Peios / Reference / peinit / Failure Modes

14.2.1 authd #

Without authd, no non-SYSTEM service can obtain a token, so every such start fails with ParentSetupFailure. Platform services are unaffected, since they never take that path.

authd is Critical , so its own failure eventually reboots the system rather than leaving it in a state where no user-facing service can start.

14.2.2 eventd #

peinit supervises eventd like anything else, and eventd is Critical. While it is down, peinit re-enables the pre-eventd buffer (§11.2) and keeps collecting output; when eventd returns the handoff repeats.

There is a log gap bounded by the buffer size. There is no event gap — audit events land in the KMES ring buffer regardless of eventd's state, and eventd resumes from the last persisted sequence. A submitter's output sink (§11.1) is fed regardless, since it is written from the pipe read rather than from the forwarder.

14.2.3 A bound dependency #

A service that BindsTo something is stopped when that something stops, with cause BindsToPropagation, and restarted when it returns, with cause BindsToRecovery and no charge against the restart budget (§7.1). This is the one dependency relationship that recovers by itself.

A Requires dependency crashing does not affect a running dependent at all. The dependent was ordered after it, not coupled to it.

14.2.4 A dependency that never becomes satisfying #

A dependent blocked on a hard dependency waits until its own operation lifetime expires, and then fails. The timeout is measured from when the operation was created rather than from when it started running, so a service queued behind a slow dependency can exhaust its StartTimeout without ever having attempted to start  — which is the honest answer, in that the caller really has been waiting that long.

14.3 Unkillable Processes

Peios / Reference / peinit / Failure Modes

A process in uninterruptible kernel sleep does not respond to SIGKILL. Nothing peinit can do will make it exit, and the design consequence is that peinit stops trying rather than blocking on it.

Detection is uniform: after sending the kill, arm a post-kill deadline (5 seconds by default) and check whether the cgroup still reports as populated when it fires.

For a service stop, the post-kill deadline belongs to that stop operation, including the stop leg of a Restart. When the main exits and the stop ends, the deadline is canceled. A retained obsolete deadline is ignored before probing or removing the cgroup: the same pathname can already belong to the next instance. A later stop that escalates to SIGKILL gets its own full PostKillTimeout; it cannot inherit the earlier instance's remaining grace. Re-recording a deadline for the same stop does not extend it.

What follows depends on which cgroup it was:

CgroupConsequence
main/The service goes to Abandoned with cause ProcessUnkillable. Supervision stops; the cgroup is leaked.
health/ or hooks/The sub-cgroup is orphaned and recorded as a leak. The service carries on normally.
checks/The sub-cgroup is recorded as a leak of type helper, as any other leaked sub-cgroup is (§5.7).

The distinction is about what the stuck process is holding. A main process holds the service's ports, locks and connections, so a service whose main process cannot be killed cannot be restarted into a working state. A health check or a hook holds nothing, so a stuck one is a nuisance rather than a blocker.

14.3.1 Abandoned #

peinit has given up. The service is not restarted, does not satisfy dependents, and every lifecycle command against it is invalid except reset (§10.3).

A reset re-checks main/. If it has finally emptied — the I/O that was hung completed, or the device came back — peinit cleans up the whole tree and the service returns to Inactive. If it is still populated, the service returns to Inactive anyway, the cgroup stays leaked, and both the acknowledgment and the console carry a warning saying so.

14.3.2 When the process finally dies #

Abandoning a service does not close its main job. The process is still there, so there is still something to reap, and peinit keeps the job open against the possibility that it eventually exits — which it often does, once the I/O it was blocked on completes.

That exit arrives for a service already in Abandoned, a state that has stopped expecting a process. peinit records it and does nothing else: no transition, no restart, no operation update. The service stays Abandoned, the stop stays failed , and the console reports the exit:

peinit: service <service> main process exited in state Abandoned; no action taken

The exit is news about the process, not a retroactive success for the stop that gave up on it. Recovering the service still takes a reset, which is also what cleans up the cgroup the process was holding.

The same handling covers a late exit in any state that does not expect a process — see §6.2.

14.3.3 The generational escape #

A leaked cgroup cannot be removed, so the next start would collide with it. Recording a leak increments the service's cgroup generation, and the next start builds a fresh tree at %gen<N> (§5.1). Old trees persist until reboot.

That is what lets a service recover from a leak at all: peinit cannot clean up the old tree, so it stops trying to and uses a new one.

14.3.4 What it actually means #

Every path here has the same underlying cause. Something below the service — a hung mount, a failing controller, a device that stopped answering — is not responding to the kernel, and no amount of restarting the service will change that. The leak record exists to say so, because the alternative is a service that mysteriously will not restart.

14.4 Resource Exhaustion

Peios / Reference / peinit / Failure Modes

peinit is single-threaded PID 1, so most resource pressure reaches it as a failure at a syscall rather than as slowness.

14.4.1 Descriptors #

peinit holds a descriptor per supervised process (a pidfd), two per supervised process for output pipes, one per armed timer, one per control connection, two per jobs connection (the socket and the peer's pidfd), one per submitted job's output sink, plus the sockets, the epoll instance and the signalfd. Control connections are bounded in all by MaxControlConnections (256), which is set for descriptors rather than for fairness: what keeps one caller from taking them is MaxControlConnectionsPerUser (§10.1). A submission also holds its prepared token and attached descriptors from acceptance until the launch takes them, which is bounded by MaxJobsPerSubmitter times the descriptor cap per message.

EMFILE or ENFILE from pipe2 or clone3 fails the start with ParentSetupFailure — a restart-eligible cause, so a service that failed because the system was momentarily out of descriptors gets another go.

The pre-start check helper's result descriptor and pidfd are both unregistered from the event loop and closed, so a service using filesystem conditions costs no descriptors beyond the start itself.

14.4.2 Processes #

EAGAIN from clone3 — the PID limit — is also ParentSetupFailure and restart-eligible.

The one path that forks outside the launch machinery is the timer last-run write, one child per firing of a persistent timer (§9.2). The children _exit as soon as the write returns and peinit matches each one's exit status back to its write, so a failure is reported rather than discarded — but the fork itself is real and happens on every firing.

The child closes inherited descriptors numbered 3 or above before opening the registry key, so a blocked write does not keep PID 1's pidfds, event-loop handles, sockets or service pipe ends open. It keeps the standard streams and exits when its write completes. Cleanup failure is reported like a failed timestamp write (§9.2). Driving the write through an asynchronous LCS path instead would remove the fork entirely; there is no such path today.

14.4.3 Memory #

ENOMEM from clone3 behaves like the others.

peinit's own memory is bounded by design in the places that could otherwise grow without limit: the pre-eventd buffer has a fixed size and drops its oldest, there is no outbound queue for log delivery, terminal jobs and operations are dropped rather than retained, and neither has a history structure.

Nor do the two structures that once did. A graph execution context and its operation associations are retired on the maintenance turn after every member reaches a terminal state (§7.3), so a boot or an on-demand start costs nothing lasting. And an OnFailure chain entry is cleared once its handler has held for a RestartWindow (§6.3), so a resident handler does not permanently occupy a slot of that failure's depth budget.

14.4.4 Disk #

A full root filesystem shows up in three places. The boot attempt counter cannot be written, which peinit treats as a counter of zero and continues — a failure to record an attempt is not itself worth escalating. The random seed cannot be saved at shutdown, which is recorded and does not block the shutdown.

And registryd cannot write, which is registryd's problem and reaches peinit as a Critical service failing.

14.4.5 The OOM killer #

An ErrorControl=Critical service is marked OOM-immune, with oom_score_adj at -1000; everything else is left at the default (§5.4). A Critical service is one whose loss reboots the machine, so letting the OOM killer pick it would turn memory pressure into a reboot.

peinit itself is PID 1 and the kernel will not choose it.

14.5 Power Loss and Corruption

Peios / Reference / peinit / Failure Modes

14.5.1 What peinit writes #

Three things, and all three are written to survive an unexpected loss of power:

WhatWhereHow
Boot attempt counter/.peinit/boot-attemptsA plain integer, rewritten each boot.
Local machine ID/lcl/etc/machine-idTemporary file, flush, rename.
Random seed/var/state/peinit/random-seedTemporary file on the same filesystem, flush, atomic rename, directory flush.

The seed and the machine ID are atomic in the sense that matters: a reader sees either the old value or the new one, never a partial write.

14.5.2 Reading a damaged file #

The three behave differently on finding something they cannot use, and the differences track how bad each situation is.

The counter is the strictest. Absent means zero. But unreadable, empty, non-decimal, carrying trailing data, or overflowing all send peinit to recovery mode. A counter that cannot be trusted cannot escalate, and the whole point of it is escalation — so failing to read it is treated as though it had already escalated.

The machine ID is regenerated. Absent, empty, all zeroes, the wrong length, not hexadecimal, or missing its trailing newline all produce a fresh identifier, recorded as a warning. It is an opaque install identifier, not a security principal, and a new one is a smaller problem than no boot. An unreadable file or an unwritable path is fail-soft too — the boot continues on an ephemeral identifier, recorded as a warning. Only a failure to generate one sends peinit to recovery, because at that point there is no identifier to continue with (§2.3).

The seed is entirely fail-soft. Absent, empty, oversized, or unrestorable all continue the boot. An empty or oversized seed is recorded as an error on the way past (§2.3); none of them stops the boot. A system with no entropy cache still boots; it starts with less entropy, which is the image builder's problem to solve with a hardware or virtio RNG.

14.5.3 The registry #

peinit does not write service state to the registry, apart from timer last-run timestamps. Everything else about a service's runtime state lives in memory and is rebuilt from the definitions on the next boot, which means a power loss cannot leave peinit's own state inconsistent — there is no state on disk to be inconsistent with.

Registry consistency across power loss is loregd's concern, and its recovery paths are what the recovery shell offers (§2.8).

14.5.4 Timers across a loss #

A persistent timer's last-run timestamp is written after the firing and after the start is initiated, not after the service completes (§9.3). A power loss mid-run therefore does not re-trigger on the next boot — the run was attempted, not missed.

A power loss between the firing and the write does re-trigger, which is the right way round: one extra run is better than a silently skipped one.

14.5.5 Shutdown that never finishes #

If power is lost during the graceful sequence, the effect depends on how far it got. Before step 7, the filesystems are still mounted read-write and the next boot behaves like any unclean shutdown. After step 7, the root has been remounted read-only and everything else unmounted, so there is nothing outstanding to lose.

The counter was incremented at the start of the boot that is now ending, and a successful boot resets it during that boot, once the success grace period has been held. So a power loss during the shutdown of a boot that succeeded leaves the counter at zero; one during the shutdown of a boot that never reached success leaves it advanced. Enough of those in a row reach the recovery threshold, which is the intended behavior: a machine that keeps failing to reach a successful boot is a machine an administrator should be looking at.

Appendix A Registry Key Reference

Peios / Reference / peinit

Every registry key peinit reads or writes. Semantics are in the sections referenced.

A.1 Service definitions #

KeyPurposeDefined in
Machine\System\Services\Parent key. Each child key is one service.§3.2
Machine\System\Services\SchemaVersionSchema version guard. REG_DWORD, 1. Created by peinit if absent.§2.3, §3.2
Machine\System\Services\ServiceSecurityThe descriptor inherited by definitions that carry none. REG_BINARY.§4.6
Machine\System\Services\<name>One service definition.§3.2
Machine\System\Services\<name>\ProvidesRoles this service fills, which dependencies can name in place of the service. REG_MULTI_SZ. Read at boot and on reload.§7.6
Machine\System\Services\<name>\LastTimerRunLast-run timestamp for a single-trigger persistent timer. REG_QWORD, written by peinit.§9.3
Machine\System\Services\<name>\TimerState\Per-trigger timestamps for a multi-trigger service. Each value is named by the percent-encoded schedule and holds a REG_QWORD.§9.3

A.2 Boot configuration #

KeyTypeDefaultPurposeDefined in
Machine\System\Boot\MaxParallelStartsdword, > 010Services starting concurrently during boot. Zero, a type mismatch, or a malformed payload is invalid and enters recovery.§2.5
Machine\System\Boot\BootSuccessGracedword30Seconds every Critical service has to hold a dependent-satisfying state before the boot counts as successful.§2.5
Machine\System\Boot\SettleTimeoutdword5Seconds to wait for the boot set to settle before starting boot:settled services regardless. Zero is legal.§2.5
Machine\System\Boot\ShutdownTimeoutdword90Seconds for the entire graceful shutdown.§12.2
Machine\System\Boot\PostKillTimeoutdword5Seconds for a cgroup to drain after SIGKILL before it is treated as stuck. Bounds one service's final stop, where ShutdownTimeout bounds the sequence.§12.2

A.3 Operational parameters #

KeyTypeDefaultPurposeDefined in
Machine\System\Init\ControlSecuritybinarySYSTEM and Administrators, every right; Authenticated Users, SYSTEM_QUERY_STATUSThe descriptor for system-level control operations and the boot query.§4.7
Machine\System\Init\MaxControlConnectionsPerUserdword16Concurrent control socket connections one caller's user SID can hold. SYSTEM is exempt.§10.1
Machine\System\Init\MaxControlConnectionsdword256Concurrent control socket connections in all.§10.1
Machine\System\Init\MaxRequestSizedword65536Maximum control request size, in bytes.§10.1
Machine\System\Init\ConnectionTimeoutdword30Seconds before an idle control connection is closed.§10.1
Machine\System\Init\MaxJobsConnectionsdword64Concurrent jobs socket connections.§10.7
Machine\System\Init\MaxJobMessageSizedword32768Maximum jobs socket message content, in bytes.§10.7
Machine\System\Init\JobsConnectionTimeoutdword30Seconds before an idle jobs connection is closed.§10.7
Machine\System\Init\MaxJobsPerSubmitterdword64Live submitted jobs one submitter SID can hold. SYSTEM is exempt.§8.5
Machine\System\Init\MaxLogLineLengthdword8192Bytes per output line before truncation. Minimum 256; below that the default is used and a warning logged.§11.3
Machine\System\Init\MaxLogBufferPerServicedword65536Pipe capacity per service, applied with F_SETPIPE_SZ. Minimum 4096 (one page, the kernel's own floor).§11.3
Machine\System\Init\LogReadBytesPerEventdword16384Bytes drained from one output pipe per readable event. Minimum 512.§11.3
Machine\System\Init\PreEventdBufferdword1048576Bytes of output retained before eventd is available. Applied at boot and on reload. Minimum 4096.§11.2
Machine\System\Init\EnvVars\parent keyemptyVariables injected into every service but registryd. Value name is the variable name; REG_SZ data is the value. Its descriptor is security-critical.§5.5
Machine\System\Init\ProvisionedPaths\parent keyemptyBoot-time path provisioning entries.§2.4
Machine\System\Init\ProvisionedPaths\<name>\Kindstring—directory or file. Required.§2.4
Machine\System\Init\ProvisionedPaths\<name>\Pathstring—The absolute path. Required.§2.4
Machine\System\Init\ProvisionedPaths\<name>\Securitybinarybuilt-inThe descriptor to apply.§2.4
Machine\System\Init\ProvisionedPaths\<name>\Requireddword0If 1, a failure enters recovery before Phase 2.§2.4

A.4 Other subsystems #

KeyTypePurposeDefined in
Machine\System\eventd\LogSocketPathstringWhere peinit forwards service output.§11.4

A.5 Watches #

peinit subscribes to Machine\System\Services\ and Machine\System\Init\ at boot. Any drained event triggers a full reload-config, which also covers the OVERFLOW case (§3.7).

Appendix B Constants and Paths

Peios / Reference / peinit

Values compiled into peinit, which no registry key changes.

B.1 Filesystem paths #

PathPurpose
/usr/bin/peinit2Where peinit is installed in package storage.
/bin/peinit2The runtime path the kernel init= names.
/sbin/registrydThe compiled-in registryd image path.
/var/state/loregd/Machine.hiveThe machine hive, passed to registryd.
/var/state/loregd/Users.hiveThe users hive, passed to registryd.
/.peinit/peinit's own state directory on the root filesystem.
/.peinit/boot-attemptsThe boot attempt counter.
/lcl/etc/machine-idThe local machine identifier.
/var/state/peinit/random-seedThe persisted entropy seed.
/lcl/policy/autorun.dPhase 1 autorun scripts.
/run/services/peinit/control.sockThe control socket.
/run/services/peinit/notify.sockThe notification socket, by default.
/run/services/peinit/jobs.sockThe jobs socket.
/sys/fs/cgroup/peinit/The root of every service cgroup tree.
/sys/fs/cgroup/peinit/jobs/<guid>A submitted job's cgroup.
/dev/rtc, /dev/rtc0The hardware clock, in that order of preference.
/dev/consoleWhere peinit writes its own messages.
/bin/recsh, /bin/shThe recovery shell, in that order of preference.

B.2 Timeouts and limits #

ConstantValueMeaning
registryd setup timeout30 sProcess setup, driven synchronously in Phase 1.
registryd readiness timeout30 sWaiting for READY=1 in Phase 1.
Reload detection window2 sWaiting for RELOADING=1 after a reload signal. Bounded above by the operation deadline.
Restart delay cap60 sThe ceiling on exponential backoff.
Timeout extension cap×4The multiple of a phase's base timeout an extension can reach.
Operation retention60 sHow long a terminal operation is kept before being dropped.
Submitted job retention60 sHow long a terminal submitted job's entry answers status before being dropped.
peinit.job.status.reported interval1 sThe least spacing between two peinit.job.status.reported events for one job.
Submitted job stop_timeout10 sThe default, per submission.
Submitted job readiness_timeout30 sThe default, per submission.
Submitted job argv and environment2 MiBThe bound on a definition's arguments and environment together.
Boot attempt threshold3The default, overridden by peios.bootattempts=.
OnFailure chain depth16The maximum handler chain from one originating failure.
Pre-eventd buffer1 MiBThe compiled-in buffer capacity.
Notification datagram64 KiBThe receive buffer size.
Descriptors per datagram64The control message buffer capacity.
Random seed512 bytesWritten at shutdown. Restoring accepts 1–4096 bytes.
Control listen backlog32
Jobs listen backlog32
Descriptors per jobs message64Including an output sink.
Tokens per jobs message1
First injected descriptor3Where stored descriptors are placed.
Final action retry1 sThe minimum interval between reboot(2) retries.

B.3 Environment #

VariableValue
PATH/sbin:/bin — the compiled-in base for every service.

The recovery shell additionally receives TERM=linux and HOME=/.

B.4 Kernel command line #

ParameterEffect
peios.safemode=1Force Safe mode.
peios.recovery=1Force recovery mode.
peios.bootattempts=NThe recovery threshold; 0 disables the check.
peios.quiet=NConsole verbosity: 0, 1, or 2.
peios.notifysocket=PATHOverride the notification socket path.

B.5 Descriptors peinit applies #

WhereSDDL
/dev/shm, /run, /sys/fs/cgroup after mountingO:SYG:SYD:(A;OICI;GA;;;SY)(A;OICI;GA;;;BA)(A;CI;GRGX;;;WD)(A;OICIIO;GA;;;S-1-3-0)
/dev/null, /dev/zero, /dev/full, /dev/random, /dev/urandom, /dev/tty, /dev/ptmx (DACL only)D:(A;;GA;;;SY)(A;;GA;;;BA)(A;;FRFW;;;WD)
A provisioned path with no SecurityO:SYG:SYD:(A;;GA;;;SY)(A;;GA;;;BA)(A;;FR;;;BU)
A service's /run/<name> runtime directoryO:SYG:SYD:(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;<service SID>)
The random seed fileO:SYG:SYD:(A;;GA;;;SY)
The default ServiceSecurityO:SYG:BAD:(A;;0x000F;;;SY)(A;;0x000F;;;BA)(A;;0x0001;;;AU)
The default ControlSecurityO:SYG:BAD:(A;;0x0007;;;SY)(A;;0x0007;;;BA)(A;;0x0004;;;AU)
The control socket inodeO:SYG:SYD:(A;;GA;;;SY)(A;;GA;;;BA)(A;;FW;;;AU)
The jobs socket inodeO:SYG:SYD:(A;;GA;;;SY)(A;;GA;;;BA)(A;;FW;;;AU)
A submitted job with no security_descriptorOwner and group the submitter; (A;;0x0007;;;<submitter>)(A;;0x0007;;;SY)(A;;0x0007;;;BA)

B.6 Access rights #

RightBit
SERVICE_QUERY_STATUS0x0001
SERVICE_START0x0002
SERVICE_STOP0x0004
SERVICE_INTERROGATE0x0008
SERVICE_ALL_ACCESS0x000F
SYSTEM_SHUTDOWN0x0001
SYSTEM_RELOAD_CONFIG0x0002
SYSTEM_QUERY_STATUS0x0004
JOB_QUERY0x0001
JOB_STOP0x0002
JOB_SIGNAL0x0004
JOB_ALL_ACCESS0x0007

B.7 Identifiers #

Every GUID peinit generates — jobs, operations — is UUIDv7, so identifiers sort by creation time.

1.1 Overview

Peios / Reference / loregd / Introduction

loregd; the Local Registry Daemon; is the primary registry source for Peios. It holds one or more registry hives in SQLite databases and serves them to the kernel's registry subsystem over the Registry Source Interface (RSI).

loregd is not architecturally special. Any process that implements the RSI contract can serve as a registry source, and the kernel is source-agnostic: it does not know or care that the process answering for a hive keeps its data in SQLite.

What makes loregd special is operational. It is the source that provides the Machine\ and Users\ hives at boot, which puts it on the critical path to a running system; if loregd does not come up, very little else does.

The dev.peios.loregd package contains the daemon and man page under /usr and provides the registryd role. loregd creates missing state and runtime directories with their security descriptors at startup (§2.2); no package installation step creates /var/state/loregd.

peinit owns the compiled-in Phase-1 service definition, so loregd does not ship a second service seed that could compete with it.

1.1.1 Where loregd sits #

The registry is split across a trust boundary. The kernel side owns the namespace, the layer model, access checks, watches, and transactions; it holds no storage of its own. The source side owns bytes on disk and answers questions about them. loregd is a source, and everything in this manual describes the lower half of that split.

Three consequences run through the whole design:

  • loregd stores; it does not decide. It never resolves layers, never filters results by visibility, and never applies the stored registry security descriptor. It returns every layer entry it holds and lets the kernel work out which one wins. The security descriptors in its tables are opaque payload to it.
  • Key creation requests carry kernel-assigned GUIDs. loregd records each GUID as the primary key. On first boot, loregd generates the root GUID for an empty hive before registering that hive.
  • Sequence numbers come from the kernel. loregd stores them and reports the maximum it holds at registration, but never allocates one.

1.1.2 What this manual covers #

The command line and startup sequence; the SQLite schema backing a hive and the tmpfs-backed store backing volatile keys; the connection model, write serialization, and how requests are dispatched; and the handling of each RSI operation, including transactions and enumeration ordering.

The kernel registry manual describes namespaces, layers, watches, and access control. The kernel source interface describes the other end of the RSI connection. Key schemas belong to their owning subsystems; service supervision belongs to peinit.

1.1.3 Compatibility and scope #

This manual describes loregd 0.21.13 and SQLite schema version 1. The daemon requires the kernel RSI lifetime extension version 1 before registering any hive. It does not fall back to an earlier lifetime protocol.

The daemon registers global hives only. A transaction binds to one hive; layer deletion visits each registered hive independently. The daemon does not import Windows REGF files or migrate an older SQLite schema.

1.2 Terminology

Peios / Reference / loregd / Introduction

The registry's own vocabulary; hive, key, value, layer, source, watch, security descriptor, sequence number; is defined by the kernel-side registry documentation and is used here unchanged.

The terms below are specific to loregd.

Hive database. The SQLite database file backing one hive. Each hive registered by loregd has its own file, whose path is given on the command line (§2.1). Referred to in SQL as the main schema.

Volatile database. The tmpfs-backed SQLite WAL database for one hive's volatile keys, attached as volatile. It mirrors the persistent tables, starts empty, and is never reused across daemon instances (§3.3).

Folded name. The case-folded form of a key name, value name, or child name, stored in a _folded column beside the canonical case-preserving name and used for all case-insensitive comparison (§3.4).

Write connection. The single SQLite connection per hive through which every mutation passes. Its uniqueness is what serializes writes (§4.1).

Read pool. The fixed set of connections serving reads that are not part of a transaction, selected round-robin (§4.1).

Snapshot connection. A dedicated connection opened for one read-only transaction, pinning a point-in-time view of the hive database for that transaction's lifetime (§4.3).

Orphan. A key record that no path entry in any layer points at. Orphans are cleaned up at startup (§2.2) and are reported by RSI_DELETE_LAYER as the keys its deletion left unreachable (§5.6).

2.1 Command Line

Peios / Reference / loregd / Startup

loregd is configured entirely by its argument vector. It takes one or more hive declarations, each naming a hive and the SQLite database file that backs it:

loregd <hive-name>=<database-path> [<hive-name>=<database-path> ...]

The placeholders name a hive and its absolute database path. peinit selects Machine=/var/state/loregd/Machine.hive and Users=/var/state/loregd/Users.hive for its registry service. The daemon has no built-in database-path defaults.

Each argument is split at its first =, so a database path can itself contain =.

Every declared hive is registered with the kernel at startup (§2.2).

2.1.1 Argument validation #

loregd rejects the invocation and exits with status 1 if any of the following hold:

ConditionReason
No hive arguments at allAt least one hive is required.
An argument with no =Not a hive declaration.
An empty hive name or empty pathNeither is meaningful.
A relative database pathPaths are required to be absolute.
A hive name containing \, /, or NULThese are path separators and terminators in the registry namespace.
The hive name CurrentUser, in any caseReserved by the kernel as a per-token alias; no source can claim it.
Two declarations of the same hive nameDuplicates are detected on the folded name, so Machine and MACHINE collide.

Hive-name comparison is case-insensitive throughout; for duplicate detection here, and for routing requests later; but the case as written on the command line is preserved and is what loregd presents to the kernel when it registers.

2.1.2 Unsupported recovery switches #

The argument parser accepts hive declarations only. It has no help, version, inspection, restore, or clearing switches. In particular, --inspector, --recover-from-backup, and --dangerously-clear-database fail validation because they lack =.

Startup backup and repair limits describes the distinction between WAL recovery and a saved backup.

2.1.3 Configuration #

loregd has no configuration file and reads no configuration from the registry. This is deliberate: loregd is the configuration store, and a store that had to read its own configuration to start could not start.

Everything about how it behaves comes from three places: the command-line arguments above, the contents of the SQLite databases they name, and compiled-in constants (§4.1).

NOTIFY_SOCKET is the one environment variable loregd consults, and it carries no behavioral setting. When it is set, loregd treats it as a service-manager readiness socket: once the hives are registered and the request loop is about to begin, it connects and sends READY=1\n. Connection and write share a one-second deadline. Failure produces a warning and startup continues. When it is unset, the step is skipped.

loregd writes ordinary progress to standard output and faults to standard error. peinit captures both streams during Phase 1: if loregd fails before readiness, peinit relays the captured diagnostic output to the console; after the log service starts, the pre-eventd buffer carries both streams into eventd. This keeps early-boot failures visible without bypassing the system log.

2.2 Startup Sequence

Peios / Reference / loregd / Startup

Startup runs to completion before loregd accepts a single request. Database preparation, device negotiation, and registration failures are fatal: loregd logs the error and exits with status 1. Readiness notification is best effort; a failure is logged and serving continues.

2.2.1 1. parse and validate arguments #

loregd extracts the hive-to-database mapping and validates it as described in §2.1. Before opening a hive, it ensures /run/loregd exists, verifies tmpfs, and takes the runtime lock. Missing directories are created with the descriptor below in the creation call; no later restamping is needed. It removes old volatile stores only after taking that lock.

2.2.2 2. open each hive database #

For each declared hive, create missing database parent directories before opening SQLite. This includes /var/state/loregd on a standard first boot. loregd creates each missing ancestor, /run/loregd, and each fresh volatile store directory with the same explicit descriptor in the native creation call:

O:SYG:SYD:P(A;OICI;GA;;;SY)(A;OICI;GA;;;BA)

SYSTEM owns the directory. Its protected DACL grants full control only to SYSTEM and Administrators, inherited by files and directories. Native creation failure aborts startup; there is no POSIX-only fallback in the daemon.

Existing directories keep their ownership, descriptor, and mode. A path that exists but is not a directory, including a symbolic link, fails with an error naming the path. If another creator wins a race, loregd checks the resulting type and leaves an existing directory unchanged.

ppk packages contain only /usr. loregd needs its storage before it can serve the registry, so it prepares these directories itself; registry-backed path provisioning runs too late for this Phase 1 service.

Four pieces of connection state are established immediately:

  • PRAGMA journal_mode=wal. The result is read back and checked; if the database does not report wal, the open fails. WAL mode is what allows concurrent readers alongside a writer (§4.1), so silently running without it is not acceptable.
  • PRAGMA foreign_keys=ON. Neither schema declares a foreign key, so this constrains nothing.
  • PRAGMA busy_timeout=0; SQL lock conflicts return busy immediately (§4.4).
  • The volatile database is attached (§3.3).

Each database/sql handle is limited to a single underlying connection.

2.2.3 3. attach the volatile store #

Each hive gets a fresh tmpfs-backed SQLite database, attached as volatile and put in WAL mode with private caches. Before opening hives, loregd ensures and locks /run/loregd, verifies tmpfs, and removes old volatile stores left by a crash (§3.3). It never reuses a prior process's volatile data.

2.2.4 4. establish the schema #

If the database has no schema_version table, it is new: loregd creates the persistent tables, creates the volatile tables, and stamps the schema version, in one transaction.

If the version is present, it is compared against the version loregd supports. A newer version aborts startup, and so does an older one (§3.1).

2.2.5 5. first-boot root key #

For each hive, look for a key with no parent. If none exists, this is the hive's first boot: loregd generates a random 16-byte GUID for the root key, builds the default hive-root security descriptor, and inserts the root key record.

The default root descriptor grants SYSTEM and Administrators full access to the key, grants Authenticated Users read access, marks all three as container-inheritable, and sets both owner and group to SYSTEM.

2.2.6 6. crash recovery #

SQLite's own WAL recovery handles any transaction that was uncommitted when the process died; it happens when the database is opened and needs nothing from loregd.

What loregd does on top of that is clean up orphaned keys; key records that no path entry in any layer points at. These can survive a crash between a key's creation and the creation of the path entry naming it. In one transaction, loregd deletes the values belonging to orphaned keys, then their blanket tombstones, then the key records themselves.

The hive root is exempt: it legitimately has no parent and no path entry pointing at it, so orphan detection skips keys whose parent_guid is null.

2.2.7 7. compute the maximum sequence number #

For each hive, take the maximum sequence across the path entries, values, and blanket tombstones; in both the persistent and the volatile tables; then take the maximum across all hives. That single global figure is what loregd reports at registration, so the kernel can resume allocating sequence numbers above everything already stored.

In practice the volatile tables are empty at this point in startup and contribute nothing.

2.2.8 8. open the registry device #

Open /dev/pkm_registry. The kernel requires SeTcbPrivilege in the calling thread's token to permit this; loregd performs no check of its own and relies on the kernel to refuse.

Before registration, negotiate RSI lifetime extension version 1 with REG_SRC_NEGOTIATE. Retain the returned source-session identifier for request contexts and lease renewal. A kernel without this extension is incompatible; startup fails before registering hives instead of silently changing lifetime semantics.

2.2.9 9. register the hives #

Issue REG_SRC_REGISTER with every hive name, its root key GUID, and the global maximum sequence number from step 7.

The registration flags are zero: loregd registers global hives only and never private ones.

2.2.10 10. signal readiness and serve #

loregd sends readiness to NOTIFY_SOCKET if it is set (§2.1). The complete notification attempt has a one-second deadline. A failed attempt produces a warning, not a startup failure. The daemon installs its termination signal watcher (§2.3) and enters the request loop (§4.2).

2.2.11 Backup and repair limits #

loregd creates no automatic startup backup. Opening a hive prepares its schema, root, orphan cleanup, and reader pool. Orphan cleanup deletes unreferenced persistent records; it does not restore a backup or repair arbitrary database corruption.

WAL recovery and RSI_FLUSH checkpointing create no separate recovery copy. Read-only RSI transactions provide snapshots for higher-level backup operations, but do not save those snapshots themselves. The kernel backup interface is a separate operation.

The command-line interface provides no offline repair command. Database recovery requires a separately verified backup and a procedure appropriate to that backup format.

2.3 Exit and Shutdown

Peios / Reference / loregd / Startup

The daemon distinguishes process failures from errors returned for individual requests.

2.3.1 What ends the process #

loregd exits when any of the following happens:

  • The kernel closes the registry device. Reading from /dev/pkm_registry returns end-of-file, the request loop returns, and loregd shuts down cleanly with status 0. This is the normal path when the registry subsystem goes away.
  • A termination signal arrives. SIGTERM and SIGINT are trapped. The handler closes the device, which unblocks the read loop and produces the same clean shutdown as above. This is how the service manager stops loregd.
  • A request cannot be framed. If a message read from the device cannot be parsed as an RSI request, loregd treats it as unrecoverable and exits non-zero.
  • Startup preparation fails. Database, device, negotiation, or registration failures in §2.2 exit with status 1. Readiness warnings do not stop the daemon.

On shutdown, the signal watcher stops and joins after serving ends. In-flight requests are drained before the process exits (§4.2), then outstanding transactions are rolled back, every connection is closed, and the per-hive volatile directories are removed before the runtime lock is released.

2.3.2 What does not end the process #

A storage failure during request handling does not terminate loregd. Errors from SQLite while serving a request; including I/O errors; are converted into a status response. Lock contention and unbound request deadline failures produce RSI_TXN_BUSY; other storage failures produce RSI_STORAGE_ERROR and the daemon carries on serving. There is no corruption detector and no disk-full detector that takes the process down; a database that has become unreadable will produce a stream of storage errors rather than an exit.

A running, registered daemon can therefore return errors for every operation on a damaged hive. Process liveness alone does not establish registry health.

2.3.3 What happens to the data #

Persistent data is durable at the point each transaction commits; SQLite finalizes any outstanding WAL state as the connections close.

Volatile data is never recovered after process exit. Clean shutdown removes the tmpfs stores; startup removes crash residue and creates new stores before registering the hives (§3.3).

When the kernel observes the source disconnect, it marks every hive loregd served as unavailable.

3.1 Schema Version

Peios / Reference / loregd / Storage

Every hive database carries a schema version in a single-row table :

CREATE TABLE schema_version (
    version INTEGER NOT NULL
);

The supported schema version is 1.

loregd checks the version as it opens each database (§2.2, step 4) and takes one of three paths:

Statebehavior
No schema_version tableThe database is new. loregd creates the persistent tables, the volatile tables, and inserts version 1, all in one transaction.
Version equals 1Normal startup.
Version greater than 1Startup fails. The database was written by a newer loregd, and proceeding risks corrupting it by writing through an older understanding of its layout.
Version less than 1Startup fails.

There are no migrations. loregd carries no migration table, no migration step list, and no upgrade path; an older database is reported as requiring migration and startup stops there. The version check does not convert existing data to another layout.

The schema_version table has no primary key, uniqueness constraint, or check constraint, so a second row is not detected: the first row read wins.

And because every table is created with IF NOT EXISTS, a database holding the data tables but no schema_version table is stamped as version 1 without any validation that its contents match that layout.

3.2 Persistent Tables

Peios / Reference / loregd / Storage

Each hive is one SQLite database, and every hive database has the same four data tables. loregd creates them on first boot (§2.2, step 4).

The tables hold what the kernel gives loregd and nothing derived from it. Security descriptors are stored as opaque blobs, GUIDs in creation requests and sequence numbers are assigned by the kernel, and no table records a resolved or filtered view of anything.

3.2.1 keys #

CREATE TABLE keys (
    guid           BLOB NOT NULL PRIMARY KEY,
    name           TEXT NOT NULL,
    name_folded    TEXT NOT NULL,
    parent_guid    BLOB,
    sd             BLOB NOT NULL,
    volatile       INTEGER NOT NULL DEFAULT 0,
    symlink        INTEGER NOT NULL DEFAULT 0,
    last_write_time INTEGER NOT NULL
);
ColumnMeaning
guidThe 16-byte primary key. The kernel supplies it in creation requests; loregd generates the first-boot root GUID.
nameThe key's own name component, with case preserved as written.
name_foldedThe folded form of name (§3.4), used for case-insensitive lookup.
parent_guidThe parent key's GUID; null for the hive root, which is how the root is identified.
sdThe security descriptor, in binary self-relative form. Opaque to loregd.
volatile1 for a volatile key, 0 for a persistent one. In this table it is always 0; volatile keys live in the volatile database (§3.3).
symlink1 if the key is a symbolic link.
last_write_timeUnix nanoseconds.

3.2.2 path_entries #

CREATE TABLE path_entries (
    parent_guid       BLOB NOT NULL,
    child_name        TEXT NOT NULL,
    child_name_folded TEXT NOT NULL,
    layer             TEXT NOT NULL,
    target_type       INTEGER NOT NULL,
    target_guid       BLOB,
    sequence          INTEGER NOT NULL,
    PRIMARY KEY (parent_guid, child_name_folded, layer)
);

CREATE INDEX idx_path_entries_target
    ON path_entries (target_guid)
    WHERE target_type = 0;

A path entry is one layer's opinion about one child name under one parent. Several layers can hold entries for the same name; resolving between them is the kernel's job, not loregd's.

ColumnMeaning
parent_guidThe parent key's GUID.
child_nameThe child name with case preserved.
child_name_foldedThe folded form, which is what the primary key uses; so a name collides case-insensitively within a layer.
layerThe layer name. Compared as binary, so layer names are case-sensitive, unlike key names.
target_type0 for a GUID entry (the key exists in this layer), 1 for HIDDEN (a tombstone masking lower layers).
target_guidThe target key's GUID when target_type is 0; null for HIDDEN.
sequenceThe kernel-assigned sequence number.

The partial index on target_guid covers only non-HIDDEN rows. It is what makes the reverse lookup; which path entries point at this key; cheap, and that reverse lookup is what orphan detection (§2.2, step 6) and RSI_DROP_KEY need.

3.2.3 values #

CREATE TABLE [values] (
    key_guid       BLOB NOT NULL,
    name           TEXT NOT NULL,
    name_folded    TEXT NOT NULL,
    layer          TEXT NOT NULL,
    type           INTEGER NOT NULL,
    data           BLOB,
    sequence       INTEGER NOT NULL,
    PRIMARY KEY (key_guid, name_folded, layer)
);
ColumnMeaning
key_guidThe key this value belongs to.
nameThe value name, case preserved. The empty string is the key's default value.
name_foldedThe folded form; also the empty string for the default value.
layerThe layer this value entry belongs to.
typeThe registry value type; REG_SZ is 1, REG_DWORD is 4, and so on. REG_TOMBSTONE (0xFFFF) marks a per-value tombstone.
dataThe value payload; null for a tombstone.
sequenceThe kernel-assigned sequence number.

values is a reserved word in SQL, so every reference to this table is quoted; [values], or main.[values] and volatile.[values] when the schema is named explicitly. Unquoted, it is a syntax error.

3.2.4 blanket_tombstones #

CREATE TABLE blanket_tombstones (
    key_guid       BLOB NOT NULL,
    layer          TEXT NOT NULL,
    sequence       INTEGER NOT NULL,
    PRIMARY KEY (key_guid, layer)
);

A blanket tombstone hides every value a key holds in the layers beneath it, rather than naming one value the way a REG_TOMBSTONE entry does. One row per key per layer.

3.3 The Volatile Store

Peios / Reference / loregd / Storage

Volatile keys never reach the persistent hive file. Each hive attaches a separate SQLite database as volatile, using WAL and private connection caches. Its files live on tmpfs beneath /run/loregd/hive-<random>/.

New runtime directories have a protected, inheritable KACS DACL granting full control to SYSTEM and Administrators, with SYSTEM ownership. The descriptor is supplied in the creation call, including for each per-hive directory. Existing directories retain their policy (§2.2). Startup verifies that /run/loregd is on tmpfs and refuses symlinks. A stable .lock file prevents two daemon instances from cleaning up each other's stores.

3.3.1 A mirror of the persistent schema #

The volatile database carries the same four tables as the persistent one keys, path_entries, [values], and blanket_tombstones; with identical columns, identical primary keys, and the same partial idx_path_entries_target index on non-HIDDEN path entries. Column meanings are exactly those in §3.2.

There is one deliberate difference. In volatile.keys the volatile column defaults to 1 rather than 0, and loregd writes 1 into it. Every record in this database is volatile by definition, and the column carries that fact back out in responses without a second lookup.

Because the two schemas are structurally identical, a query that needs both stores is a UNION ALL across them rather than two queries merged in application code:

SELECT 1 FROM main.keys WHERE guid = ?
UNION ALL
SELECT 1 FROM volatile.keys WHERE guid = ?
LIMIT 1

3.3.2 Why this shape matters #

A SQLite transaction spans the attached schemas. A per-hive publication gate prevents concurrent readers from observing a commit halfway through publishing the two stores. Rollback discards changes to both stores. SQLite WAL does not provide crash-atomic commits across attached files. After a crash, persistent WAL recovery and volatile-store disposal have different lifetimes (§4.3).

Volatile writes inside a transaction are invisible to other readers until commit and disappear on rollback for the same reason persistent ones do see §4.3.

3.3.3 Lifetime #

Every open hive gets a fresh random directory. Read, write, and snapshot connections attach the same database file for that hive. Different hive instances never share a store merely because their names match.

Clean shutdown closes the connections and removes the hive directories. After a crash, files can remain in tmpfs until the next start or reboot. The next daemon acquires the runtime lock and removes that residue before creating fresh stores; it never reads or recovers old volatile data. The .lock file remains; its kernel lock ends when the process exits. Every volatile table is empty on startup, including a restart within the same boot.

3.3.4 Which store an operation uses #

For an operation naming a single key, the key's own storage decides: loregd looks the GUID up in main.keys and volatile.keys, and whichever holds it determines where the reads and writes go.

RSI_CREATE_KEY is the exception, because the key does not exist yet the volatile flag in the request decides which database receives it.

Two operations are not scoped to one store at all. RSI_LOOKUP and RSI_ENUM_CHILDREN consult both and combine the results, because a persistent parent can legitimately have volatile children. The reverse does not arise: a persistent child beneath a volatile parent is forbidden by the kernel's data model, so a volatile key's whole subtree is volatile.

3.4 Case Folding

Peios / Reference / loregd / Storage

Key names and value names are case-insensitive but case-preserving. loregd implements this by storing both forms: the name as written, and a folded form alongside it in a _folded column.

The folded form is computed once, when the name is written, and it is the folded column that appears in every WHERE clause and every primary key. Lookups are therefore plain binary comparisons :

SELECT * FROM path_entries
WHERE parent_guid = ? AND child_name_folded = ?

This is why no custom SQLite collation is registered anywhere in loregd the case-insensitivity has already happened by the time SQLite sees the query.

The canonical name is what comes back in responses, so callers see the case they originally supplied while storage compares the folded form.

Hive names are folded too, though not stored : routing a request to a hive and rejecting duplicate hive declarations (§2.1) both compare folded names.

Layer names are not folded. They are compared as binary, so layer names are case-sensitive.

3.4.1 How the folded form is computed #

The folded form is Unicode Simple Case Folding: each codepoint is replaced by its status C or S mapping from CaseFolding.txt, Unicode 16.0.0, or left alone when it has none. This is the rule used for case-insensitive LCS names. loregd and the kernel use byte-identical folded forms because a name the two fold differently is a key that exists for one side and not the other.

Identity is guaranteed by construction rather than by care. loregd does not derive the fold from the Go standard library, whose case tables implement lowercasing (a different operation) at a different Unicode version. Its table is generated by the kernel's own generator, peios/generate-casefold-table.py in the kernel repository, from the same CaseFolding.txt that produces the kernel's table; the generated Go file records the source version and checksum, and the lookup mirrors the kernel's binary search over the same ranges and pairs. A Unicode version bump regenerates both outputs together.

3.4.2 Compatibility with older folded columns #

Simple folding differs from lowercasing. For example, Greek final sigma ς folds to σ; Cherokee folds toward uppercase. A database populated by the lowercasing implementation used before September 2026 can contain folded columns that differ from Unicode 16.0.0 simple folding.

Schema version 1 does not distinguish those tables and startup does not recompute existing folded columns. A successful version check therefore does not establish that a database uses the same folding rules.

4.1 Connections

Peios / Reference / loregd / Concurrency

Each hive holds a small, fixed set of SQLite connections, and which one an operation runs on decides both its isolation and what it can block on.

ConnectionCountUsed for
WriteOne per hiveEvery mutating operation, and every read inside a bound read-write transaction.
Read poolmin(NumCPU, 16), at least 1Reads outside a transaction. Selected round-robin.
SnapshotOne per active read-only transactionReads inside a read-only transaction. Created on demand, closed when the transaction ends.

The pool size is compiled in and cannot be configured; loregd reads no configuration (§2.1).

4.1.1 One connection per handle #

Each Go database/sql handle has one physical connection. The write handle is reserved by a bound read-write transaction. Other mutations return busy rather than waiting for that reservation; per-hive gates coordinate admission and publication (§4.4).

It also means the snapshot connections are separate handles rather than borrowed pool entries, which is what keeps a long-running read-only transaction from consuming a pool slot.

4.1.2 What every connection carries #

Connection state is established on every physical connection, including one that replaces a connection discarded after cancellation:

  • journal_mode=wal on both databases, verified after being set.
  • foreign_keys=ON.
  • busy_timeout=0; SQL lock conflicts return busy immediately (§4.4).
  • The hive's tmpfs database attached as volatile (§3.3).

Both stores have private-cache WAL readers. The volatile tables are created on the write connection; other connections attach the same file. A read-only transaction pins a snapshot of both stores before a commit can publish.

4.1.3 Which connection an operation uses #

Nine mutating operations are routed to the write connection through the transaction-aware write path: RSI_CREATE_KEY, RSI_WRITE_KEY, RSI_DROP_KEY, RSI_CREATE_ENTRY, RSI_HIDE_ENTRY, RSI_DELETE_ENTRY, RSI_SET_VALUE, RSI_DELETE_VALUE_ENTRY, and RSI_SET_BLANKET_TOMBSTONE.

Four read operations are routed to the read pool, or to the transaction's connection when one is bound: RSI_LOOKUP, RSI_ENUM_CHILDREN, RSI_READ_KEY, and RSI_QUERY_VALUES.

RSI_DELETE_LAYER and RSI_FLUSH take the hive's write connection directly rather than through the transaction-aware path. Layer deletion opens a transaction per hive; flush issues a WAL checkpoint. Neither can join a caller's transaction: RSI_FLUSH checkpoints a hive, and RSI_DELETE_LAYER spans every registered hive while a transaction binds to exactly one.

They do still consult the request's transaction id, for the two answers that do not require joining. A read-only transaction is declined with RSI_INVALID, as it is on every other mutating path.

And because each hive allows a single write connection, RSI_DELETE_LAYER declines with RSI_TXN_BUSY while any transaction holds a pinned write connection rather than blocking on it forever; the same answer RSI_FLUSH gives for its own hive.

4.2 Request Dispatch

Peios / Reference / loregd / Concurrency

RSI requests arrive multiplexed on the /dev/pkm_registry file descriptor. Each carries a request id and a transaction id in its header.

loregd reads messages into a 16 MiB buffer and copies each complete frame. RSI_BEGIN_TRANSACTION is dispatched inline so later requests cannot overtake registration of the transaction ID. Other requests run in separate goroutines; the daemon imposes no independent concurrency cap.

Responses are serialized by a mutex, because one write to the device corresponds to exactly one response.

On shutdown the in-flight goroutines are drained before the process exits.

4.2.1 Identifying the target hive #

Most operations name a key GUID (or, for lookups and enumerations, a parent GUID), and loregd determines which hive owns it.

A guidCache maps GUID to hive. It is seeded at startup with every hive's root GUID, and maintained as keys come and go:

  • RSI_CREATE_KEY stores the new GUID immediately, before the transaction that created it commits, and registers an abort hook to evict it if that transaction rolls back. This makes the key immediately routable within the transaction. Cache misses also consult an existing transaction binding so a snapshot does not lose access to keys deleted after its first read.
  • RSI_DROP_KEY evicts immediately outside a transaction, or through a commit hook inside one.

  • RSI_DELETE_LAYER evicts the GUIDs its deletion orphaned.

On a miss, loregd probes each hive in turn:

SELECT 1 FROM main.keys WHERE guid = ?
UNION ALL
SELECT 1 FROM volatile.keys WHERE guid = ?
LIMIT 1

Only hits are cached, so a GUID that exists nowhere is re-probed against every hive on every request that names it. The cache has no size bound; it shrinks only through the three eviction paths above.

A GUID that resolves to no hive produces RSI_NOT_FOUND for most operations. RSI_DROP_KEY and the entry deletions treat it differently; see §5.3 and §5.4.

4.2.2 Operations that resolve differently #

RSI_FLUSH carries a hive name rather than a GUID and resolves it by folded name (§3.4), so the match is case-insensitive.

RSI_DELETE_LAYER does not resolve a hive at all: it applies to every registered hive and concatenates the orphan sets (§5.6).

4.3 Transactions

Peios / Reference / loregd / Concurrency

Transaction identifiers are allocated by the kernel and carried on every request.

loregd binds them to connections lazily; RSI_BEGIN_TRANSACTION does no SQLite work at all.

4.3.1 Beginning #

RSI_BEGIN_TRANSACTION carries the transaction id and a mode: RSI_TXN_READ_WRITE (0) or RSI_TXN_READ_ONLY (1). loregd records the id as pending in the requested mode and returns RSI_OK immediately. No connection is taken and no SQLite transaction is opened.

loregd supports both modes; its SQLite backing provides atomic read-write commits and stable read-only snapshots; so it never returns RSI_TXN_NOT_SUPPORTED.

Re-using a transaction id that is already active returns RSI_INVALID. A missing or truncated mode field, or a mode other than 0 or 1, returns RSI_INVALID without recording a transaction. The id remains available for a subsequent well-formed request. The decoder accepts a complete u64 ID and u32 mode. A request carrying only the ID is rejected rather than interpreted as read-write.

4.3.2 Read-write transactions #

The transaction binds to a hive on its first mutating operation: loregd identifies the hive from the operation's GUID, acquires that hive's write connection, issues BEGIN IMMEDIATE, and records the binding. If SQLite reports SQLITE_BUSY at that point, the operation returns RSI_TXN_BUSY.

Once bound, every subsequent operation with that transaction id; reads included; runs on the same connection.

That is what provides read-your-own-writes: uncommitted rows are visible to the transaction because it is the connection that wrote them. Reads issued before the transaction binds go to the read pool instead, since there is nothing uncommitted to see.

One SQLite transaction spans both databases. A per-hive publication gate excludes readers while a commit publishes, so readers cannot observe one store before the commit and the other after it. Non-transactional mutations use the same gate for their whole operation. The gate is released between transaction requests, allowing ordinary readers to see committed data while a write transaction remains open.

SQLite WAL does not provide crash-atomic commit across attached database files. After a crash, the persistent hive is recovered by SQLite and the volatile store is discarded, never replayed (§3.3).

An operation whose GUID belongs to a different hive than the transaction is bound to is rejected with RSI_STORAGE_ERROR. The kernel enforces hive-scoping before requests reach loregd, so this is a backstop.

4.3.3 Read-only transactions #

A read-only transaction binds on its first read. loregd identifies the hive, opens a dedicated connection; deliberately not one from the read pool, so a long-lived snapshot cannot starve ordinary reads; and issues BEGIN DEFERRED.

WAL fixes the snapshot at that first read, and every later read with the same transaction id reuses the connection and observes the same point in time.

Before the first request proceeds, loregd reads both schemas while holding the hive gate, pinning both WAL snapshots at the same published state. Later reads, including the first access to a volatile key, retain that state. The snapshot does not block volatile writes.

A mutating operation carrying a read-only transaction id is rejected with RSI_INVALID before any state changes.

The nine operations that route through the write path get this from the routing itself; RSI_DELETE_LAYER and RSI_FLUSH cannot route that way and ask directly, for the same answer (§4.1).

4.3.4 Committing and aborting #

RSI_COMMIT_TRANSACTION issues COMMIT on the bound connection and returns RSI_OK. If the commit fails, the transaction is left open so the caller can retry or abort: a busy or locked failure returns RSI_TXN_BUSY, anything else RSI_STORAGE_ERROR. Committing an unknown transaction id returns RSI_STORAGE_ERROR.

Committing a read-only transaction releases the snapshot and returns RSI_OK.

RSI_ABORT_TRANSACTION issues ROLLBACK, closes the connection, releases any snapshot, runs the transaction's abort hooks, and returns RSI_OK for an admitted, decoded abort, including an unknown ID. A malformed or expired request can fail before cleanup is dispatched. A connection with an uncertain rollback is discarded rather than returned to the pool. This is how the kernel releases a read-only snapshot after a REG_IOC_BACKUP finishes or fails.

LCS sends aborts when a client transaction expires or its last handle closes. loregd also rolls back every remaining transaction during shutdown. A renewable cleanup lease also reclaims state when an abort is lost. Its authority comes from the live kernel owner, for both read-write transactions and read-only snapshots; it is not an inactivity timeout (§4.4).

If a request interrupts a bound SQLite transaction, loregd marks that ID failed. Reads, writes, and commits on it return a storage error until LCS aborts it; it is never silently rebound. This handles SQLite's possible automatic rollback after interruption.

4.4 Waiting and Contention

Peios / Reference / loregd / Concurrency

Request deadlines bound admission and statement waits; kernel ownership governs transaction cleanup.

4.4.1 Request deadlines #

Each RSI operation uses the absolute CLOCK_MONOTONIC deadline supplied by LCS through REG_SRC_REQUEST_CONTEXT. The budget includes kernel admission, queue time, connection-pool waits, publication-gate waits, and SQL statements; receiving the request does not restart it. A contended wait that expires returns RSI_TXN_BUSY; successful operations retain their success status. SQLite's busy timeout is zero because its native busy wait can outlast a canceled Go context. Busy classification uses SQLite and Go error codes.

The lifetime extension is negotiated before hive registration. loregd requires version 1 and fails startup on a kernel without it. The 25-second local budget is only a fallback for direct, unnegotiated test clients.

4.4.2 A transaction holding the writer #

A competing mutation returns RSI_TXN_BUSY immediately while a read-write transaction owns the hive's write connection. This includes non-transactional key drops, conditional value writes, flushes, and layer deletion. Admission and binding are coordinated under the hive gate, so the check cannot race a new binding. A read-only snapshot is not counted as a writer.

Both stores use WAL with private caches. Ordinary reads see committed data while a writer remains open; backup snapshots do not hold volatile table locks that block writers. A short per-hive gate excludes reads from commit publication and non-transactional mutations, not from an entire transaction's lifetime. Different hives have separate gates.

4.4.3 Cancellation and cleanup #

Operations on the same transaction are serialized, including commit and abort. Rollback uses a fresh cleanup context, and an uncertain connection is discarded rather than returned to the pool with a live transaction. Every replacement physical connection receives its WAL, foreign-key and volatile-attachment setup again.

SQLite can automatically roll back an interrupted write. Such a bound transaction is marked failed and subsequent use returns a storage error; LCS aborts it. It is never silently rebound or allowed to autocommit.

LCS owns transaction lifetime. A live transaction file object (including all duplicated handles) or an in-kernel operation owns the shared kernel transaction record. A source can renew its five-second cleanup lease only while that owner and source session remain valid. SQL activity neither creates ownership nor extends a transaction's lifetime deadline. An internal operation can have no separate lifetime limit; its live operation scope is still required.

A separate control loop renews leases with three seconds or less remaining, checks expiration every 100 milliseconds, and reclaims expired transactions. Control ioctls consume no ordinary RSI request slots. Final owner release, abort, timeout, or a lost source session prevents renewal even if an abort message cannot be delivered. Expired transactions reject new operations; late renewals cannot revive them. Cleanup serializes on the transaction's operation gate and waits for an already-admitted commit to resolve. A request timeout is not evidence that a commit failed. The request deadline gates commit admission; once admitted, SQL COMMIT runs without caller cancellation and its actual result is reported, including through normal late-response recovery. Shutdown drains requests and cleanup before closing databases.

5.1 Store Routing

Peios / Reference / loregd / Request Handling

Persistent data lives in the hive database's main schema; volatile data lives in the attached volatile schema (§3.3). Most operations act on one of the two, and loregd has to decide which before it can run any SQL.

5.1.1 Operations naming one key #

For a write that names an existing key, the schema containing the key row selects the store. loregd first probes main.keys by GUID, then probes volatile.keys only if the first query found no row. A database error is returned as a storage error, not treated as absence. If an externally modified database contains the GUID in both stores, the existing main-first lookup precedence applies; normal key creation rejects such duplicates.

A GUID present in neither produces RSI_NOT_FOUND for most operations.

Routing follows the source table, including when the stored volatile column contradicts it. A row in main.keys carrying volatile = 1 still routes writes to main; a row in volatile.keys carrying 0 still routes writes to volatile. An inconsistent flag does not redirect writes to the other store. Rows loregd creates carry the consistent flag for their store. This routing rule does not repair external metadata changes: read-key and lookup metadata continue to report the stored column value.

RSI_CREATE_KEY cannot consult a key that does not exist yet, so it routes on the volatile flag carried in the request instead.

RSI_CREATE_ENTRY routes to the store containing the child key the entry points at. When that child GUID is present in neither store, the entry is written to the persistent table.

RSI_HIDE_ENTRY routes on the parent key, since a HIDDEN entry belongs to the parent's child list and a volatile parent's whole subtree is volatile.

5.1.2 Operations spanning both stores #

RSI_LOOKUP, RSI_ENUM_CHILDREN, RSI_READ_KEY, and RSI_QUERY_VALUES are not scoped to one store: a persistent parent can have volatile children, and a persistent key can have volatile-store rows beneath it. Each issues a single UNION ALL statement over the two schemas rather than querying them separately, so the merge happens inside SQLite.

Nothing de-duplicates across the two stores. The primary keys that make (parent_guid, child_name_folded, layer) unique apply per schema, so if the same triple exists in both, both rows appear in the response. The same holds for value entries keyed on (key_guid, name_folded, layer).

The deletions; RSI_DELETE_ENTRY, RSI_DELETE_VALUE_ENTRY, and RSI_DROP_KEY; do not route at all. They delete from both schemas unconditionally.

5.2 Response Ordering

Peios / Reference / loregd / Request Handling

The queries backing enumerations and lookups carry no ORDER BY, and a UNION ALL across the two stores yields rows in whatever order SQLite produces them. That order is not stable across calls.

The kernel walks enumeration results by dense index across repeated calls, so an unstable order would make that walk duplicate or drop entries. loregd therefore sorts every affected array into a canonical order before encoding a response:

ResponseSorted by
RSI_LOOKUP path entrieslayer, then sequence
RSI_ENUM_CHILDREN childrenfolded child name
RSI_ENUM_CHILDREN per-child entrieslayer, then sequence
RSI_QUERY_VALUES value entriesfolded value name, then layer, then sequence
RSI_QUERY_VALUES blanket tombstonesfolded layer name, then sequence
RSI_DELETE_LAYER orphan GUIDsascending GUID, compared bytewise
Key-metadata blocks, in any responseascending GUID, compared bytewise

This ordering is a wire-stability guarantee only. It has no bearing on layer resolution, which is order-independent; the kernel selects a maximum, not a first match.

5.2.1 Arrays assembled outside one query #

Two of those arrays are not a single query's result set. They are assembled first and sorted afterward:

  • The blanket-tombstone array in an RSI_QUERY_VALUES response comes from its own UNION ALL, separate from the value entries it travels beside, and takes the same order they do.
  • The orphan-GUID array in an RSI_DELETE_LAYER response is the concatenation of every registered hive's orphan set. That walk ranges a Go map, whose iteration order is randomized, so the array is sorted bytewise before it is encoded.

5.2.2 Child display names #

RSI_ENUM_CHILDREN groups rows by child_name_folded and emits one child block per folded name, carrying a display name taken from the child_name column.

Where two rows share a folded name but differ in stored case; Foo in one store and FOO in the other, say; the display name emitted is the lower of the two bytewise, which is a property of the set rather than of the order the union produced. Both the order of children and the case of the name reported for each are therefore stable across calls.

5.3 Key Operations

Peios / Reference / loregd / Request Handling

Four RSI operations create, read, update, and remove key records.

5.3.1 RSI_CREATE_KEY #

The request's volatile flag selects the target table (§5.1). For a persistent key:

INSERT INTO keys
    (guid, name, name_folded, parent_guid, sd, volatile, symlink,
     last_write_time)
VALUES (?, ?, ?, ?, ?, 0, ?, ?)

last_write_time is not carried in the request. loregd sets it to the current wall-clock time in Unix nanoseconds at insertion.

Uniqueness comes from the target table's primary key on guid, surfaced as RSI_ALREADY_EXISTS. That key binds one schema, so loregd also asks the other store whether it holds the GUID before inserting, and answers RSI_ALREADY_EXISTS if it does. Without that check a GUID could come to exist in both stores, where metadata reads would resolve it to the main row; the reading query takes the first row of a UNION ALL that puts main first; leaving the volatile row unreachable while it still occupied its GUID.

The new GUID is added to the hive cache immediately, before the enclosing transaction commits, with an abort hook to remove it if that transaction rolls back (§4.2).

An unresolvable parent GUID returns RSI_NOT_FOUND, after a fallback check of the registered hives' root GUIDs.

5.3.2 RSI_READ_KEY #

SELECT name, parent_guid, sd, volatile, symlink, last_write_time
FROM main.keys WHERE guid = ?
UNION ALL
SELECT name, parent_guid, sd, volatile, symlink, last_write_time
FROM volatile.keys WHERE guid = ?
LIMIT 1

RSI_NOT_FOUND if the GUID is in neither store, and likewise if it resolves to no hive. The volatile field in the response is the stored column value.

5.3.3 RSI_WRITE_KEY #

Updates the two mutable fields of a key, selected by a field mask:

BitValueField
00x01sd
10x02last_write_time

Valid masks are therefore 0x00, 0x01, 0x02, and 0x03. Any other bit set returns RSI_INVALID; it indicates an attempt to modify an immutable field.

loregd builds one UPDATE from the mask, setting only the named fields:

-- mask 0x03
UPDATE keys SET sd = ?, last_write_time = ? WHERE guid = ?

A mask of 0x00 names no fields and acts as an existence check, returning RSI_OK or RSI_NOT_FOUND. An update that matches no row also returns RSI_NOT_FOUND.

Outside a transaction the update is a single auto-committed statement. Inside one it runs on the transaction's connection.

5.3.4 RSI_DROP_KEY #

Purges every trace of a GUID from both stores; four tables in each schema:

DELETE FROM keys               WHERE guid = ?;
DELETE FROM path_entries       WHERE target_guid = ?;
DELETE FROM [values]           WHERE key_guid = ?;
DELETE FROM blanket_tombstones WHERE key_guid = ?;

Outside a transaction, the eight statements are wrapped in a BEGIN IMMEDIATE transaction of their own so the purge is atomic. Inside one, they run on the transaction's connection.

Dropping a GUID that does not exist returns RSI_OK; so does one that resolves to no hive. The operation is idempotent. The GUID is evicted from the hive cache (§4.2).

The daemon folds names before binding SQL parameters. The examples show parameterized SQL; no SQLite fold function is registered.

5.4 Path Entry Operations

Peios / Reference / loregd / Request Handling

Path entry operations store layer-specific names, targets, and hiding markers.

5.4.1 RSI_LOOKUP #

Returns every layer's entry for one child name under one parent, together with metadata for the keys those entries point at.

SELECT layer, target_type, target_guid, sequence
FROM main.path_entries
WHERE parent_guid = ? AND child_name_folded = ?
UNION ALL
SELECT layer, target_type, target_guid, sequence
FROM volatile.path_entries
WHERE parent_guid = ? AND child_name_folded = ?

HIDDEN entries are returned as entries but contribute no metadata GUID. For each distinct non-HIDDEN target_guid, loregd fetches the key's metadata; one query per GUID; and emits the blocks in ascending GUID order (§5.2).

loregd does no layer filtering and no resolution: every entry it holds is returned, and choosing between them is the kernel's job.

An unresolvable parent GUID returns RSI_NOT_FOUND.

If a path entry names a target_guid for which no key record exists, loregd drops that entry from the response and returns RSI_OK, so the child reads as absent. This is reachable in ordinary operation: the kernel issues RSI_CREATE_ENTRY before RSI_CREATE_KEY, so a lookup landing between the two sees an entry whose key has not yet been written, and failing the request would make a routine race fatal to the caller.

5.4.2 RSI_CREATE_ENTRY #

INSERT INTO path_entries
    (parent_guid, child_name, child_name_folded, layer,
     target_type, target_guid, sequence)
VALUES (?, ?, ?, ?, 0, ?, ?)

The target table follows the store containing the child key (§5.1). A child GUID in neither store lands in the persistent table.

RSI_ALREADY_EXISTS comes from the target table's primary key on (parent_guid, child_name_folded, layer). That key binds one schema, so loregd also asks the other store for the same triple before inserting, and answers RSI_ALREADY_EXISTS if it finds one. Nothing de-duplicates on read, so a triple in both stores would put two entries claiming the same name in the same layer inside one child block (§5.1).

An unresolvable parent GUID returns RSI_NOT_FOUND.

5.4.3 RSI_HIDE_ENTRY #

Writes a tombstone that masks the same name in lower layers:

INSERT OR REPLACE INTO path_entries
    (parent_guid, child_name, child_name_folded, layer,
     target_type, target_guid, sequence)
VALUES (?, ?, ?, ?, 1, NULL, ?)

target_type is 1 and target_guid is null. The target table follows the store containing the parent key, because a volatile parent's entire subtree is volatile. A parent GUID in neither store returns RSI_NOT_FOUND.

Hiding an entry replaces the same parent, folded child name, and layer in both stores. loregd removes an opposite-store entry before writing the HIDDEN marker to the parent's store. A nontransactional request wraps both steps in a local SQLite transaction; a caller transaction can commit or abort both steps together. This prevents a visible target and its hiding marker from appearing together for the same name and layer.

5.4.4 RSI_DELETE_ENTRY #

Removes one layer's entry for one name, from both stores:

DELETE FROM path_entries
WHERE parent_guid = ? AND child_name_folded = ? AND layer = ?

No rows-affected check is made, so deleting an entry that is not there succeeds. A parent GUID that resolves to no hive returns RSI_NOT_FOUND rather than succeeding.

5.4.5 RSI_ENUM_CHILDREN #

Returns every layer's entry for every child under a parent:

SELECT child_name, child_name_folded, layer, target_type,
       target_guid, sequence
FROM main.path_entries WHERE parent_guid = ?
UNION ALL
SELECT child_name, child_name_folded, layer, target_type,
       target_guid, sequence
FROM volatile.path_entries WHERE parent_guid = ?

Rows are grouped by folded child name into one block per child, each carrying that child's per-layer entries. Metadata for the distinct non-HIDDEN target GUIDs is fetched and emitted exactly as for RSI_LOOKUP, including its treatment of an entry whose key record does not yet exist: the entry is dropped, and a child left holding no entries at all is dropped with it, so the child reads as absent rather than failing the enumeration. The metadata block for a dropped entry is omitted with it the kernel rejects a GUID-typed entry carrying no metadata, and equally a metadata block no entry references.

Ordering, and the treatment of two rows whose folded names match but whose stored case differs, are covered in §5.2.

The daemon folds names before binding SQL parameters. The examples show parameterized SQL; no SQLite fold function is registered.

5.5 Value Operations

Peios / Reference / loregd / Request Handling

Value operations preserve every layer entry and its kernel-assigned sequence.

5.5.1 RSI_QUERY_VALUES #

Returns every layer's entry for one value, or for all of a key's values when the request sets the query-all flag:

-- single value
SELECT name, layer, type, data, sequence
FROM main.[values] WHERE key_guid = ? AND name_folded = ?
UNION ALL
SELECT name, layer, type, data, sequence
FROM volatile.[values] WHERE key_guid = ? AND name_folded = ?;

-- query all
SELECT name, layer, type, data, sequence
FROM main.[values] WHERE key_guid = ?
UNION ALL
SELECT name, layer, type, data, sequence
FROM volatile.[values] WHERE key_guid = ?

The response also carries the key's blanket-tombstone state:

SELECT layer, sequence
FROM main.blanket_tombstones WHERE key_guid = ?
UNION ALL
SELECT layer, sequence
FROM volatile.blanket_tombstones WHERE key_guid = ?

Value entries and blanket tombstones are both sorted (§5.2).

An unresolvable GUID returns RSI_NOT_FOUND. An existing key with no values returns RSI_OK with empty arrays.

5.5.2 RSI_SET_VALUE #

The store containing the key selects the target table (§5.1). A key GUID in neither store returns RSI_NOT_FOUND.

INSERT OR REPLACE INTO [values]
    (key_guid, name, name_folded, layer, type, data, sequence)
VALUES (?, ?, ?, ?, ?, ?, ?)

5.5.2.1 Conditional writes #

When the request carries a non-zero expected_sequence, the write is a compare-and-swap. loregd reads the current entry's sequence and writes only if it matches:

SELECT sequence FROM [values]
WHERE key_guid = ? AND name_folded = ? AND layer = ?

If the row is absent, or its sequence differs, the operation returns RSI_CAS_FAILED and writes nothing.

Outside a transaction, the check and the write are wrapped in their own BEGIN IMMEDIATE transaction so no other writer can interleave. If that transaction cannot begin because the database is busy, the operation returns RSI_TXN_BUSY.

Inside a transaction, the caller's transaction already provides the isolation.

5.5.3 RSI_DELETE_VALUE_ENTRY #

Removes one layer's entry for one value, from both stores:

DELETE FROM [values]
WHERE key_guid = ? AND name_folded = ? AND layer = ?

No rows-affected check, so deleting an absent entry succeeds. A GUID that resolves to no hive returns RSI_NOT_FOUND.

5.5.4 RSI_SET_BLANKET_TOMBSTONE #

Sets or clears the tombstone that masks every value a key holds in lower layers. The store containing the key selects the target table (§5.1). A GUID in neither returns RSI_NOT_FOUND.

-- set
INSERT OR REPLACE INTO blanket_tombstones (key_guid, layer, sequence)
VALUES (?, ?, ?);

-- clear
DELETE FROM blanket_tombstones WHERE key_guid = ? AND layer = ?

The daemon folds names before binding SQL parameters. The examples show parameterized SQL; no SQLite fold function is registered.

5.6 Layer and Maintenance Operations

Peios / Reference / loregd / Request Handling

Both operations in this section consult the request's transaction id before doing anything; a read-only transaction cannot mutate, and an unknown id is refused (§4.3); but neither can join one. Both use the hive's write connection directly. Layer deletion opens a transaction per hive; flush issues a WAL checkpoint. A bound read-write transaction makes either operation decline rather than wait (§4.1).

5.6.1 RSI_DELETE_LAYER #

Removes every entry belonging to one layer and reports the keys that the removal left unreferenced.

The operation is applied to every registered hive, not to one identified from the request, and the per-hive orphan sets are concatenated into a single response array.

For each hive, inside one BEGIN IMMEDIATE transaction, loregd first computes the orphan set and then deletes:

-- GUIDs referenced by the layer being removed
SELECT DISTINCT target_guid FROM main.path_entries
WHERE layer = ? AND target_type = 0
UNION
SELECT DISTINCT target_guid FROM volatile.path_entries
WHERE layer = ? AND target_type = 0

minus the GUIDs referenced by any other layer, gathered the same way with layer != ?. What remains is reachable only through the layer being deleted, and is therefore orphaned by it.

The deletion statements run against each schema:

DELETE FROM path_entries       WHERE layer = ?;
DELETE FROM [values]           WHERE layer = ?;
DELETE FROM blanket_tombstones WHERE layer = ?;

Both schemas are covered, and all six deletions run inside the same transaction as the orphan computation, so nothing can be inserted between the two steps. The orphaned GUIDs are evicted from the hive cache (§4.2) and returned to the caller.

The response array is sorted into ascending byte order (§5.2).

A contended write is reported as RSI_TXN_BUSY, the same distinction every other write path draws: the operation declines if any transaction already holds a hive's write connection, and again if a hive's own BEGIN IMMEDIATE finds the database busy. Other failures are RSI_STORAGE_ERROR.

5.6.2 RSI_FLUSH #

Checkpoints the hive's main write-ahead log and requests truncation after all frames are checkpointed:

PRAGMA wal_checkpoint(TRUNCATE)

The request carries a hive name rather than a GUID. It is matched case-insensitively against the registered hives by folded name (§3.4). A name matching none returns RSI_INVALID.

Two conditions return RSI_TXN_BUSY instead of checkpointing:

  • A read-write transaction is bound to the hive. A checkpoint on a connection already held by a transaction would deadlock, so loregd declines immediately rather than waiting (§4.4).
  • The checkpoint itself reports that it could not complete because the database was busy.

The volatile store has no durability and is unaffected: nothing is flushed, and nothing needs to be.

5.6.3 Partial layer deletion #

Layer deletion commits separately for each hive. If a later hive fails, changes committed to earlier hives remain committed. The response reports the failure rather than a complete orphan list. The order of the hive walk is not stable because it ranges over a Go map. This operation does not provide a transaction spanning all hives.

5.7 Status Codes

Peios / Reference / loregd / Request Handling

loregd returns seven of the RSI status codes:

StatusValueReturned when
RSI_OK0The operation succeeded. Also returned by the idempotent deletions when their target was already absent.
RSI_NOT_FOUND1A named key GUID exists in neither store, or resolves to no registered hive. Also an update matching no row.
RSI_ALREADY_EXISTS2A duplicate key GUID or path entry: the target table's primary key, or the matching check against the other store (§5.3, §5.4). No value operation produces it; every value write is an INSERT OR REPLACE.
RSI_STORAGE_ERROR3A SQLite failure while serving the request. Also an operation whose GUID belongs to a hive other than the one its transaction is bound to, a mutating operation carrying an unknown transaction id, and a failed commit that was not busy.
RSI_TXN_BUSY6BEGIN IMMEDIATE found the database busy, a conditional write could not begin its transaction, or RSI_FLUSH or RSI_DELETE_LAYER found a transaction already bound to a hive's write connection.
RSI_INVALID7An unknown opcode, a request whose payload cannot be decoded, an out-of-range RSI_WRITE_KEY field mask, a mutating operation carrying a read-only transaction id, an RSI_FLUSH naming an unregistered hive, or an RSI_BEGIN_TRANSACTION re-using an active id or naming a mode other than RSI_TXN_READ_WRITE or RSI_TXN_READ_ONLY.
RSI_CAS_FAILED8A conditional RSI_SET_VALUE whose target was absent or whose sequence did not match.

Three codes are defined by the interface and never produced by loregd: RSI_NOT_EMPTY (4), RSI_TOO_LARGE (5), and RSI_TXN_NOT_SUPPORTED (9).

RSI_TXN_NOT_SUPPORTED is never needed because loregd supports both transaction modes (§4.3).

RSI_TOO_LARGE is never returned because an oversized or malformed frame is not answered at all. Framing is validated before an opcode is known, and a frame that fails validation ends the connection instead of producing a response (§2.3).

Appendix A Prior Art

Peios / Reference / loregd

loregd combines SQLite storage with the Peios registry source protocol.

A.1 SQLite #

loregd's storage engine is SQLite, and it is specified against SQLite rather than against an abstract store. The schema, the concurrency model, and the operational behavior all name SQLite features directly: WAL mode for concurrent readers alongside a serialized writer, transactions for atomicity, PRAGMA wal_checkpoint for durability on demand, and its crash recovery for restart after an unclean shutdown.

Both halves of a hive are SQLite. Persistent data lives in the database file named on the command line; volatile data lives in a second, tmpfs-backed WAL database attached to the same connections (§3.3). Using one engine for both allows a transaction to cover both schemas. Per-hive publication gates coordinate readers with commits. Attached WAL databases do not provide crash-atomic commit across files (§4.3).

A different storage engine would have to supply equivalent transactional and concurrency semantics. Nothing in the design forbids that, but nothing accommodates it either.

A.2 The Windows registry hive format #

The Windows registry stores hives as binary REGF files managed directly by the kernel's Configuration Manager. loregd departs from that model completely: storage is a SQLite database managed by a SYSTEM userspace daemon with SeTcbPrivilege, not a kernel-managed binary file, and the kernel holds no storage of its own at all.

What the two share is the data model; keys, values, security descriptors which Peios inherits through the registry's kernel-side specification rather than from the file format. The on-disk format has no relationship to REGF whatsoever, and no REGF file can be read by loregd or written by it.

A.3 The registry source interface #

loregd implements the RSI. The kernel source interface describes the kernel side; the RSI specification defines the shared wire contract. The request-handling chapter maps those operations onto SQL against the two stores.

The protocol specification owns the contract. This manual describes the implementation and its limitations; it does not replace the protocol or turn implementation details into requirements for other sources.

1.1 Overview

Peios / Reference / eventd / Introduction

eventd is the observability daemon: the single persistent sink for everything a Peios system records about itself. Events, logs and metrics all end in eventd, and every query for any of them is answered by it.

It is one of the platform daemons the service manager starts at boot, configured as Critical. Production deployment requires signing at the trusted computing base (TCB) level; a development build alone does not establish that signing qualification.

The three data types are different and eventd treats them differently at every layer.

Events are structured, typed records carrying identity stamps the kernel applied and an emitter could not influence. They arrive through KMES, in per-CPU shared-memory ring buffers, and eventd is their primary consumer. They are the audit and security telemetry, and losing one is a real failure — so the event path is the one with sequence numbers, gap detection, per-transaction durability, and an eventd.events.lost record written for detected sequence loss when storage is writable.

Logs are text: a line a program wrote, with light metadata attached. They arrive on a datagram socket, mostly from the service manager forwarding what it read from a service's standard output and standard error. The ingestion path is best effort and does not provide the event store's receipt accounting.

Metrics are numeric measurements over time — dense series rather than discrete occurrences. They arrive on a second datagram socket, pushed by whatever is doing the measuring. eventd is a sink, not a collector: it scrapes nothing and polls nothing.

1.1.1 The shape of the daemon #

Three ingestion paths, three storage engines, one query surface.

The event path runs one drain thread per CPU, each attached to one ring buffer, handing events over a bounded channel to a writer thread that batches them into a SQLite shard. Shards are independent — separate files, separate write-ahead logs, and separate writer threads — so shards can make independent write progress (§2.3).

The log and metric paths each run a single thread that reads datagrams and writes them to one database each. They do not share the event writers' SQLite connections.

Underneath all three sits a decision that shapes the event pipeline entirely: the KMES ring buffers are the only buffer. eventd holds no large intermediate queue. Events move from the ring buffer through a small bounded handoff straight into a transaction, and when the writer falls behind, backpressure propagates backward until the ring buffer absorbs it — and when the ring buffer cannot, the loss is detected and recorded rather than hidden (§2.5).

Adaptive indexing watches which fields event queries filter on and maintains indexes for them, shedding those indexes under write pressure because ingestion throughput outranks query latency (§3.4). Repeated wide metric-window queries can seed bounded adaptive rollups, but eventd proves each cached result current against raw samples and never maintains it on the ingestion path (§5.6).

Everything eventd holds is readable only through access checks that KACS performs, per event type, per log origin, per metric name, and per field within a record (§7).

1.1.2 What eventd is not #

It is not a log framework. eventd stores lines; it does not parse them, does not understand severity beyond a single error flag, and does not care whether the text happens to be JSON.

It does not collect other services' measurements. eventd does not scrape endpoints or poll services for metrics. It reads /proc for its boot identifier and records its own health (§5.7). External producers measure and push their own samples.

It is not a tracing system. Distributed tracing is out of scope entirely.

It exposes committed history. A consumer that needs direct event transport can attach to kernel mediated event subsystem (KMES) rings. eventd adds storage and query authorization; records become queryable after their batch commits. That delay depends on the workload and storage.

It is not the only KMES consumer, and holds no privileged position among them.

1.2 What This Manual Is

Peios / Reference / eventd / Introduction

This manual describes the eventd implementation in this repository. It covers ingestion, storage, queries, authorization, and failure handling. The source code is authoritative when the description and implementation disagree.

1.2.1 Interface boundaries #

The Peios userspace protocols specification (PSPU), section 3, defines log ingestion, metric ingestion, and the query protocol. The Peios kernel protocols specification (PSPK) defines the kernel event transport. This manual explains how eventd implements its side of those interfaces. It does not replace their contracts.

Command options belong to eventd(8) and evctl(1). Registry values belong to the Machine\System\eventd regman records. Synthetic event payloads belong to the eventd evman catalog. The appendices summarize implementation choices and point to those references.

1.2.2 Reading the implementation #

The workspace separates four responsibilities:

CrateResponsibility
eventd-coreBounded queues, routing, receipts, and SQLite stores
eventdKernel attachment, ingestion, policy, lifecycle, and queries
eventd-clientQuery wire format, client state, and shared access constants
evctlCommand-line input, output formatting, and result publication

The source paths in the repository's documentation source map identify the implementation areas used to review this manual. Tests establish specific properties; passing host tests does not qualify kernel integration, privilege provisioning, power-loss behavior, or deployment performance.

1.2.3 Numbering and evidence #

Chapter numbers and named statement anchors remain stable so that code, tests, and other manuals can cite them. An anchor identifies a statement; it is not itself evidence that a runtime test passed.

The manual describes mechanisms and limits without promising a particular throughput or latency. Those results depend on the kernel, storage, hardware, configuration, and workload.

1.3 Terminology

Peios / Reference / eventd / Introduction

Terms defined elsewhere are used with the same meaning and are not redefined here: event, header, payload, stamp, ring buffer, consumer, origin class, and sequence number from the KMES chapters of the Peios Kernel TRM and PSPK; token, GUID, SID, Security Descriptor, ACL, ACE, and privilege from the Peios Kernel TRM and PCDS; registry, hive, key, value, and layer from the Peios Kernel TRM; producer, client, log record, metric sample, time series, and concrete identifier from PSPU §3.2.

Syscall numbers and signatures for the kernel interfaces eventd calls — kmes_attach, the SOL_KACS peer-token option, kacs_access_check and kacs_access_check_list — are in the Peios Kernel TRM's generated ABI appendices, §2.A and §3.A. This manual names them and does not repeat their numbers.

The following are specific to eventd.

Drain thread: one of the threads that reads from a per-CPU KMES ring buffer. There is exactly one per CPU (§2.2).

Writer thread: the sole writer to one event shard. There is exactly one per shard, and no other thread writes to that database (§2.3).

Shard: one of the independent SQLite databases the event store is split across, each with its own file, write-ahead log and writer thread. A shard is a write-path construct only; the query path treats the whole directory as one store (§2.3).

Active shard: a shard in the current configuration's numbering. Historical shard: a shard database left behind by a previous configuration. It takes no new events and is still queried, through read-only connections; its one writer is the retention coordinator (§3.3, §3.6).

Handoff channel: the bounded queue between drain threads and a writer thread. It is a small startup-fixed scheduling handoff, bounded by slots and bytes independently of transaction batch size (§2.3).

Synthetic event: a record eventd generates itself and writes directly to a shard, bypassing KMES. Synthetic events carry no identity stamps and no sequence numbers, and are distinguished by their type, one of exactly five eventd reserves: eventd.daemon.started, eventd.daemon.stopped, eventd.events.lost, eventd.store.quarantined, and eventd.config.changed (§2.6).

Gap record: the eventd.events.lost synthetic event recording that events were lost on one CPU, and which sequence numbers went missing (§2.5).

Event store directory: the directory holding every shard database and the metadata database. Metadata database: eventd-meta.db, the one database that is not a shard and survives shard reconfiguration (§3.5).

Desired index set: the global, priority-ordered list of fields eventd aims to have indexed across all shards.

Material indexes: the indexes a given shard actually has, which converge toward the desired set when the shard is quiet and diverge from it under pressure (§3.4).

Shedding: dropping secondary indexes to protect write throughput (§3.4).

Rollup: a disposable, pre-computed metric-window result whose freshness is proved against authoritative raw samples before reuse (§5.6).

Series cache: the bounded in-memory map from series identity to series row, which keeps metric ingestion off SQLite in the common case (§5.3).

Logical live size: (page_count - freelist_count) × page_size for a SQLite database — the space actually holding data, excluding pages freed by deletion and available for reuse. Retention is enforced against this rather than against the file size (§3.6).

Quarantine: renaming a database SQLite has reported corrupt, aside from the path eventd uses, and creating an empty one in its place (§3.3).

1.4 Component Boundaries

Peios / Reference / eventd / Introduction

eventd owns persistence and authorized queries for events, logs, and metrics. Event production, kernel transport, and service supervision remain separate responsibilities. These boundaries determine where a failure must be investigated.

The responsibilities are divided as follows:

ConcernOwner
Event emission and ring-buffer transportKernel mediated event subsystem (KMES)
Event type names and payload meaningsThe emitting component
Token and access-check primitivesKernel access control subsystem (KACS)
Registry storage and accessLayered configuration subsystem (LCS) and loregd
Service lifecycle and output forwardingpeinit
Persistent stores and query executioneventd
Shared userspace wire interfacesPeios userspace protocols specification (PSPU)

1.4.1 Storage boundary #

eventd uses SQLite databases for its stores. Clients use the query socket rather than opening those files. Opening a store directly bypasses eventd's record and field authorization.

The database schemas describe eventd's implementation. They are not an application interface or a substitute for the query protocol.

1.4.2 Delivery boundary #

Event receipts account for committed event sequences. Log and metric sockets provide best-effort ingestion and do not acknowledge persistence to the sender. A successful send therefore does not establish that a record reached durable storage.

Kernel rings are finite and do not survive reboot. Stored history is bounded by retention and available storage. Neither boundary provides an unlimited audit archive.

2.1 The Pipeline

Peios / Reference / eventd / Event Ingestion

eventd is the primary consumer of the KMES ring buffers. Events travel from shared memory to a committed database row in four stages.

  1. Drain. One thread per CPU reads events from that CPU's ring buffer, following the lock-free read protocol PSPK specifies (§2.2).
  2. Detect. The drain thread compares each event's sequence number against the last it saw for that CPU. A jump means events were lost, and the loss becomes a gap record (§2.5).
  3. Hand off. The drain thread copies the event out of the mapped region and passes it to the writer thread that owns the shard it routes to (§2.3).
  4. Write. The writer thread accumulates events into a transaction and commits, sizing the batch to whatever throughput allows (§2.4).

Two principles govern the whole pipeline, and most of its behavior follows from them rather than from anything specific to a stage.

2.1.1 The ring buffers are the only buffer #

eventd holds no large intermediate queue between KMES and SQLite. The handoff channel has startup-fixed slot and byte bounds chosen by performance testing, independently of the writer's transaction batch size, and nothing else accumulates (§2.3).

When the writer falls behind, the channel fills; when the channel is full, the drain thread stops reading; when the drain thread stops reading, events accumulate in the ring buffer, which is exactly what a ring buffer is for. Backpressure propagates all the way back to the kernel, and the absorption capacity is the ring buffer's, which an administrator already sizes.

If the ring buffer also fills, KMES overwrites its oldest events, the drain thread notices the sequence jump when it resumes, and the loss is recorded (§2.5). That is the designed worst case: eventd loses events visibly rather than buffering without bound and dying.

The alternative — a large in-process queue — would move the same capacity into a place where losing it is invisible, where it competes with the page cache for memory, and where an out-of-memory kill takes the whole queue with no record that it existed.

2.1.2 Independent shard writes #

Each shard is a self-contained SQLite database with its own file, its own write-ahead log and its own writer thread. Each shard commits its rows and receipts independently (§2.3). The writers share a commit notification for queries, but no cross-shard transaction coordinator.

The consequence for the query path is that a shard means nothing to it. A shard database holds whatever CPUs happened to route to it in whatever eventd lifetime wrote it, so a query filtering by CPU reads every shard, and the query path never assumes a relationship between a shard and a CPU (§6.4).

2.2 KMES Consumption

Peios / Reference / eventd / Event Ingestion

2.2.1 Attachment #

At startup eventd calls kmes_attach(KMES_ATTACH_QUERY_SLOTS, …) to obtain the logical CPU slot count. It then walks every slot from zero to one below that count. A successful call returns one descriptor for that logical CPU's ring buffer; EINVAL means the slot is a hole and eventd continues rather than treating it as the end of enumeration. Each successful descriptor is mapped at the size derived from the returned capacity, exactly as PSPK §2.3 defines.

The attached logical CPU IDs can therefore be sparse. eventd assigns the successful attachments dense internal ordinals in ascending logical CPU-ID order for shard routing (§2.3), while preserving the logical cpu_id everywhere externally visible: event rows, receipt ranges, gap records, and diagnostics.

Attachment requires SeSecurityPrivilege in the effective token, which is the privilege that grants an unfiltered view of every event on the system. eventd holds it because it is the party that then applies per-event access control on everything it stores (§7).

Discovering zero CPUs is a startup failure (§8.2). There is no configuration for the CPU count and no way to attach to a subset.

2.2.2 Drain threads #

There is one drain thread per CPU, and each reads exactly one ring buffer. A drain thread never reads another CPU's buffer, which is what makes per-CPU sequence tracking a thread-local variable rather than shared state.

Each thread follows the read protocol PSPK specifies:

  • read_pos starts at tail_pos on first attachment, so eventd begins at the oldest surviving event rather than at the newest.
  • The drain loop loads write_pos with acquire ordering, checks tail_pos for lapping, validates the event's structural integrity, and advances read_pos by event_size.

  • After reading an event it re-reads tail_pos — the torn-read check — to detect that KMES overwrote the event while it was being copied.
  • With nothing to read it uses the notification protocol, setting need_wake and waiting on the futex, rather than spinning.

2.2.3 Copying #

A drain thread reserves both one slot and the event's byte length in its shard handoff before copying the event — header and payload — into process-local memory and advancing read_pos. If either reservation is unavailable, it leaves the event in KMES and waits; it does not copy or advance first (§2.3).

Nothing derived from the mapped region ever reaches a writer thread. The region is producer-owned and KMES can overwrite any part of it the moment read_pos moves past, so a pointer handed across the channel would be a pointer into memory that another CPU is entitled to rewrite before the writer gets to it.

The copy is bounded by the event's own event_size, and the drain thread never reads beyond it.

2.2.4 Generation changes #

An administrator changing the ring buffer capacity causes KMES to replace the buffers, which it signals by changing the generation field. A drain thread checks it after each drain cycle, and on a change:

  1. Records the sequence number of the last event it has successfully handed off.
  2. Finishes draining the old buffer to its now-frozen write_pos, updating that sequence number as it goes.
  3. Calls kmes_attach again for the same logical CPU, obtains the replacement descriptor, and maps it while the old mapping remains valid.

4. Scans the new buffer from tail_pos for the first event whose sequence is greater than the final sequence drained from the old buffer, and sets the new read_pos there. 5. Closes and unmaps the old buffer only after that scan succeeds. 6. Resumes draining from the new buffer.

Each drain thread handles this independently. There is no barrier, no coordination and no shared state, because each attaches only to its own CPU's buffer — so a resize is a per-CPU event that happens to occur on every CPU at roughly the same time.

Draining the frozen old buffer before switching prevents loss at the back of the old generation. The sequence scan prevents duplicates from the events KMES copied into the replacement. A shrink can still discard the oldest survivors; that loss appears as an ordinary sequence gap.

2.2.5 Sequence tracking #

During an uninterrupted run, each drain thread holds the last sequence number it saw for its logical CPU. It serves gap detection (§2.5) and a generation change.

After a restart, there is deliberately no single resume number. Different shard transactions can have committed out of sequence, so taking MAX(sequence) could skip an earlier stripe that never committed. The authority is the union of committed receipt_ranges from every readable active and historical shard (§3.1).

Startup merges those ranges per (boot_id, cpu_id), scans the surviving ring records, skips survivors already covered by a receipt, and re-ingests uncovered survivors. It emits a gap only for a sequence that is covered by neither a committed receipt nor a surviving ring record (§8.5). With no receipt for a CPU, coverage begins before sequence 1, so an overwritten prefix is detected correctly.

The metadata database's sequence checkpoints and the shutdown event are diagnostic only (§3.5, §8.4). Neither participates in recovery.

eventd depends on KMES sequence numbering remaining continuous while the kernel boot ID is unchanged, and so on KMES being initialized once for the whole boot and never unloaded or reloaded. A sequence regression under the same boot ID, other than duplicates deliberately encountered during replacement scanning, is a fatal incompatibility: eventd stops rather than confuse two KMES stream lifetimes under one receipt key.

2.3 Sharding

Peios / Reference / eventd / Event Ingestion

2.3.1 The shard count #

Event writes are distributed across independent SQLite databases. An explicit StorageShards count (§A) is between one and 256. Zero means "as many shards as there are successfully attached KMES buffers", and is the default; that automatic count is not capped at 256.

Every shard costs file descriptors. An active shard's writer connection holds three for eventd's life — the database, its write-ahead log and its shared-memory index — as does the retention coordinator's connection to each historical shard (§3.6), and every event query that reads every shard holds about two more per shard while it runs (§6.4). eventd neither raises its own descriptor limit nor caps the shard count to fit it. The packaged eventd-service.reg sets LimitNOFILE to 262144. peinit applies it as both the soft and hard RLIMIT_NOFILE before launch; eventd does not raise the limit itself. Under an inherited 1024-descriptor soft limit, 256 shards do not start, and counts well below that leave little room for queries. Operators can override LimitNOFILE (DWORD) at Machine\System\Services\eventd and restart the service to apply it (peinit TRM §3.2).

The packaged value uses this conservative planning allowance:

4 × Q × max(E, 1) + 4 × Q + 3 × (E + 3) + 2 × C + 256

Here Q is the concurrent query count, E the total active and historical event databases visible to queries, and C the attached KMES buffer count. The terms allow four descriptors per query database (database, WAL, shared-memory index, and temporary-file headroom), four per query for its socket, peer token and transient handles, three per persistent database connection (including log, metric, and metadata stores), two per KMES buffer during replacement, and 256 for fixed handles and maintenance. Historical shards have persistent retention connections as well as query readers. Streaming queries are already included in Q; their separate limit is not added again.

At the default MaxConcurrentQueries=128, with at most 256 query-visible event databases and 256 attached KMES buffers, this gives 133129; 262144 rounds up with additional headroom. This is a sizing allowance, not a strict SQLite descriptor bound or a guarantee that the workload fits memory and thread limits. The limit does not preallocate handles.

Neither historical shard discovery nor the automatic shard count is globally capped by the explicit StorageShards range. More historical shards, more attached buffers or higher query concurrency require operator sizing and, where needed, a larger service limit. The host's fs.nr_open ceiling must also permit the chosen limit; setting the service value does not raise that system ceiling.

Two properties make a count perform well, and neither is enforced. A power of two lets routing use a bitwise AND rather than a modulo. A multiple of the attached-buffer count distributes shards evenly across drain threads. The default satisfies the second by construction.

2.3.2 Assignment #

Shard-to-CPU assignment is computed once at startup and is fixed for the process lifetime.

The successfully attached logical CPUs are assigned dense ordinals c = 0..attached_count-1 in logical-ID order (§2.2). For each ordinal c, eventd assigns every shard j where j % attached_count == c.

If that produces nothing — which happens when there are fewer shards than attached buffers — ordinal c is instead assigned c % shard_count. Every drain thread ends with at least one write path. Logical cpu_id, not the ordinal, is stored.

The three cases behave differently:

RelationResult
shards == CPUsone shard per CPU, the 1:1 case
shards < CPUsseveral CPUs share a shard
shards > CPUsa CPU owns several shards

A drain thread owning several shards distributes contiguous sequence stripes, not individual events round-robin. It sends a fixed positive number of successive events to one shard, then moves to the next shard it owns.

The stripe length is selected once at startup and is not persisted; committed receipt ranges, rather than recomputing the routing choice, are the recovery authority (§2.2, §3.1).

Keeping a contiguous run together makes one receipt describe the run compactly. It preserves parallelism across CPUs and across successive stripes without requiring any cross-shard commit coordinator.

When the counts do not divide evenly, some CPUs carry one shard more than others, or some shards receive from one CPU more than others. The resulting imbalance is one shard's worth of throughput, which is negligible against the whole.

2.3.3 Shards are not a query-path concept #

Assignment is not persisted. A shard database accumulates events from whatever CPUs routed to it during whatever eventd lifetimes wrote it, so a single shard file can hold events from a different set of CPUs in different regions of its history.

The query path therefore assumes nothing: it reads every database in the directory, and a query filtering on event.cpu scans all of them (§6.4). Sharding is a write-path optimization that the read path pays a fan-out for.

2.3.4 Writer threads #

Each shard has exactly one writer thread, and that thread is the only writer to that database. No other thread and no other connection writes to it, which is what makes the single-writer assumptions in §3.3 and §3.4 safe.

Drain threads never write to SQLite. When several drain threads share a shard they hand off concurrently, so the handoff channel is multi-producer and single-consumer.

2.3.5 The handoff channel #

Each writer thread has one bounded channel through which drain threads submit events. Its capacity is fixed at startup and independent of MaxBatchSize: the channel is bounded both by occupied slots and by the total bytes held by those slots.

Both are internal implementation limits selected by performance testing, not live registry settings.

When either bound would be exceeded the drain thread stops reading from the ring buffer and waits.

It reserves capacity before copying or advancing read_pos (§2.2), does not drop events to relieve pressure, and does not grow the channel. Events accumulate in the ring buffer instead, which is the designed path (§2.1):

writer slow → channel fills → drain pauses → ring buffer absorbs
            → KMES overwrites oldest if full → gap detected on resume

When the writer consumes slots and the channel has room, the drain thread resumes immediately.

Publication wakes a writer waiting on an empty channel; releasing capacity wakes producers waiting for room. The change itself supplies the wakeup, even when it races with a thread going to sleep. Neither side needs a later event or a timeout to notice the available work or capacity.

The channel is a small scheduling handoff, not storage for a complete transaction and not a second backlog buffer. A writer can consume and insert one slot while producers refill it, so a transaction can contain many more events than the channel can hold simultaneously.

Changing MaxBatchSize changes only the writer's next commit threshold and never resizes or replaces a live channel (§8.3).

2.3.6 Lifecycle and reconfiguration #

Shard databases are created in the event store directory on first use. eventd never deletes or overwrites one left by a previous configuration: starting with fewer shards than exist leaves the excess in place, and the query path continues to read them (§3.3).

Changing StorageShards takes effect at the next restart. The configuration watch notices the change and eventd defers it rather than reassigning CPUs or creating shards while running (§8.3).

Shard count changes are expected to be rare — set once from the hardware profile, one for a small board and a multiple of the CPU count for a server, and then left alone. Live migration would mean rebalancing writer threads and channels while events are in flight, for a configuration change that happens once in a machine's life.

2.3.7 Queue ownership #

The Rust queue constructor returns a clonable producer handle and one QueueReceiver. Consumer operations require mutable access to that receiver, so safe Rust cannot create concurrent consumers for a shard. Dropping the receiver closes the queue and wakes blocked producers.

Capacity must be a power of two and at least 2 slots. The sequence-number ring algorithm cannot distinguish a published slot from a free slot when the capacity is 1. Byte reservations remain independent of the slot count.

2.4 The Batch Writer

Peios / Reference / eventd / Event Ingestion

2.4.1 Transactions #

Each writer thread writes to its shard with explicit transactions: a BEGIN, one INSERT per event, a COMMIT. The commit is the durability boundary.

For every maximal contiguous sequence run represented by the event rows and eventd.events.lost rows in that transaction, the writer also inserts a receipt_ranges row for (boot_id, cpu_id, first_sequence, last_sequence) (§3.1).

Events, gaps, and their receipts commit together: there is no second durability operation and no global receipt writer.

The database runs in WAL mode with synchronous = FULL, so every commit fsyncs the write-ahead log.

This is the strictest of the three stores' settings, and the only one where per-transaction durability is bought at per-transaction cost — because an event can be an audit record and losing the last second of them to a power cut is a real loss.

2.4.2 Adaptive batch sizing #

The writer sizes each batch to balance throughput against how much sits uncommitted at any moment.

Throughput is always the priority. If eventd falls behind the emission rate, ring buffers fill and events are overwritten, which is irrecoverable; a shorter power-loss window is not worth that trade. The algorithm maximizes resilience within the constraint that throughput is maintained, never against it.

  1. When the first event is available, the writer opens a transaction and records the start time.

2. It reads available events from its drain threads and inserts them. 3. After each group of inserts it commits if any of these holds:

  • no assigned drain thread has an event available
  • the batch holds MaxBatchSize events
  • MaxBatchLatencyMs has elapsed since the first event entered it
 <a class="citation-anchor" id="cite-batch.a-batch-commits-once-max-batch-latency-ms-has-elapsed-since-its-first-event" href="#cite-batch.a-batch-commits-once-max-batch-latency-ms-has-elapsed-since-its-first-event" data-citation="*batch.a-batch-commits-once-max-batch-latency-ms-has-elapsed-since-its-first-event" title="*batch.a-batch-commits-once-max-batch-latency-ms-has-elapsed-since-its-first-event" aria-label="Citation *batch.a-batch-commits-once-max-batch-latency-ms-has-elapsed-since-its-first-event"><sup></sup></a>
  1. Otherwise it keeps reading and inserting.
  2. With nothing available and an empty batch, it sleeps until a producer wakes it.

The first condition is what makes the algorithm adaptive. Under light load the input drains immediately, so a batch of three events commits at once and the exposure window is microseconds. Under sustained load batches grow until they hit the size cap or the latency cap, whichever comes first, and the per-commit fsync is amortized across thousands of rows.

The writer chooses its own insert-group size, subject to a group never letting a batch exceed the size cap or stay open past the latency cap.

Both bounds are configuration (§A). The defaults are 10000 events and 100 milliseconds — the tightest latency of the three stores, for the same reason the durability setting is the strictest.

2.4.3 WAL checkpointing #

WAL mode accumulates log data until a checkpoint copies it back into the main database file. Under sustained writes the log grows.

Each writer triggers a checkpoint when its write-ahead log reaches WalCheckpointPages (§A), in SQLITE_CHECKPOINT_PASSIVE mode — checkpointing as much as it can without blocking readers.

If a passive checkpoint cannot make progress because readers hold pages, the writer does not block: it keeps writing and retries after a later commit.

Checkpointing runs on the writer thread and briefly serializes with insert work, which is inherent to SQLite rather than a choice — a database cannot be checkpointed and written concurrently. Passive mode is the lightest option available, yielding immediately when readers hold pages, and the per-checkpoint cost is bounded by the threshold.

2.4.4 Prepared statements #

Each writer prepares its INSERT once at startup and reuses it for every row, which keeps SQL parsing and planning off the hot path entirely.

The receipt insert and new-event-type catalog insert are prepared and reused too.

A known event type causes no catalog SQL operation; the writer's in-memory intern table identifies only new names, which are inserted in the same transaction as their first event (§3.1).

2.4.5 Maintenance commands #

The writer owns the shard's only read-write connection. Retention, receipt compaction and index policy code can inspect through read-only connections, but they submit bounded maintenance commands to this writer rather than opening another writer or taking a shard mutex.

The writer considers low-priority maintenance only at transaction boundaries and rechecks ingestion pressure after one bounded action.

A size-urgent retention delete can be included in an existing ingestion transaction so it adds no second commit.

Index creation remains cancellable through SQLite's progress handler (§3.4). Under sustained pressure maintenance can lag indefinitely; accepting incoming events is the higher priority.

2.5 Gap Detection

Peios / Reference / eventd / Event Ingestion

Every event carries a per-CPU, per-boot sequence number, and a drain thread knows what it last saw. That is the whole mechanism: an event whose sequence number exceeds the expected next one means the numbers in between belonged to events eventd never received.

During restart reconciliation, "expected" is the union of committed receipt coverage and surviving ring records rather than one last-seen number. A sequence already covered by either source is not a gap (§2.2).

2.5.1 Causes #

  • Ring buffer overrun. KMES overwrote events before eventd read them. The most serious case: it means audit events were lost irrecoverably.
  • Structural drops. KMES declined to write an event that exceeded its size limits.
  • Downtime. Events emitted while eventd was not running.

All three appear identically at the consumer, which is why the record says what was lost rather than why.

2.5.2 Gap records #

On detecting a jump, the drain thread generates a gap record, an eventd.events.lost event, carrying:

  • the CPU identifier
  • the first missing sequence number, the last seen plus one
  • the last missing sequence number, the revealing event's minus one
  • the count of missing events
  • the timestamp of the last event successfully processed on this CPU, where one is known

"Known" means the drain thread saw that event in this run. A gap found during restart reconciliation whose preceding events are accounted only by a committed receipt range carries no preceding timestamp, even though those events are stored: a receipt proves the sequence was accounted for, and eventd does not read the stored event back to recover its time.

Its own timestamp, event.time, is the timestamp of the event that revealed the gap, not the moment eventd noticed. The lost events were therefore written between the last processed timestamp and the record's own, and the record sorts beside the event that revealed it.

The record is written into the shard database through the normal write path — handed to the same writer thread, batched with ordinary events, committed in the same transaction. That transaction's receipt range covers the missing sequence interval as well as any real event rows, so a restart never emits the same gap twice (§3.1).

It is not emitted through KMES, which would be circular: the mechanism for recording that the event transport lost something cannot depend on that transport.

The gap details are stored as a MessagePack map in the payload column (§3.2), under the catalog's buffer.cpu and loss.* fields, and gap records are queryable exactly like any other event.

2.5.3 The CPU column #

A gap record populates cpu_id and leaves the other KMES header columns — sequence, origin_class, the identity GUIDs — null (§3.1).

cpu_id is populated deliberately, and it is the one place a synthetic event carries a header field. Without it, EVENTS WHERE event.cpu == 3 would return every event from CPU 3 except the record saying that events from CPU 3 went missing — which is the one record such a query most needs to return.

sequence stays null because a gap record has no place in the sequence: it describes numbers that were skipped, and giving it one of them would make it indistinguishable from the event that was lost. It is also what keeps gap records distinct from real events; receipt_ranges records the accounted sequence interval separately (§3.1).

2.5.4 Lapping #

If read_pos falls behind tail_pos, the consumer has been lapped and the PSPK read protocol advances it to tail_pos.

Lapping needs no special handling here. The next event read is the oldest survivor, its sequence number is far beyond what the thread expected, and ordinary gap detection records the difference. The lapping case and the restart case produce the same record by the same path.

2.6 Synthetic Events

Peios / Reference / eventd / Event Ingestion

Synthetic events are records eventd generates about itself. They are written straight to a shard database and never touch KMES.

They carry no KMES header: no identity stamps, no sequence number, no origin class. What they have is a timestamp and one of exactly five event types, all under eventd's own platform root eventd (PGSS §6.A), and the type is what distinguishes them in the events table — no separate record-type column exists (§3.1). The timestamp is eventd's clock when it generated the record, except for a gap record, whose timestamp is that of the event that revealed the gap (§2.5).

2.6.1 When they are generated #

ConditionType
Lost events detected on a CPUeventd.events.lost (§2.5)
eventd started and attached to KMESeventd.daemon.started
Graceful shutdown, once everything read is committedeventd.daemon.stopped
A store was found corrupt and quarantined, at startup or at write time (§9.2)eventd.store.quarantined
A configuration value changed at runtimeeventd.config.changed

Payload schemas for all five are in §3.2.

All five are tier essential (PGSS §6.8). eventd is their emitter as well as their store, and the emission policy never switches an essential type off (PGSS §6.9), so eventd writes each whenever its condition occurs and consults no policy for them. Their fields are those of eventd's catalog fragment, installed as /usr/share/evman/eventd.evman (PGSS §6.10).

Note what is absent: there is no synthetic event for malformed ingestion input. Authentication does not make admitted input trustworthy, and emitting a durable record per bad datagram would hand a producer an amplification primitive (PSPU §3.4). These five are conditions eventd observed about itself, not reactions to what it was sent.

2.6.2 Which shard #

CPU-specific synthetic events — gap records — go to the shard assigned to the CPU that generated them, handed to that writer thread alongside that CPU's ordinary events. A gap record travels with the events it describes.

Daemon-wide ones — start, stop, configuration changes, quarantines — go to shard 0 when shard 0 is writable, and otherwise to the lowest-numbered writable active shard.

If no shard is writable at all the event is skipped, with the failure logged to standard error.

A quarantine is the case that needs the fallback. It describes a failure on one particular shard but is itself a daemon-wide notification, so it is not written to the failing shard unless that shard has since been replaced and is writable again (§9.2) — writing the record of a shard's failure into that shard would lose it exactly when it matters.

These events are infrequent enough that concentrating them on shard 0 costs nothing measurable in balance.

2.6.3 Storage and ordering #

Synthetic events live in the same shard databases as KMES events and participate in the same batching, the same retention and the same queries.

Access control treats their types like any other (§7.2), so a descriptor at Machine\System\eventd\Security\Events\eventd governs all five, and one at …\Events\eventd.daemon only the start and stop records.

They are ordered by their timestamp and take no part in per-CPU sequence numbering.

For the four daemon-wide types that timestamp is when eventd noticed, not when the condition occurred. A gap record is different: its timestamp is the revealing event's (§2.5), so it sorts beside that event, and with loss.preceding-time it bounds when the lost events were written. eventd can detect a gap long after the events were overwritten — after a restart, the first thing it writes in a boot can be the record of events lost before — and the record's time says when they were lost, not when eventd found out.

2.6.4 The reserved types #

A KMES event whose type is one of the five is not stored: eventd counts it and drops it, and still receipts its sequence (§3.1). Exactly those five names are reserved, not the eventd root or any prefix of it, so eventd remains free to emit other eventd.* types through KMES.

3.1 The Event Shard Schema

Peios / Reference / eventd / Event Storage

Every shard database holds one events table.

ColumnTypeContents
idINTEGER PRIMARY KEYSQLite rowid, monotonic within the shard.
boot_idBLOB NOT NULL16-byte boot ID GUID in PCDS binary layout.
timestampINTEGER NOT NULLNanoseconds since the Unix epoch. From the KMES header for a real event; eventd's clock at generation for a daemon-wide synthetic one; the revealing event's timestamp for a gap record (§2.5).
cpu_idINTEGERFrom the KMES header. Null for daemon-wide synthetic events; populated for gap records (§2.5).
sequenceINTEGERPer-CPU, per-boot sequence from the KMES header. Null for every synthetic event.
origin_classINTEGER0 userspace, 1 KMES, 2 KACS, 3 LCS, 4 NTFE. From the header, as written. Null for synthetic events.
event_typeTEXT NOT NULLFrom the header; or one of the five types eventd writes itself (§2.6).
effective_token_guidBLOB16-byte GUID for the effective token at emission. Null for synthetic events; the null GUID when identity was unavailable at emission.
true_token_guidBLOB16-byte GUID for the process's primary token. Null for synthetic events.
process_guidBLOB16-byte GUID for the emitting process. Null for synthetic events.
payloadBLOBMessagePack. For a KMES event, the raw payload bytes exactly as received. For a synthetic event, a map (§3.2). Null when the event carries none.

3.1.1 Header fields are columns #

Every KMES header field is extracted into its own column rather than left inside the payload blob.

That is what lets a predicate on emitter.process.guid or event.type become a SQL comparison rather than a decode of every candidate row, and it is what makes those fields indexable by ordinary column indexes (§3.4).

The column names are internal to the store. A query names a header field by its path from PSPU §3.22, and eventd reads it from its column:

FieldColumn
event.timetimestamp
event.sequencesequence
event.cpucpu_id
event.typeevent_type
event.boot.guidboot_id
emitter.classorigin_class
emitter.token.guideffective_token_guid
emitter.true-token.guidtrue_token_guid
emitter.process.guidprocess_guid

A column's name is not a field: cpu_id in a query names a payload field, as any other name outside these nine does.

event_type is the sole discriminator between real and synthetic records. No record-type column exists, because the five types eventd writes itself already partition the type namespace and a second column would be a second thing to keep consistent.

The partition holds because eventd reserves those five names, and only those (§2.6). A KMES event whose type is one of them is not stored: eventd counts it and receipts its sequence, so it is neither a row nor a gap.

Any other type, including any other under eventd., is stored as usual. The count appears in the diagnostic dump (§8.5).

3.1.2 The payload is not touched #

For a KMES event the payload column holds the bytes KMES delivered, unmodified. eventd does not decode them on the write path, does not re-encode them, and does not validate them beyond what the ring-buffer protocol already checked.

The payload is a MessagePack value whose schema belongs to the emitting subsystem, and eventd has no catalog of those schemas. It decodes on the read path when a query needs a payload field (§6.1), which is also the only point at which the flattening rules of PSPU §3.22 apply.

Storing the bytes verbatim is also what keeps a payload value at a header field's path recoverable: the value, or the map and everything beneath it, is suppressed from the query surface but remains in the blob.

3.1.3 The event-type catalog #

Every shard also holds event_types:

ColumnTypeContents
event_typeTEXT PRIMARY KEYA concrete event type that has been committed to this shard.

The writer loads this small set into an in-memory intern table at

startup. A known type adds no catalog statement to an event insert.

A new type is inserted once, in the same transaction as its first event, and enters the in-memory set only after that transaction commits.

A transaction-local pending set prevents later events of that type in the same batch from repeating the catalog statement; rollback discards the pending set.

Query planning unions these catalogs across relevant active and historical shards to discover concrete identifiers for access checks (§6.1).

It never needs a DISTINCT event_type scan of the events table, so idx_events_event_type remains an adaptive index that can be shed without breaking planning (§3.4).

Retention records the distinct types touched by each delete batch and offers orphan checks as low-priority maintenance. The writer rechecks NOT EXISTS in the deletion transaction, and removes the type from its in-memory set only after that deletion commits.

A stale catalog row is safe — it causes an unnecessary access check but cannot expose data — so an unindexed or pressure-interrupted check is skipped and cleanup never delays ingestion.

Catalog pages count toward the store's logical live size (§3.6), preventing unique-name abuse from escaping the store-wide size accounting.

3.1.4 Committed receipt ranges #

Every shard also holds receipt_ranges:

ColumnTypeContents
boot_idBLOB NOT NULL16-byte kernel boot ID.
cpu_idINTEGER NOT NULLLogical KMES CPU identifier.
first_sequenceINTEGER NOT NULLFirst accounted sequence, inclusive.
last_sequenceINTEGER NOT NULLLast accounted sequence, inclusive.

The primary key is (boot_id, cpu_id, first_sequence, last_sequence), and every row satisfies first_sequence > 0 and last_sequence >= first_sequence.

A receipt says that every sequence in its range was accounted for by the same transaction: either the real event row was stored or an eventd.events.lost row durably records why it was absent. The receipt is in that transaction, so its presence proves commit without a global checkpoint or another fsync.

Receipt rows survive event retention.

Startup unions and merges overlapping or adjacent ranges across every readable shard (§2.2, §8.5).

A read-only background pass can prepare a low-priority compaction plan while the store is quiet. Writer-owned mutations first insert a merged range and only later delete ranges it subsumes, including ranges in other shards.

Insert-before-delete makes every intermediate state conservative and crash-safe.

Compaction mutations piggyback transactions a writer would commit anyway; they never cause a standalone commit or fsync, acquire no hot-path coordination primitive, and can lag indefinitely. Startup merge correctness never depends on physical compaction.

3.1.5 Identity can be absent two ways #

effective_token_guid, which a query reads as emitter.token.guid, distinguishes two cases that would otherwise look alike. Null means the record is synthetic and never had an identity. The null GUID — sixteen zero bytes — means the record is a real KMES event whose identity was not available at emission time, because it was emitted before or outside a context that had one.

The distinction matters for audit: "eventd wrote this" and "the kernel emitted this and could not attribute it" are different facts.

3.1.6 Write-time indexes #

One index is created with the table:

  • idx_events_timestamp on events(timestamp)

Time-range filtering is the foundational access pattern — nearly every query carries a SINCE — and it is the one index eventd never sheds, whatever the write pressure (§3.4). Every other index is the adaptive system's business.

3.1.7 Schema version #

Each shard holds events, event_types, receipt_ranges, and a metadata table:

ColumnTypeContents
keyTEXT PRIMARY KEYMetadata key.
valueTEXT NOT NULLMetadata value.

with two required entries: schema_version, and created_at as a UTC timestamp formatted YYYY-MM-DDTHH:MM:SSZ.

The current version is in §B.

eventd checks the version at startup and applies the lifecycle rules of §3.3. It does not migrate: an unrecognized version is a startup failure for an active shard and an exclusion for a historical one. Migration is an administrative operation, deliberately not an automatic one — a daemon that silently rewrote an audit store's schema on first start after an upgrade would be doing the one thing an audit store must not do unattended.

3.2 Synthetic Event Payloads

Peios / Reference / eventd / Event Storage

Each of the five synthetic event types (§2.6) carries a MessagePack map in payload, with the schema below. The fields are catalog fields, defined in eventd's fragment /usr/share/evman/eventd.evman or in the kernel's (PGSS §6.10), and each is stored as nested maps, one per segment of its path: store.shard-count is the value at {store: {shard-count: …}}. A query names a field by its dotted path, and reads an array field whole.

No field is ever nil. A field with no value is left out of the map (PGSS §6.5), and the table below says when each one can be.

None of them is at a header field's path, so none is suppressed. The boot and the CPU are read from the columns as event.boot.guid and event.cpu (§3.1), and no payload repeats the boot.

3.2.1 eventd.daemon.started #

FieldTypeContents
store.restartedboolTrue when committed rows or receipts for this boot already existed at startup; false on the boot's first successful eventd start.
store.shard-countunsigned integerActive shard count after resolving StorageShards.
store.resume.cpusarray of unsigned integerOne entry per logical CPU, in ascending order.
store.resume.sequencesarray of unsigned integerParallel to store.resume.cpus: for the CPU at the same index, the highest sequence contiguously accounted for after receipt/ring reconciliation, or 0.

There is no boot ID in the payload: the record's own event.boot.guid is the boot it describes.

store.restarted is the boot-boundary decision of §3.7 recorded as data, which makes "did eventd crash during this boot, and how often" answerable by query rather than by inference from gaps.

3.2.2 eventd.daemon.stopped #

FieldTypeContents
store.committed.cpusarray of unsigned integerOne entry per logical CPU, in ascending order.
store.committed.sequencesarray of unsigned integerParallel to store.committed.cpus: the highest sequence contiguously covered by committed receipts for that CPU this boot, or 0 if none was.

When eventd cannot read its committed receipts at shutdown, both arrays are left out and the payload is an empty map. It never writes zeroes in their place, so a 0 is always a real value.

Diagnostic only. Startup derives recovery coverage from committed receipt ranges, never from this payload (§2.2).

3.2.3 eventd.events.lost #

FieldTypeContents
buffer.cpuunsigned integerThe CPU whose ring the gap was found on.
loss.sequenceunsigned integerFirst missing sequence number.
loss.sequence-lastunsigned integerLast missing sequence number.
loss.countunsigned integerHow many are missing.
loss.preceding-timetimestampThe last event successfully processed before the gap. Absent when none is known.

The time of the event that revealed the gap is not a payload field: it is the record's own event.time (§2.5).

The CPU appears both here, as buffer.cpu, and in the cpu_id column (§2.5). The column is what a WHERE event.cpu == N predicate matches and what a query presents as event.cpu; the payload field is what WHERE buffer.cpu == N matches, and what a reader of the stored payload sees without joining anything.

3.2.4 eventd.config.changed #

FieldTypeContents
config.key.pathstringAlways Machine\System\eventd.
config.namestringThe value's name under config.key.path.
config.type-previousunsigned integerThe registry type the value had before, as its REG_* number: 4 for REG_DWORD, 11 for REG_QWORD. Absent when no value was stored.
config.value-previousunsigned integerThe value before. Present exactly when config.type-previous is.
config.typeunsigned integerThe registry type the value has now, numbered the same way. Absent when the change removed the value.
config.valueunsigned integerThe value now. Present exactly when config.type is.

Every value eventd reloads at runtime is a REG_DWORD or a REG_QWORD (§A), so both values are integers, and a query can compare them as numbers.

A side is absent when no value is stored, even though eventd's compiled default then applies. A stored value of the wrong type is reported as the type eventd expects, holding the integer it actually uses.

3.2.5 eventd.store.quarantined #

FieldTypeContents
store.kindstringevent, log, or metric.
store.shardunsigned integerThe shard, for the event store. Absent for the log and metric stores, which are not sharded.
outcome.detailstringHuman-readable description of what eventd found.

outcome.detail is diagnostic text and its wording is not stable. store.kind and store.shard are the fields worth alerting on. The metadata database is never reported here: a damaged one is rebuilt (§3.5) and writes no record.

3.3 Database Lifecycle

Peios / Reference / eventd / Event Storage

3.3.1 The event store directory #

Every shard database and the metadata database live in one directory, named by EventStorePath (§A).

There is no compiled-in default: a missing or invalid value is a startup failure, and eventd writes event databases nowhere else.

The standard path is /var/state/eventd/events/.

The eventd package ships eventd-config.reg, which declares /var/state/eventd/ and its events/, logs/, and metrics/ children as required peinit provisioned directories. peinit creates all four and establishes their descriptors before eventd starts. The eventd entry sorts before eventd-events, eventd-logs, and eventd-metrics, so the parent exists when each child is provisioned. The image or installer supplies /var/state; peinit does not create unnamed parents.

Each of the four carries an explicit protected, inheritable descriptor granting full control only to SYSTEM, Administrators, and the service SID of eventd's own virtual Service identity, which is what the daemon runs as:

O:SYG:SYD:P(A;OICI;GA;;;SY)(A;OICI;GA;;;BA)(A;OICI;GA;;;S-1-5-80-1963885778-1835409261-1671587836-2279113866-1994761124)

A deployment choosing another configured path provisions it with this descriptor before eventd starts.

eventd does not create store directories.

It opens every path component without following symbolic links, retains the resulting directory descriptor, and opens, creates, renames and quarantines database, WAL and shared-memory files relative to that descriptor.

A missing path, a non-directory component, a symbolic-link component, or a store directory whose owner, group and DACL are not exactly the descriptor above — which is what keeps an untrusted principal from replacing children — is a startup failure.

SQLite's database, -wal, and -shm files inherit the directory's protection.

3.3.2 Naming #

Active shards are shard-NNNN.db, with the shard index zero-padded to four digits — the index assigned at startup, which is not a CPU number (§2.3).

Starting with more shards than exist creates the new ones.

Starting with fewer leaves the excess in place: they become historical shards, are never deleted, and remain available to the query path.

3.3.3 Creation #

A shard database that does not exist, or that holds no schema at all (what a power cut leaves when it takes the uncheckpointed creating transaction), is created, in one transaction, with:

  1. WAL mode, PRAGMA journal_mode=WAL
  2. PRAGMA synchronous=FULL
  3. the events, event_types, receipt_ranges, and metadata tables (§3.1)
  4. the idx_events_timestamp index
  5. the schema_version and created_at entries

3.3.4 Opening an active shard #

  1. Open in WAL mode.
  2. Set synchronous to FULL.
  3. Read and verify schema_version. Missing or unrecognized is a startup failure. No migration is attempted.
  4. Verify structural integrity — the required tables and write-time indexes exist. Failing this, with SQLite reporting no corruption, is a startup failure.
  5. If SQLite reports corruption while opening or verifying, quarantine and replace (below).

A database holding schema objects but no metadata table with entries is not a shard eventd could have written; it is quarantined and replaced like a corrupt one.

Steps 3 and 4 fail rather than repair because an active shard is required: eventd has no degraded mode that runs without one (§8.2).

3.3.5 Quarantine #

When SQLite reports corruption in a required store, eventd renames the database aside and starts a fresh one at the original path. The main database file and any matching -wal and -shm files are renamed with the suffix .corrupt.<timestamp_ns>, all three using the same suffix from one operation, and a new empty shard-NNNN.db is created.

If a target name is taken, eventd appends .N with the lowest positive integer that makes it unique — which happens when two quarantines land in the same nanosecond, and when a previous quarantine already used the name.

Quarantining rather than deleting is the point: the corrupt file is the only copy of whatever it held, recovering data from it is an administrative operation, and eventd attempts no automatic repair.

The corruption is logged and an eventd.store.quarantined event is emitted once a shard is available to write it to (§9.2).

3.3.6 Historical shards #

A historical shard is never required for startup.

If one has a missing or unrecognized schema version, fails structural verification, or cannot be opened read-only, eventd logs the error and excludes it from the query path for this run — it does not fail startup and does not quarantine it.

The asymmetry is deliberate. An active shard that will not open means eventd cannot do its job; a historical one that will not open means some old data is unreadable, which is a smaller problem than refusing to boot the audit daemon over it.

3.3.7 Query path discovery #

The query path opens every file in the directory matching shard-NNNN.db that has a recognized schema and passes structural verification — active and historical alike. It assumes no particular number of them.

It explicitly does not treat every .db file in the directory as a shard: eventd-meta.db is excluded by the naming pattern, along with anything else that happens to be there.

Each is opened with a read-only connection.

Read-only connections in WAL mode do not contend with the writer's connection.

3.3.8 Concurrency #

Each shard has exactly one read-write connection, owned by its writer thread — for a historical shard, the retention coordinator (§3.6) — and any number of read-only connections owned by query handlers.

WAL mode permits concurrent readers alongside one writer without blocking either.

Writer threads never share connections.

Each creates and owns its own for the process lifetime, which is what makes the prepared statement in §2.4 a per-thread object with no locking around it.

3.4 Adaptive Indexing

Peios / Reference / eventd / Event Storage

Secondary indexes make queries fast and writes slow. Which indexes are worth that trade depends on what a particular deployment actually queries, which varies between systems and over time, and which nobody wants to tune by hand.

eventd observes the queries and maintains the indexes they imply — subject throughout to the rule that throughput outranks query latency.

3.4.1 Three decoupled parts #

Query frequency counters. Query handlers increment a per-field counter when a field appears in a WHERE predicate. This is the write-heavy path — once per query, per predicate.

Counters live in memory and are flushed periodically to the metadata database (§3.5), never to a shard, because they are global state that must survive shard reconfiguration.

Index policy. A periodic process reads the counters, applies the creation and removal thresholds, and computes the desired index set — an ordered list of fields, highest priority first.

It runs every AdaptiveIndexPolicyIntervalMinutes (§A), and also at once on every applied configuration change (§8.3) and every INDEX command, and once more at shutdown; it is the only writer to the desired set.

Each run reads the current thresholds and WAL checkpoint setting after its wait ends, including the final run on shutdown. An applied threshold change is therefore judged using the new configuration; it does not require a second change to take effect. Pending wakes can coalesce, so this is not a promise of one run per registry update.

Shard convergence. Writer threads read the desired set and move their material indexes toward it. They never read the counters and never write the desired set.

The separation exists so that the high-frequency counter updates never contend with the writer threads. The policy is the bridge between them and runs on the order of once an hour, so it is never a contention point.

The desired set is global — one list applying to every shard. Individual shards do not make independent decisions; they differ only in how far they have got.

3.4.2 Convergence #

A shard converges when it is quiet: its writer thread has no pending events, and no batch within the last SheddingWindowSeconds exceeded 75% of MaxBatchSize, the same measure that sheds indexes (below).

When it is quiet and its material indexes do not match the desired set, it takes one convergence action — creating the highest-priority missing index, or dropping the lowest-priority material index outside the desired set — then rechecks write pressure before considering another. It does so without waiting for the next policy run.

Creation uses CREATE INDEX IF NOT EXISTS; removal uses DROP INDEX IF EXISTS.

Both run on the shard's writer thread, which is the only thread permitted to write that database (§2.3).

Index creation is cancellable. If drain threads detect rising write pressure during a build, they signal the writer to abort; the writer cancels the CREATE INDEX, SQLite rolls back the partial index cleanly, and the writer returns to event batches immediately.

The abandoned build is retried at the next quiet period.

Cancellation responsiveness matters more than it looks. sqlite3_interrupt sets a flag checked at SQL VM opcode boundaries, and during B-tree construction for a large index the gap between checks can be tens of milliseconds — long enough to overrun a ring buffer at a high event rate. sqlite3_progress_handler(), registering a callback invoked every thousand opcodes that checks a cancellation flag and returns non-zero to abort, gives cancellation that tracks the pressure signal rather than lagging it.

Shards converge at their own pace. One under sustained pressure can lag the desired set indefinitely, and that is the correct outcome: it is prioritizing throughput.

3.4.3 Shedding #

Under sustained pressure a shard drops indexes to cut per-insert cost.

Graduated shedding. If more than SheddingBatchPercent of a shard's batches within a SheddingWindowSeconds sliding window exceeded 75% of MaxBatchSize, the shard drops its lowest-priority secondary index — the one whose column has the lowest query frequency in the desired set. If pressure persists, the next-lowest goes, and so on.

The check runs once per batch commit.

Emergency shedding. If a shard is at maximum batch size and its drain thread signals rising ring buffer pressure, it drops all secondary indexes at once.

DROP INDEX is a metadata operation measured in milliseconds, so it is safe to do under pressure in a way that creation is not.

The pressure signal comes from the drain thread watching the gap between write_pos and its own read_pos. Exceeding EmergencySheddingBufferPercent of ring buffer capacity raises it.

It is a distinct signal from the index-build cancellation one: this triggers shedding whether or not a build is in progress.

idx_events_timestamp is exempt. It is never shed at any pressure, because time-range queries are the access pattern everything else is built on and the store is unusable without it.

When pressure subsides, shedding reverses: the shard rebuilds toward the desired set under the same quiet-period scheduling and the same cancellability, highest priority first.

3.4.4 Candidates #

Any field that can appear in a WHERE predicate is a candidate.

Header columns. The columns of event.type, emitter.class, event.cpu, emitter.token.guid, emitter.true-token.guid, emitter.process.guid, and event.boot.guid (§3.1). The counters and the desired set name each by its field path. timestamp, the column of event.time, is always indexed and is not adaptively managed; a predicate on event.time is not counted.

Payload fields. Any queryable flattened path that appears in a predicate is a candidate for an expression index. A path suppressed by the flattening rules of PSPU §3.22 — a header field's path or one beneath it, a key that is not a valid segment, a duplicate path — never receives one, because it is not a query-language field at all. A path beside a header field's, such as emitter.process.pid beside emitter.process.guid, is an ordinary candidate.

Counters and a desired set written by an earlier eventd, which named header fields by their columns (event_type, process_guid), are read back at startup under the fields' paths. Such a name could only have meant the header field then, because a payload key spelled like a column was reserved, so the renaming loses no index and builds no spurious one.

The raw payload column never receives a plain column index. Indexing an opaque blob accelerates nothing.

3.4.5 Payload indexes are an optimization, not an authority #

An expression index extracts a field from the payload on every insert and indexes a deterministic private key for it.

The exact key bytes are internal to eventd and are not part of the storage contract.

eventd can implement these as SQLite expression indexes with deterministic extraction functions, as generated columns, or by any equivalent SQLite-backed means. What every mechanism has in common is that it implements the same field resolution and flattening as PSPU §3.22 — and that where the index cannot reproduce the query language's comparison semantics exactly, it is used only to narrow candidate rows, with the real predicate applied after the row is loaded (§6.3).

SQLite's native dynamic-type equality and ordering never substitute for the query language's string case folding, numeric comparison, binary comparison, array comparison, or null and missing-field handling. Getting a smaller answer faster is worthless if it is a different answer.

Rows where the field is absent, unqueryable or suppressed index as null, or are otherwise excluded in a way that preserves those semantics.

Payload indexes are otherwise ordinary members of the desired set, with the same priority ordering, shedding and convergence.

3.4.6 Naming #

Header column indexes are idx_events_<column>, named for the column rather than the field — idx_events_event_type for event.type, idx_events_process_guid for emitter.process.guid.

Payload expression indexes are named from the field GUID (§7.3), to avoid both collisions and characters SQLite will not accept in an identifier:

idx_events_payload_<field_guid_hex>

where field_guid_hex is the UUID v5 field GUID for the flattened path, as 32 lowercase hexadecimal digits with braces and hyphens stripped.

The path source.name yields idx_events_payload_ followed by the 32 hex digits of uuid_v5(EVENTD_FIELD_NAMESPACE, "source.name").

Deriving the name from the GUID rather than from the path means the same path always produces the same index name, and no path — however it is spelled — can produce a name that collides with another's or that SQLite rejects.

3.5 The Metadata Database

Peios / Reference / eventd / Event Storage

One database in the event store directory is not a shard: eventd-meta.db.

It holds the state that is global to eventd rather than to any shard — adaptive index state and diagnostic sequence checkpoints — and it is the one database that survives shard reconfiguration untouched.

It is created on first startup if absent or holding no schema, opened in WAL mode with synchronous=NORMAL. It is written at each run of the index policy (§3.4) — every policy interval, on every applied configuration change and every INDEX command, and once more at shutdown — and read at startup, so per-transaction durability buys nothing: losing the counters since the last run costs some adaptation, not any data.

The query path excludes it explicitly, since it is in the same directory as the shards (§3.3).

3.5.1 Tables #

index_counters — query frequency per field (§3.4).

ColumnTypeContents
field_pathTEXT PRIMARY KEYHeader field or payload path: event.type, access.granted, source.name. A header field's column name written by an earlier eventd is read back as its path (§3.4).
query_countINTEGER NOT NULLQueries filtering on it within the current window.
window_startINTEGER NOT NULLWhen the window started, nanoseconds since the epoch.

desired_indexes — the computed desired index set.

ColumnTypeContents
field_pathTEXT PRIMARY KEYHeader field or payload path, read back like a counter's.
priorityINTEGER NOT NULLRank; lower is higher priority.
is_expressionINTEGER NOT NULL1 for a payload expression index, 0 for a column index.

sequence_checkpoints — diagnostic only.

ColumnTypeContents
boot_idBLOB NOT NULLThe boot the checkpoint applies to.
cpu_idINTEGER NOT NULLCPU identifier.
sequenceINTEGER NOT NULLLast committed sequence for that pair when written.
updated_atINTEGER NOT NULLWhen it was written.

Primary key (boot_id, cpu_id). Startup recovery uses committed receipt ranges and never this table (§2.2).

The table exists so that an operator can see what eventd believed at shutdown and compare it with receipt coverage — the two disagreeing is itself diagnostic.

meta — key-value.

ColumnTypeContents
keyTEXT PRIMARY KEYMetadata key.
valueBLOB NOT NULLStrings as UTF-8 bytes, binary as raw bytes.

with two required entries: schema_version (§B) and created_at as a UTC YYYY-MM-DDTHH:MM:SSZ string. The administrative descriptor lives with every other eventd descriptor at Machine\System\eventd\Security\Admin (§7.2); no access-control state is stored in this reconstructible database.

3.5.2 Concurrency #

One writer connection, owned by the index policy thread. No other thread opens the database read-write.

Query handlers write only to the in-memory counters; the policy thread flushes them at each interval.

Writer threads and query handlers read the desired sets from memory, never from the database.

Graceful shutdown writes sequence_checkpoints through the same connection, after policy activity has stopped (§8.4).

With a single writer and no other database-level access, SQLite's WAL mode is the whole of the concurrency control needed.

The policy thread checkpoints the write-ahead log at WalCheckpointPages in passive mode, and does not block when readers hold pages — the same rule as every other store (§2.4).

3.5.3 Recovery is cheap #

If SQLite cannot read the file, or the schema version is missing or unrecognized, or any required table or meta entry is missing or malformed, eventd logs an error and recreates the database from defaults.

This is the opposite of the rule for a shard, which fails startup (§3.3), and the difference is what is at stake. A shard holds the only copy of audit data. This database holds an optimization policy and some diagnostics — all of it reconstructible, none of it irreplaceable. Losing it costs the adaptation eventd had accumulated, and the counters begin refilling immediately. Security policy is unaffected because it lives in the registry.

3.5.4 Startup #

  1. Open eventd-meta.db, creating it if absent.
  2. Verify the schema version and required meta entries; recreate from defaults on failure.
  3. Load index_counters into memory.
  4. Load desired_indexes into memory.
  5. Load sequence_checkpoints, for diagnostics only.
  6. Discover the material indexes in each shard from its schema and compare against the desired set.

eventd resumes convergence from wherever each shard happens to be. It neither drops nor rebuilds indexes at startup: a shard's material set is a fact to be observed, not a state to be restored.

3.6 Retention

Peios / Reference / eventd / Event Storage

Retention bounds disk growth. eventd deletes on two axes, age and size, and enforces both — an event goes when it exceeds either threshold.

The retention model is deliberately minimal, and a later one is expected to support rules resembling queries: retain KACS events for ninety days, synthetic events for seven, userspace-origin events for fourteen; and to prune during ingestion rather than only in arrears. What is here is the least that prevents unbounded growth.

3.6.1 Age #

Rows are deleted from events where timestamp is older than EventRetentionDays (§A) from the current wall clock, until none remain.

Each shard is processed independently, and the rule covers KMES events, synthetic events and gap records alike.

3.6.2 Size #

Size is measured as logical live size, not file size:

logical_live_bytes = (page_count - freelist_count) * page_size

from PRAGMA page_count, PRAGMA freelist_count and PRAGMA page_size, taken after attempting a passive WAL checkpoint.

The event store's total is the sum across every shard.

Pages freed by retention do not count, because they are reusable by future inserts. Counting them would make retention chase its own tail: each deletion would free pages that still counted against the limit, prompting more deletion.

When EventRetentionMaxBytes is non-zero and the total exceeds it:

  1. Identify every non-current boot ID present in the shards.

2. Order them by their newest event timestamp, oldest boot first.

3. Delete each of those boots entirely, across all shards, one boot at a time, until the total is within the limit or no non-current boots remain.

4. If still over, delete the oldest events of the current boot by timestamp, across all shards, until within the limit.

Size pressure prefers boot boundaries. Deleting a whole old boot removes a self-contained unit — its sequence numbers, its gap records and its startup event go together — and it preserves recent events across the boundary, which is what an operator investigating a reboot needs. Only when whole boots are exhausted does eventd start on the current one.

3.6.3 Running it #

A background retention coordinator processes the event store first, then the log store (§4.4), then the metric store (§5.5). Each store is processed whether or not the one before it failed, and the pass reports every store that did. The interval is RetentionCheckIntervalMinutes (§A); an applied configuration change (§8.3) and a write refused for want of space (§9.2) each request a pass at once. After a failed pass, requests are held for one second, doubling to a minute while passes keep failing, so a full disk does not drive retention into a tight retry loop. It uses read-only connections to measure and plan. The only read-write connections it owns are to historical shards, which have no ingestion writer: it opens each one read-write for the life of the process and deletes from it and checkpoints it directly, as that shard's one writer.

Every other database has exactly one read-write connection, owned by its ingestion writer.

The coordinator submits low-priority maintenance commands to that owner.

A command runs only at a transaction boundary, deletes at most RetentionDeleteBatchRows, and yields to ingestion before another command runs.

Under urgent size pressure the owner can append one bounded deletion to an ingestion transaction it already has open, avoiding an additional commit and fsync.

The passive checkpoint attempted before a size measurement is also a writer-owned command. The coordinator requests it, then reads the page and freelist counts through its read-only connection.

It never tries to checkpoint through that connection or temporarily promotes it.

There is no retention writer mutex and no second SQLite writer. A single unbatched DELETE over a month of events could otherwise hold a write transaction for as long as it took, blocking the writer and, behind it, the drain thread and KMES ring.

3.6.4 Reclamation #

Deleting rows does not shrink a SQLite file. Freed pages are reused by later inserts, and reclaiming filesystem space needs VACUUM, which rewrites the whole database.

eventd never runs VACUUM automatically. Reclamation is an explicit administrative operation.

In steady state it is not needed. Where ingestion and retention run at comparable rates, the file settles at roughly the high-water mark of retained data and the freed pages are recycled without further growth — which is also why logical live size, rather than file size, is the right thing to measure.

3.7 Boot Partitioning

Peios / Reference / eventd / Event Storage

Every record eventd stores — every event, every log line, every raw metric sample — carries a boot_id: a 16-byte GUID identifying the boot that produced it.

Linux assigns it at boot; eventd reads /proc/sys/kernel/random/boot_id at startup, validates the UUID text, and stores the corresponding PCDS-layout GUID.

3.7.1 What it is for #

Disambiguation. KMES per-CPU sequence numbers restart at zero each boot. Without a boot ID, sequence 42 from one boot is indistinguishable from sequence 42 from the next, and every gap calculation across a reboot would be wrong.

Lifecycle. Retention can delete a whole boot as a unit rather than scanning by timestamp, and a boot is the natural unit to delete: its events, its gaps and its startup record go together (§3.6).

3.7.2 Where it is stored #

StoreColumn
Eventevents.boot_id, every row
Loglogs.boot_id, every row
Metricsamples.boot_id, every row

The log store records it because log output can mean different things across boots — a service configured differently at boot time says different things.

The metric store records it per sample but does not make it part of series identity (§5.2).

A time series stays continuous across a reboot, which is what a chart of CPU usage across a restart should show, and a query that wants one boot's worth filters for it explicitly (PSPU §3.25).

3.7.3 Uniqueness #

Within one boot an event is uniquely identified by (cpu_id, sequence). Across boots, boot_id supplies the disambiguating dimension, and the triple (boot_id, cpu_id, sequence) is globally unique.

3.7.4 Detecting the boundary #

At startup eventd reads the kernel boot ID, then searches every readable event shard database — historical shards included — for committed rows or receipt ranges carrying it.

No committed rows or receipts for this boot. This is the boot's first successful eventd start. Coverage for every CPU begins before sequence 1, the new boot ID is used for subsequent writes to all three stores, and eventd.daemon.started carries store.restarted false.

Committed rows or receipts exist. eventd was previously ready in the same boot. It merges receipt coverage per (boot_id, cpu_id), reconciles that coverage with surviving ring records (§2.2), continues under the same boot ID, and emits eventd.daemon.started with store.restarted true.

The two cases are distinguished by the data itself rather than by any flag eventd persisted.

That is the point: a flag would have to be written at a moment eventd might not reach, and a crash is precisely the case where it did not.

Committed receipt ranges are the sequence authority. Committed event rows still establish that eventd previously ran when no receipt was yet needed. The metadata database's sequence checkpoints and the previous eventd.daemon.stopped payload are diagnostic — neither is consulted for recovery (§2.2, §3.5).

The receipt key is sound only while KMES sequence numbers do not restart under one kernel boot ID, so eventd depends on KMES remaining initialized for the whole boot. A future KMES ABI can add a stream generation GUID to make module reloads distinguishable without relying on that lifecycle invariant.

4.1 The Log Writer

Peios / Reference / eventd / Log Storage

One thread reads datagrams from the log socket and writes log records to the log store. It is independent of the event drain and writer threads, so log ingestion never contends with event ingestion.

The wire contract — socket type, datagram ceiling, record format, and exactly which malformations cost what — is PSPU §3.6 to §3.8. What follows is what eventd does with a record once it has one.

4.1.1 One thread does both jobs #

The log thread performs both the socket reads and the SQLite writes.

The consequence is direct: during a batch commit the socket is not being drained, and datagrams arriving in that window occupy the receive queue until it fills. A Unix datagram socket's receive queue is bounded in datagrams, by the kernel's net.unix.max_dgram_qlen, and it is the whole cushion. Once it is full the kernel refuses further sends rather than accepting and discarding them: a non-blocking sender receives EAGAIN, and a blocking one waits until the queue drains.

eventd sets SO_RCVBUF to four times the datagram ceiling, but for this socket type the kernel charges a queued datagram to its sender's send buffer, and the receive buffer bounds nothing.

Note

Linux's default net.unix.max_dgram_qlen is ten, and the kernel refuses a send only once more than that many are queued, so the queue holds eleven datagrams. A batch commit takes one to ten milliseconds, and those eleven are the only thing absorbing arrivals in the window. A service dumping a stack trace through non-blocking sends will have datagrams refused, which is the intended degradation for a loss-tolerant path (PSPU §3.4): whatever is lost is lost in the sender, and eventd neither buffers beyond the queue nor learns of the refusal.

Splitting into a reader and a writer with a bounded handoff — the shape the event path uses (§2.3) — would decouple them. It is not done, and the reasoning is that log loss is tolerable by design (PSPU §3.4), log volume is normally well below event volume, and the single-thread model avoids a handoff channel and its backpressure semantics entirely.

Where log throughput does become the constraint, sharding the log store the way the event store is sharded is the larger lever; splitting the thread only moves the stall.

4.1.2 Batching #

The writer batches on the same adaptive principle as the event writer (§2.4), with the socket receive queue as its input. A transaction opens when the first valid record is available and commits when any of these holds:

  • no further datagram is immediately available in the receive queue
  • the batch holds LogMaxBatchSize records
  • LogMaxBatchLatencyMs has elapsed since the first record entered it

If a datagram yields more valid records than fit in the remaining space, the writer commits, then continues with the same datagram in a new transaction.

A transaction never exceeds the size cap and never stays open past the latency cap — a batched datagram cannot smuggle a larger transaction past either.

The defaults (§A) are 5000 records and 500 milliseconds. The latency is five times the event writer's, because log loss on power failure is acceptable where event loss is not, and larger, less frequent transactions are more efficient at the moderate volumes logs normally run at.

The writer keeps the known origin names in memory. Before inserting the first log row for an origin not in that set, it executes INSERT OR IGNORE into log_origins in the same transaction (§4.2).

A transaction-local pending set ensures that insert runs only once per new origin in a batch. The main in-memory set is updated only after commit and the pending set is discarded on rollback.

Thus discovery never needs to scan the hot logs table, and a rolled-back first row cannot make the cache claim that its catalog entry exists.

4.1.3 Durability #

The log store runs in WAL mode with synchronous=NORMAL, not FULL.

NORMAL syncs at checkpoint time rather than at every commit. It is durable against process crashes — the write-ahead log survives — but not against power loss, where commits since the last checkpoint can be gone.

This is a deliberate divergence from the event store, and it is the single clearest expression of the hierarchy the whole daemon is organized around: events are sacred, logs are not. Paying an fsync per transaction to protect data whose loss is defined as acceptable would be paying for nothing.

4.1.4 Adding to the record #

eventd supplies the boot_id and, where the producer omitted timestamp, its own clock at receipt.

Everything else is stored as given — message byte for byte (PSPU §3.8).

4.1.5 Rejected origins are counted #

A record whose origin is outside the origin grammar (§4.2) is discarded where it is parsed, before it can join a batch.

eventd counts every such discard and keeps the most recent origin, escaped and truncated to 64 characters; both appear in the diagnostic dump (§8.5) as log_ingress and last_rejected_log_origin.

It also writes one line to standard error on the first discard and at most one a minute after that.

peinit captures eventd's own standard error, so that line is stored as an ordinary log record under the origin eventd and is queryable with everything else — and it still reaches the console directly when the log store is the broken thing.

The rate limit is what makes the report usable. A producer whose vocabulary has drifted from this one usually uses the same origin for every line it sends, so an unlimited report would turn a silent total loss into a flood; the count is the quantity that matters and the text is there to name the vocabulary that drifted.

4.2 The Logs Table

Peios / Reference / eventd / Log Storage

The log store is a single SQLite database — not a directory of shards. There is no sharding here: one ingestion thread produces the writes, so splitting the target would give a single writer several files to switch between rather than several writers working in parallel.

It holds the logs, log_origins, and metadata tables.

ColumnTypeContents
idINTEGER PRIMARY KEYSQLite rowid, monotonic.
boot_idBLOB NOT NULL16-byte boot ID GUID in PCDS binary layout.
timestampINTEGER NOT NULLNanoseconds since the Unix epoch — the producer's value if it supplied one, otherwise eventd's clock at receipt.
originTEXT NOT NULLThe producer peinit associated with the output pipe — a service, or a hook, health check, reload command or job within one.
is_errorINTEGER NOT NULL1 for standard error or an explicitly marked error, 0 otherwise.
messageTEXT NOT NULLThe log text.
job_idBLOB16-byte correlation GUID when the producer supplied one; null otherwise.

The schema is deliberately narrow. A log record is text with light metadata: what produced it, whether it was an error, when, and optionally which execution it belongs to. There is no payload blob and no origin class. origin is broker-attested rather than a service's self-assertion: the log socket admits peinit and excludes service-logon tokens (§7.6).

The optional correlation key is not an identity.

4.2.1 What an origin looks like #

An origin is one or two components (PSPU §3.7):

origin    := component | component "/" producer
producer  := component | component "[" [0-9]+ "]"
component := [A-Za-z0-9_][A-Za-z0-9_.-]*

One component is a service — loregd, jellyfin — and is what a main process's output carries. Two name a producer within a service: peinit tags a pre-start hook jellyfin/ExecStartPre[0], a reload command jellyfin/ExecReload, a health check jellyfin/HealthCheck, and a submitted job jobs/<guid> (peinit TRM §11.1). The bracketed index appears only after a slash, and there is never more than one slash.

Ingestion discards a record whose origin is anything else, before the record reaches a batch (§4.1). Nothing wider is accepted: * would impersonate the access-control wildcard, and a backslash, a quote or whitespace would reach into the registry path an origin's descriptor lives at (§7.2).

A program needing more structure than this emits events.

4.2.2 The origin catalog #

log_origins has one column, origin TEXT PRIMARY KEY. The log writer inserts a previously unseen origin in the same transaction as its first log row (§4.1), so every committed row is discoverable immediately.

Query planning enumerates origins from this compact catalog rather than running DISTINCT origin over the retained log rows (§6.1).

Catalog entries deliberately survive ordinary retention.

An origin can therefore remain discoverable after its final row expires; this safe superset avoids write work on the ingestion path.

Low-priority maintenance can remove an entry after proving through a read-only scan that no row refers to it, with the deletion submitted to the log writer.

The writer rechecks NOT EXISTS in that transaction and removes the origin from its in-memory set only after commit, so a log arriving between planning and execution cannot become undiscoverable.

Catalog pages count toward logical live size.

4.2.3 is_error is an integer here and a boolean there #

The column stores 0 or 1; the query language exposes a boolean, and accepts either WHERE is_error == true or WHERE is_error == 1 (PSPU §3.22). ERROR ONLY is sugar for the first.

4.2.4 Write-time indexes #

Three indexes are created with the table:

  • idx_logs_timestamp on logs(timestamp) — time-range filtering, as everywhere.
  • idx_logs_origin on logs(origin) — "show me logs from X", which is the dominant log query.
  • idx_logs_job_id on logs(job_id) WHERE job_id IS NOT NULL — a partial index for "show me logs for job X". Partial because ordinary service output can carry no correlation key, so only correlated lines are worth indexing.

The origin index costs write amplification beyond the timestamp index, and the cost is modest in practice: origin has low cardinality, tens of distinct names on a normal system, so its index pages stay in SQLite's page cache and insertion stays cheap. The trade is accepted deliberately — the two dominant log queries must not become full table scans.

4.2.5 No adaptive indexing #

The log store does not participate in adaptive indexing (§3.4). Its field set is closed and small, and the three write-time indexes already cover the access patterns; there is no space of candidate fields for a policy to discover.

The same follows for query frequency counters: log queries do not increment them (§6.5).

4.2.6 Schema version #

The log store holds a metadata table with the same two-column structure as a shard's (§3.1). Schema version 1 comprises logs, log_origins, and metadata; its version number is in §B.

eventd checks it at startup and applies the lifecycle rules of §4.3, and does not migrate.

4.3 Database Lifecycle

Peios / Reference / eventd / Log Storage

4.3.1 Path #

LogStorePath (§A) names a provisioned directory, conventionally /var/state/eventd/logs. The database itself has the fixed name logs.db inside it. A missing, invalid, or unsafe directory is a startup failure.

The directory has the provisioning, descriptor, and path-resolution requirements defined for the event store (§3.3). eventd does not create it or any parent directory, never follows a symbolic-link component, and creates or opens the database relative to an already validated directory handle.

4.3.2 Creation #

A log store that does not exist, or whose database holds no schema at all (what a power cut leaves when it takes the uncheckpointed creating transaction), is created, in one transaction, with:

  1. WAL mode, PRAGMA journal_mode=WAL
  2. PRAGMA synchronous=NORMAL
  3. the logs, log_origins, and metadata tables (§4.2)
  4. the idx_logs_timestamp, idx_logs_origin, and idx_logs_job_id indexes
  5. the schema_version and created_at entries

4.3.3 Opening #

  1. Open in WAL mode.
  2. Set synchronous to NORMAL.
  3. Verify the schema version. Missing or unrecognized is a startup failure; no migration is attempted.

4. Verify structural integrity — required tables and indexes present. Failing this, with SQLite reporting no corruption, is a startup failure. 5. On SQLite reporting corruption, quarantine and replace. A database holding schema objects but no metadata table with entries is not a store eventd could have written; it is quarantined and replaced like a corrupt one.

Quarantine works exactly as for a shard (§3.3): the database, -wal and -shm files are renamed with a shared .corrupt.<timestamp_ns> suffix, .N appended with the lowest positive integer if the name is taken, and a fresh empty log store is created at the configured path.

The log store is a required store. There is no degraded mode in which eventd runs without one (§8.2), which is why steps 3 and 4 fail startup rather than proceeding without logs.

4.3.4 Concurrency #

Exactly one read-write connection, owned by the log writer thread, and any number of read-only query and maintenance connections.

WAL mode lets readers run concurrently. Retention and catalog cleanup submit bounded commands to the writer and never open another read-write connection (§3.6).

4.3.5 Checkpointing #

The log writer checkpoints when its write-ahead log reaches WalCheckpointPages (§A), in passive mode, and does not block if readers hold pages — it keeps writing and retries after a later commit.

Checkpointing matters more here than in the event store, because synchronous=NORMAL makes the checkpoint the durability boundary rather than merely a space-reclamation event: data committed since the last checkpoint is what a power cut takes (§9.5).

4.4 Retention

Peios / Reference / eventd / Log Storage

Log retention works exactly as event retention does (§3.6), on the same background thread, running after the event store and before the metric store.

As there, the model is an early simplification and both limits are enforced with the more aggressive one winning.

4.4.1 Age and size #

Rows older than LogRetentionDays (§A) are deleted from logs until none remain.

If LogRetentionMaxBytes is non-zero and the store's logical live size exceeds it, the oldest entries by timestamp are deleted until it is within the limit.

Logical live size is the same measure as §3.6 — (page_count - freelist_count) * page_size after attempting a passive checkpoint — and freed pages do not count.

There is no boot-boundary preference here. Event size retention prefers to drop whole old boots because a boot is a self-contained unit of sequence-numbered records; a log line has no such structure, so oldest first is the whole rule.

4.4.2 The default is shorter than events' #

Fourteen days against the event store's thirty (§A).

Historical log data is worth less than historical audit data, and it is usually bulkier per unit of value. The metric store's default is longer than either at ninety days, for the opposite reason: a metric sample is tiny and trend data is worth more the further back it goes (§5.5).

4.4.3 Batching #

The retention coordinator plans with a read-only connection and submits low-priority commands to the log writer.

Each writer-owned transaction deletes at most RetentionDeleteBatchRows, and ingestion is rechecked before the next command.

Under urgent size pressure the writer can append one bounded delete to a transaction already open.

Retention never takes a writer mutex or opens a second read-write connection (§3.6).

The stall this avoids is the log ingestion thread's, and that thread is also the one draining the socket (§4.1) — so a retention pass holding a long write transaction would not merely delay writes, it would stop the socket being read and lose the datagrams that arrived meanwhile.

4.4.4 Reclamation #

VACUUM is never run automatically, as everywhere. Freed pages are recycled by later inserts and are excluded from the size measure.

5.1 The Metric Writer

Peios / Reference / eventd / Metric Storage

One thread reads datagrams from the metric socket and writes samples to the metric store, independent of both the event and log paths.

It has the same single-thread shape as the log writer, with the same consequence during a commit (§4.1).

The wire contract is PSPU §3.9 to §3.13. The same thread also writes eventd's own health samples, which skip step 1 below (§5.7).

5.1.1 Processing a record #

For each valid record:

  1. Authorize the name. The datagram's KACS token must hold EVENTD_PUBLISH on the resolved metric-name descriptor (§7.6).

2. Resolve the series from name and labels — and, for a histogram, bucket boundaries — through the in-memory series cache (§5.3).

A series that does not exist is inserted into series with the record's type, and the cache is updated. 3. Check the type. If the record's type differs from the resolved series' type, the record is dropped without replying to the producer. The type is set at creation and is immutable; a series never changes type. 4. Insert the sample into samples with the resolved series_id, the timestamp and the value. SQLite assigns samples.id, which is the deterministic tiebreaker among samples sharing a timestamp (§5.2). A histogram's data is encoded as the canonical MessagePack sample map and stored in histogram_data.

The transaction result counts step-3 failures and carries the most recent conflict's metric name and expected and received types.

The metric thread adds the count to an in-memory diagnostic total, retains that conflict, and emits a coalesced standard-error warning at most once per minute.

SIGQUIT includes both the total and latest conflict (§8.5).

There is still no response to the producer and no event per failure. Authentication identifies the producer; it does not make reactions proportional to its bad input safe. The one-minute global bound is what keeps the warning from becoming the amplification vector PSPU §3.4 forbids. A valid transaction takes only the existing zero-mismatch branch and performs no diagnostic allocation or synchronization.

5.1.2 Out-of-order samples #

The writer stores a valid sample whose timestamp precedes samples already held for that series.

Producers batch, clocks step, and sweeps get retried. Refusing late samples would convert any of those into silent loss, so eventd accepts them and defines every ordering it performs over (timestamp, id) rather than over insertion order. That makes raw RATE and DELTA evaluation deterministic regardless of arrival (§6.2).

5.1.3 Batching #

The same adaptive algorithm as the event and log writers (§2.4), with the socket receive queue as input.

A transaction opens at the first valid sample and commits when any of these holds:

  • no further datagram is immediately available
  • the batch holds MetricMaxBatchSize samples
  • MetricMaxBatchLatencyMs has elapsed since the first sample entered it

A datagram yielding more samples than fit is split across transactions, the writer committing before continuing with the same datagram. Neither cap is ever exceeded.

The defaults (§A) are 5000 samples and 1000 milliseconds — the longest latency of the three writers. Metrics are typically sampled every fifteen seconds, so a one-second commit window accumulates a whole sweep's worth without any latency that a dashboard could notice. Under a burst, where a collection agent submits every core, disk and interface at once, the size cap is what forces a timely commit.

5.1.4 Durability #

WAL mode with synchronous=NORMAL, as the log store (§4.1). Metric loss on power failure is acceptable, so per-transaction fsync buys nothing.

5.2 Series and Samples

Peios / Reference / eventd / Metric Storage

The metric store is a single SQLite database, and unlike the event and log stores it is organized around series rather than records.

Individual samples are appended to a series that already has an identity.

5.2.1 The series table #

ColumnTypeContents
idINTEGER PRIMARY KEYSeries identifier; the foreign key samples uses.
nameTEXT NOT NULLThe metric name.
labelsTEXT NOT NULLCanonical label representation. Empty string for no labels.
typeINTEGER NOT NULL0 counter, 1 gauge, 2 histogram.
label_hashINTEGER NOT NULLHash of the canonical label string.
boundaries_hashINTEGERHash of the canonical boundary blob. Null for counters and gauges.
boundariesBLOBCanonical boundary blob. Null for counters and gauges.

5.2.1.1 The canonical label string #

Labels are sorted by key in unsigned UTF-8 byte order, each pair written key=value, and the pairs joined with commas: core=0,host=server1.

The empty label set is the empty string.

No escaping is performed and none is needed, because ingestion rejects = and , inside a key or a value (PSPU §3.10). That prohibition exists precisely to make this encoding unambiguous, and it is the reason the constraint binds the producer rather than being handled internally.

5.2.1.2 The boundaries blob #

A fixed binary encoding, not MessagePack:

  1. boundary_count, u32 little-endian
  2. that many IEEE-754 f64 values, each little-endian, in the validated order the producer sent

It exists only to identify histogram series and to resolve hash collisions, and is never returned in a query result.

5.2.1.3 Hashes narrow, they do not decide #

label_hash and boundaries_hash are 64-bit FNV-1a over the exact bytes of the canonical string or blob, with offset basis 0xCBF29CE484222325 and prime 0x100000001B3. The high bit is cleared before storage, hash & 0x7FFF_FFFF_FFFF_FFFF, so the value always fits SQLite's signed INTEGER.

A lookup always verifies the full labels string, and for a histogram the full boundaries blob, after narrowing by hash.

A hash is an index key, never an identity: two label sets that collide are still two series.

5.2.1.4 Uniqueness #

The table carries UNIQUE(name, labels, boundaries), on the full boundary blob. boundaries_hash is a lookup key with its own index, and two histograms whose boundaries collide on it are two series.

For counters and gauges boundaries is null, and SQLite treats nulls as distinct in a unique constraint — so the constraint does not enforce uniqueness for them. What does is the single-writer resolution logic (§5.3), which checks before inserting.

The constraint is a defensive backstop against a future change that introduces a second write path, not the primary mechanism.

type is not part of the identity. A record resolving to an existing series with a different type resolves successfully and is then dropped for the mismatch (§5.1).

5.2.2 The samples table #

ColumnTypeContents
idINTEGER PRIMARY KEYInternal row identifier; the tiebreaker for samples sharing a series and timestamp.
series_idINTEGER NOT NULLReferences series(id).
boot_idBLOB NOT NULL16-byte boot ID GUID.
timestampINTEGER NOT NULLNanoseconds since the Unix epoch.
valueREAL NOT NULLThe raw value for counters and gauges. Stores 0 for histograms.
histogram_dataBLOBCanonical MessagePack histogram sample map. Null for counters and gauges.

For a histogram, histogram_data is a canonical MessagePack map (PSPU §3.5) with exactly four keys: boundaries, an array of float64 in the producer's order; counts, an array of unsigned integers; total_count; and sum, a finite float64.

value is a placeholder for histogram rows and is never returned as a metric query value. Storing 0 rather than null keeps the column NOT NULL and keeps the row layout uniform.

Canonical encoding is required here because a stored sample map must be byte-stable: two equal histograms encode identically, which is what makes them comparable without decoding.

boot_id is per sample and is not part of the series identity, so a series stays continuous across a reboot (§3.7).

5.2.3 Ordering #

Query execution order within a series is always (timestamp, id) ascending, never insertion order alone. Duplicate timestamps are permitted and id gives them a stable order.

id is internal. It is never exposed as a query field, a result field, an access-control field, or a reserved label key (PSPU §3.28).

5.2.4 Write-time indexes #

  • idx_samples_series_timestamp on samples(series_id, timestamp, id) — the dominant pattern is "samples for series X over range Y in deterministic order", and this one composite index serves the series lookup, the range filter and the (timestamp, id) ordering in a single scan.
  • idx_series_name on series(name) — name lookups.
  • idx_series_label_hash on series(label_hash) — series resolution on the ingestion path.
  • idx_series_boundaries_hash on series(boundaries_hash) — narrowing a histogram's lookup by its boundary hash.

5.2.5 Schema version #

A metadata table with the same structure as the other stores' (§3.1). Version 1 comprises series, samples, and metadata. Version 2 adds the disposable rollups query cache (§5.6); it does not change raw series or sample storage. Version 3 changes only the series table's uniqueness, from the boundary hash to the full boundary blob, and adds idx_series_boundaries_hash. The current value is in §B. eventd checks it at startup and applies the lifecycle and migration rules of §5.4.

5.3 Series Resolution

Peios / Reference / eventd / Metric Storage

Every arriving sample must be turned into a series_id before it can be inserted. This happens once per sample on the single metric ingestion thread, so it is the hottest lookup in the daemon and the reason a cache exists at all.

5.3.1 Resolving #

  1. Compute the canonical label string: sort by key in unsigned UTF-8 byte order, encode each pair key=value, join with commas. The empty label set encodes as the empty string. No escaping — ingestion has already rejected the delimiters (§5.2).
  2. Hash it.
  3. For a histogram, compute the canonical boundary blob and its hash from the validated, producer-supplied order. eventd never sorts boundaries. For counters and gauges both are null.
  4. Look up series by name, label_hash, and for histograms boundaries_hash.
  5. On a match, verify the full labels string, and for histograms the full boundary blob. If the record's type differs from the existing series' type, drop the record (§5.1). Otherwise use the existing series_id.
  6. On no match, insert a new series row and use the new identifier.

A histogram whose boundaries changed takes step 6: it is a new series (PSPU §3.13). The old one keeps its historical samples and the new one starts accumulating.

5.3.2 The cache #

Resolution runs through a bounded in-memory cache mapping (name, canonical labels, boundaries hash, boundaries blob) to series_id. For counters and gauges the boundary components are absent.

A hit is a hash table lookup with no SQLite involvement. A miss costs one SELECT on name and label_hash, after which the result is

inserted, evicting the least-recently-used entry if the cache is full.

The bound is MetricSeriesCacheSize (§A), default 50000, with LRU eviction. It bounds memory, not the number of series: the series table is uncapped and a new series is always created in the database. A system with a million series and a 50000-entry cache uses memory proportional to the cache, and at roughly 200 to 300 bytes an entry the default costs 10 to 15 MB.

The cache starts empty after a restart and is warmed on demand — within one collection cycle, typically fifteen seconds, every active series is cached. There is no pre-warming pass, because reading a million-row series table at startup to populate a 50000-entry cache would be work spent to discard most of its result.

5.3.3 Sizing it #

The cache is sized for the set of actively reporting series, and behaves badly below it.

Below that, LRU does not help, because every series is equally hot: each collection cycle evicts the overflow and reloads it, producing a fixed number of SELECTs every cycle, permanently. A system with 55000 active series and a 50000-entry cache incurs about 5000 cache misses every fifteen seconds, indefinitely.

This interacts badly with label cardinality (PSPU §3.10). Labels with unbounded values — request identifiers, user-supplied strings — grow the series table without limit, and once the active set exceeds the cache every cycle pays the eviction cost on the one thread that also drains the metric socket. The failure presents as metric loss, because the thread stops reading while it queries.

eventd does not cap series creation: at the interface, a producer creating a new series is indistinguishable from one creating garbage, and rejecting either would break a correct producer to inconvenience an incorrect one (PSPU §3.13). The default 1 GiB metric retention ceiling bounds the resulting disk growth (§5.5), but it does not prevent a hot working set from exceeding this cache and thrashing the ingestion thread before retention runs.

5.4 Database Lifecycle

Peios / Reference / eventd / Metric Storage

5.4.1 Path #

MetricStorePath (§A) names a provisioned directory, conventionally /var/state/eventd/metrics. The database itself has the fixed name metrics.db inside it. A missing, invalid, or unsafe directory is a startup failure.

The directory has the provisioning, descriptor, and path-resolution requirements defined for the event store (§3.3). eventd does not create it or any parent directory, never follows a symbolic-link component, and creates or opens the database relative to an already validated directory handle.

5.4.2 Creation #

A metric store that does not exist, or whose database holds no schema at all (what a power cut leaves when it takes the uncheckpointed creating transaction), is created, in one transaction, with:

  1. WAL mode.
  2. PRAGMA synchronous=NORMAL — the log store's reasoning, for the same reason: metric loss on power failure is acceptable (§4.1).
  3. The series, samples, rollups, and metadata tables (§5.2, §5.6).
  4. Every write-time index.
  5. The schema_version and created_at entries.

5.4.3 Opening #

  1. Open in WAL mode with synchronous NORMAL.
  2. Verify the schema version. Version 1 is migrated transactionally to version 2 by adding the adaptive-rollup cache. Version 2 is migrated transactionally to version 3 by rebuilding the series table under its new uniqueness constraint, foreign keys off for the rebuild and every identifier kept; a version 2 store missing a required table or index fails startup instead. Missing or unrecognized versions are a startup failure.
  3. Verify structural integrity — required tables and indexes present. Failing this, with SQLite reporting no corruption, is a startup failure.

4. On SQLite reporting corruption, quarantine and replace, exactly as for a shard (§3.3): matching -wal and -shm files renamed with the same .corrupt.<timestamp_ns> suffix, .N appended if the name is taken, and a fresh empty store created at the configured path.

A database holding schema objects but no metadata table with entries is not a store eventd could have written; it is quarantined and replaced like a corrupt one.

The metric store is a required store; there is no degraded mode without one (§8.2).

After opening or creation the series cache is empty and fills on demand (§5.3).

5.4.4 Concurrency #

Exactly one read-write connection, owned by the metric writer thread, and any number of read-only query and maintenance connections. WAL mode permits readers alongside the writer. Retention and adaptive rollups plan or compute with read-only connections and submit bounded commands to the writer; they never open another read-write connection (§3.6, §5.6).

The single-writer property is load-bearing here in a way it is not for the other stores: series resolution checks for an existing row and then inserts, without a transaction spanning both, and only one writer makes that safe (§5.3).

5.4.5 Checkpointing #

The metric writer checkpoints at WalCheckpointPages (§A) in passive mode, and does not block when readers hold pages.

As with the log store, the checkpoint is the durability boundary under synchronous=NORMAL, not merely space reclamation (§9.5).

5.5 Retention

Peios / Reference / eventd / Metric Storage

Metric retention runs on the same background thread as the other two, after the log store (§3.6, §4.4).

Both limits are enforced and the more aggressive wins.

5.5.1 The pass #

  1. Delete rows from samples older than MetricRetentionDays (§A) until none remain.
  2. If MetricRetentionMaxBytes is non-zero and the store's logical live size exceeds it, delete the oldest samples by timestamp until it is within the limit.

The mainline default is 1073741824 bytes (1 GiB); zero is an explicit opt-out rather than the default. 3. Track every series_id whose samples were deleted by either step. 4. Before deleting a sample batch, delete all adaptive rollups belonging to any affected series (§5.6).

5. Delete every series row with no remaining samples.

Logical live size is the same measure as §3.6.

Step 5 removes the definitions of series nobody produces any more, which is the only mechanism that ever removes a series row. A series that stopped receiving samples persists until its last sample is removed. In the absence of size pressure that is ninety days by default; the byte ceiling can remove it earlier.

5.5.2 The longest default #

Ninety days, against fourteen for logs and thirty for events (§A).

A metric sample is small and its value grows with age: a year of CPU utilization is a capacity-planning input in a way that a year of log lines is not. A thousand series sampled every fifteen seconds produce about 5.7 million samples a day, which is a few hundred megabytes in SQLite.

The long age limit therefore does not make storage unbounded. The 1 GiB size default is the safety boundary for a publisher that continually creates new label combinations: eventd still accepts new series, as PSPU requires, but retires the oldest metric data rather than allowing one metric namespace to consume the shared eventd volume.

Installations with a dedicated, externally bounded metric volume can set zero deliberately.

The size decision is made by the retention coordinator, never while a datagram is parsed or a sample is committed. Normal metric persistence therefore pays no size-check cost.

5.5.3 Rollups are not downsampling #

Retention deletes raw samples; it does not replace them with lower-resolution data. Adaptive rollups accelerate repeated queries while their raw sources remain present and valid. They are invalidated before retention removes any source from their series, so they cannot extend the apparent lifetime of data or answer a query after its authoritative samples have expired (§5.6).

A future retention engine can aggregate high-resolution data as it ages — per-second samples becoming five-minute aggregates after a week, hourly aggregates after a month — but that would require a separate versioned storage and query contract.

5.5.4 Batching and reclamation #

The retention coordinator plans with a read-only connection and submits low-priority delete commands to the metric writer.

Each writer-owned transaction deletes at most RetentionDeleteBatchRows, and ingestion is rechecked before the next command. Under urgent size pressure the writer can append one bounded retention delete to a transaction it already has open; retention never takes a writer mutex or opens another read-write connection (§3.6).

VACUUM is never run automatically. Freed pages are recycled and are excluded from the size measure.

5.6 Adaptive Rollups

Peios / Reference / eventd / Metric Storage

Raw rows in samples are always authoritative. The rollups table is a disposable query cache: deleting every rollup can make a query slower, but cannot change its answer. A miss or a stale row is computed directly from raw samples and returned immediately; query execution never waits for the cache to be repaired.

The design protects eventd's primary job. Metric ingestion does not inspect, update, or coordinate with rollups. A query computes a candidate while doing work it already needed for its own answer, and submits that candidate through a bounded non-blocking channel. The sole metric writer considers at most one such command only after the receive queue is idle and the current sample batch is committed.

A full command channel, writer pressure, or any ordinary cache-write failure drops the candidate rather than delaying ingestion.

5.6.1 Eligible queries #

A query can read or seed rollups only when all of these are true:

  • it has SINCE and an explicit AVG_OVER, MIN_OVER, MAX_OVER or SUM_OVER function;
  • the selected output is per series — the selector is bracketed, or it resolves to exactly one series;
  • it has no WHERE predicate or cross-type filter; and
  • AdaptiveRollupMaxRows is non-zero.

The label selector has already selected concrete series and is therefore safe. An unbracketed multi-series query is not eligible because its window result combines series; reusing independently cached averages or extrema would not in general reproduce that result. Predicate and cross-filter shapes remain on the raw path because their result depends on more than the cached series window.

Only complete windows aligned to Unix-epoch multiples of the requested width are cached. Any partial window at either end of the requested range is always read from raw samples. A query uses the cache only when every complete interior window for the series has a valid row, including explicit empty-window rows; otherwise it evaluates that series from raw samples.

This all-or-raw rule keeps the fallback simple and prevents a cache miss from changing transform pairing.

Streaming continuations do not use or seed rollups. They preserve their normal incremental raw-query semantics.

5.6.2 Schema and identity #

Metric schema version 2 adds:

CREATE TABLE rollups (
    series_id INTEGER NOT NULL REFERENCES series(id) ON DELETE CASCADE,
    window_start INTEGER NOT NULL,
    window_width INTEGER NOT NULL CHECK (window_width > 0),
    transform INTEGER NOT NULL CHECK (transform IN (0, 1, 2, 50, 95, 99)),
    function INTEGER NOT NULL CHECK (function BETWEEN 0 AND 3),
    value REAL,
    overflow INTEGER NOT NULL CHECK (overflow IN (0, 1)),
    source_max_sample_id INTEGER NOT NULL CHECK (source_max_sample_id >= 0),
    source_baseline_sample_id INTEGER CHECK (source_baseline_sample_id > 0),
    CHECK (overflow = 0 OR value IS NULL),
    PRIMARY KEY
        (series_id, window_start, window_width, transform, function)
) WITHOUT ROWID;

transform distinguishes no transform, RATE, DELTA, P50, P95, and P99. function distinguishes AVG_OVER, MIN_OVER, MAX_OVER, and SUM_OVER. value is null only for an empty window or a percentile overflow; overflow distinguishes those cases. Empty rows are necessary to prove that a complete cached range really has no missing window.

Opening a version-1 metric store creates the table and its pruning index in one immediate transaction, then records version 2, and continues to version 3 (§5.4).

Unknown versions still fail startup (§5.4, §B).

5.6.3 Validity proof #

Each row records the greatest raw sample id observed inside its window as source_max_sample_id. Before serving it, the query engine proves that the same series and window has no sample with a greater id. A later sample therefore makes the row stale even when its timestamp was backfilled into an old window. An empty window records zero, so its first raw sample also invalidates it.

RATE and DELTA additionally depend on the sample immediately preceding the window. Their rows record that sample's id in source_baseline_sample_id, with null meaning no preceding sample existed. The query engine compares this with the current immediately preceding sample. A new, changed, or deleted baseline makes the row stale.

Retention invalidates all rollups for every series from which it deletes a raw sample before it deletes the sample (§5.5). This is deliberately conservative. The query-time proof remains mandatory: maintenance ordering alone is not a freshness guarantee.

Non-finite cached values are rejected.

As everywhere in metric evaluation, a numeric result must be finite; percentile overflow is represented by the explicit null-and-overflow state instead (§6, PSPU §3.25).

5.6.4 Seeding and bounds #

An eligible raw evaluation can enqueue candidates only after it has scanned at least AdaptiveRollupMinSamples raw inputs. It enqueues no more than AdaptiveRollupBatchRows missing windows, and submission uses try_send on a fixed-capacity channel.

Repeating a wide query gradually fills its cache in bounded pieces without starting a background scanner.

The writer upserts a candidate under the complete cache identity and prunes the oldest window starts until no more than AdaptiveRollupMaxRows remain.

The cap is global to the metric store. It limits this optional acceleration state; it does not delete series or raw samples.

All three controls are live (§A). Setting AdaptiveRollupMaxRows to zero immediately disables cache reads and writes without changing query results.

Adaptive rollups are not downsampling. Raw samples retain their ordinary age and size policy, and every supported query remains answerable from them (§5.5).

5.7 Health Metrics

Peios / Reference / eventd / Metric Storage

eventd records its own health as metrics named eventd.*. They answer the questions an operator asks of a running collector — is it keeping up, is it losing anything, how big are the stores, are queries being turned away — through the ordinary query channel, so they can be charted and compared over time like any other metric.

5.7.1 How they are written #

Every HealthMetricIntervalSeconds (§A), the metric thread takes one sample of every series below and commits it to the metric store. The samples do not travel through the metric socket: there is no datagram, no KACS token, and no EVENTD_PUBLISH check (§7.6), in the same way synthetic events never touch KMES (§2.6). An interval of 0 turns them off.

Health samples obey MetricMaxBatchSize (§5.1). They fill any pending batch up to the size cap captured when it opened; further transactions use the current configured cap (§8.3). The final partial batch is committed immediately. Splitting an interval's samples does not drop or reorder them.

Each sample carries eventd's clock and the current boot ID, like a metric record that omits its timestamp (PSPU §3.11).

The counters count from eventd's start, and so restart from zero whenever eventd does. A reader asks for their RATE or DELTA, which read a decrease as a restart (PSPU §3.10, §3.25).

5.7.2 The series #

NameTypeLabelsWhat it is
eventd.events.storedcountershardEvents committed to each active shard.
eventd.events.lostcountercpuSequences recorded as lost on each CPU, whether KMES overwrote them or a full store refused their batch (§2.5, §9.1). The sum of the ranges in the eventd.events.lost records eventd committed; the metric and the event type share the name.
eventd.kmes.ring.fill.percentgaugecpuHow full each CPU's KMES ring buffer is, as its drain last saw it.
eventd.events.index.shedscounterreasonEvent indexes dropped under write pressure: pressure one at a time, emergency all at once (§3.4).
eventd.logs.storedcounterNoneLog records committed.
eventd.metrics.storedcounterNoneMetric samples committed, these included.
eventd.metrics.series.cachedgaugeNoneEntries in the series cache (§5.3).
eventd.store.bytesgaugestoreBytes each store occupies on disk, its write-ahead logs included: events (every active and historical shard), logs, metrics and metadata.
eventd.store.write.errorscounterstoreFailed writes to each store, the ones the diagnostic dump names the latest of (§8.5).
eventd.retention.deletedcounterstoreRows retention removed from each store (§3.6, §4.4, §5.5).
eventd.queries.activegaugeNoneQueries running, streaming or not.
eventd.queries.streaminggaugeNoneStreaming queries running.
eventd.queries.refusedcounterreasonQueries turned away by MaxConcurrentQueries (machine), MaxStreamingQueries (streaming) or MaxQueriesPerUser (user) (§6.5).
eventd.queries.failedcounterreasonQueries ended by QueryTimeoutMs (timeout) or MaxQueryHeldBytes (held_bytes) (§6.5).

eventd.store.bytes is the space on disk, which is what fills a volume. Size retention compares a store's logical live size instead, which leaves out free pages and the write-ahead log (§3.6), so the two can differ.

5.7.3 Who can read and publish them #

They are read like any metric, through the Metrics descriptors (§7.2). eventd creates Metrics\eventd on first boot, granting EVENTD_READ to SYSTEM, Administrators and Authenticated Users and EVENTD_PUBLISH to nobody. Without it the wildcard's grant would let an administrator's process send samples under eventd.* through the socket and pass them off as eventd's. An administrator who wants them narrower edits that descriptor.

5.7.4 What is left out #

Rejected ingestion input is not counted here: log records with an invalid origin, and metric datagrams without a token, truncated, denied by name policy or carrying the wrong type. Counting that input where a query client can see it is exactly what PSPU §3.4 and §3.12 forbid. Those counts stay in memory and reach only the diagnostic dump (§8.5).

Neither are datagrams the kernel refuses at a full socket queue. eventd is never told about them (§9.1), so it has nothing to count.

6.1 Parsing and Planning

Peios / Reference / eventd / Query Execution

A query arrives as one string (PSPU §3.15). Turning it into an answer has four phases before any data is read: parse, plan, authorize, execute.

6.1.1 Parsing #

The string is parsed into a syntax tree. The parser:

  1. Identifies the mode from the first token — EVENTS, LOGS, or METRIC.
  2. Extracts the primary selector: a type pattern, a FROM list, or a metric name with an optional label selector.
  3. Collects every clause, in whatever order they appear.
  4. Validates that the clauses suit the mode — CONTAINING only in log mode, RATE only in metric mode, SELECT only where a result schema is not fixed.

Parse errors are returned immediately, before anything is opened, read or authorized. A malformed query costs a decode and a parse.

6.1.2 Expression depth #

The parser enforces two independent limits before query execution:

  • Grouping parentheses can nest at most 128 pairs deep.
  • Each boolean expression tree can contain at most 128 nodes on a path from its root to a leaf.

A comparison, membership predicate (IN or NOT_IN), or null predicate (IS NULL or IS NOT NULL) is a leaf with depth 1. An AND or OR node has depth 1 plus its deeper child's depth. Both operators share the same tree limit. Grouping parentheses do not add nodes to the stored tree.

A flat chain of 128 predicates fits the tree limit; a chain of 129 does not. Parentheses around an IN list are list delimiters, not recursive expression grouping. Each WHERE clause is checked separately.

Exceeding either limit returns the parse error expression depth exceeds 128 levels. The caller can simplify the expression or remove redundant grouping and retry. These limits are independent of the query request's byte limit and prevent deeply nested parser and expression-tree traversal from exhausting the worker stack.

6.1.3 What can only fail later #

Some failures need data. The parser cannot know whether a metric name resolves to a counter or a histogram, how many series a selector matches, or whether the effective range exceeds the cross-type lookback limit — those depend on the store, so they surface at planning or execution time (PSPU §3.B).

The practical consequence is that the same query string can parse everywhere and fail on one machine: a metric selector matching one series on a two-core box matches two on a four-core one.

6.1.4 Planning #

Planning resolves what the query will actually touch:

  • which concrete identifiers the data could carry — event types, log origins, metric names — because access control resolves per identifier and a broad selector authorizes nothing by itself (§7.4)
  • which series a metric selector matches, and whether they are type-homogeneous
  • which fields the query references, for both authorization and frequency accounting (§6.5)
  • which stores are involved, including any cross-type source

Identifier discovery reads compact catalogs: the union of every shard's event_types, the log store's log_origins, and the metric store's series rows (§3.1, §4.2, §5.2).

The primary selector filters that set before access checks.

Discovery therefore never runs a DISTINCT scan over a hot records table and does not depend on an adaptive event index being present.

Catalogs can conservatively contain a name whose final retained row was

deleted. That safe superset can cause an extra access check but cannot expose a row or omit a concrete identifier that committed successfully.

Low-priority cleanup is optional and is never query-critical.

6.1.5 Header literal types #

Literal conversion uses the namespace of the record being compared. emitter.class aliases apply only to event headers. GUID forms apply to the event GUID headers, log boot_id and job_id, and metric boot_id. The same spelling in an ordinary payload field or metric label remains a string; it does not borrow another namespace's header type (PSPU §3.22).

The rule holds for comparisons, membership and compound predicates, metric bracket selectors, and metric selectors inside historical or streaming cross-type conditions. A metric condition uses the metric namespace even when the query's primary source is events or logs.

6.1.6 When payloads are decoded #

Event payloads are stored as opaque MessagePack and are never decoded on the write path (§3.1). Decoding happens here, on the read path, and only where a query needs it: to evaluate a payload predicate, to build a flat result record, or to compute a payload expression index's key on insert.

At high result counts this dominates the query path. Constructing flat maps from thousands of events means decoding thousands of payloads and applying the flattening rules of PSPU §3.22 to each. Partial extraction is the lever: with a SELECT present, only the named paths need decoding, and without one a streaming decoder that emits flattened pairs avoids materializing the payload at all (§C).

6.1.7 Read connections #

Execution uses read-only SQLite connections, which in WAL mode do not block writer threads. The one exception is SQLite's own. A reader that catches the wal-index header while a writer is updating it takes the write lock for the moment it needs to read the header again. A writer therefore waits up to 25 milliseconds for the write lock rather than failing a commit at once, and fails only if the lock is held longer.

An event query opens one connection per shard database in the directory (§6.4). A log or metric query opens one. eventd supports concurrent queries up to its admission limit (§6.5), subject to the operating system actually having the descriptors and memory; where it cannot allocate what an admitted query needs, it fails that query rather than blocking a writer or exceeding the limit.

6.1.8 Timestamp fields #

ISO timestamp hour, minute, and second fields must be nonnegative and in range. A minus sign in any of those fields is rejected as a parse error; it does not subtract time from the date.

6.2 Ordering and Tiebreakers

Peios / Reference / eventd / Query Execution

PSPU §3.21 requires every result order to be total and deterministic for a fixed set of stored records, so that SKIP and TAKE page reliably. This is how eventd achieves it.

6.2.1 The tiebreakers #

Where the query's explicit SORT keys — or the mode's default ordering — do not uniquely order two records, eventd appends internal keys until the order is total:

ModeAppended, in order
Eventstimestamp, the column of event.time, descending, shard index ascending, events.id descending
Logstimestamp descending, logs.id descending
Metricstimestamp ascending, metric name ascending, canonical labels ascending, and samples.id ascending where the row corresponds to a raw sample or a derived sample pair

These are not query-language fields. They never appear in a result record, cannot be named in a SORT or a SELECT, and have no access-control identity (PSPU §3.28).

A metric's canonical-label key is captured before field filtering. Hiding a label leaves this internal key intact, including on per-series transformed and aggregate rows, so it does not change their order or pagination. The denied label remains absent from the result. Explicit query references to that label still require field access (§7.4).

The shard index is the numeric identifier from the shard-NNNN.db filename. It appears in the event tiebreaker because rowids are per-database: two events in different shards can share a rowid, and without the shard index the pair would be unordered.

The metric tiebreaker includes name and labels because an unbracketed query merges several series into one output stream, where the timestamp alone does not separate rows from different series.

6.2.2 Why insertion order is never the answer #

samples.id and events.id break ties within one database, but neither is a substitute for the timestamp ordering they follow.

Metric samples can arrive out of timestamp order (§5.1), so insertion order and time order differ. Every metric computation — RATE's consecutive pairs, aggregate window membership, cross-type interval construction — is defined over (timestamp, id) ascending precisely so that a late-arriving sample lands where its timestamp says it belongs rather than where it happened to be written.

Events are less prone to it, since a drain thread reads one ring buffer in order, but a shard receiving from several CPUs interleaves them arbitrarily and a clock step can invert two events from the same CPU.

6.2.3 Value ordering is not SQLite's #

Sorting, grouping and equality all use the query language's semantics, never the storage engine's dynamic-type rules (PSPU §3.20, §3.21).

The divergences are not edge cases. SQLite compares an integer and a real by converting; the query language compares them mathematically and exactly, including beyond binary64's exact integer range. SQLite orders text by byte; the query language folds ASCII case and then falls back to the original bytes only to break a fold-equal tie. SQLite has its own type-affinity ordering across storage classes; the query language fixes its own type order, nulls first, arrays last.

Where a SQL construct cannot reproduce those semantics, eventd uses it only to narrow candidates and applies the real comparison after loading the row (§6.3).

6.2.4 Canonical representatives #

A group whose members are equal under the language's rules but not byte-identical emits the smallest member rather than the first (PSPU §3.21).

Smallest rather than first is what makes the representative a property of the set. An event query merges results from every shard in an order that depends on which shard answered first, so "first" would be nondeterministic across runs of the identical query — which is exactly the property this chapter exists to prevent.

6.3 SQL Translation

Peios / Reference / eventd / Query Execution

Events and logs are translated to SQL. Metrics are translated to SQL against series and samples. Clients never see any of it; the translation is entirely internal and carries no guarantees.

6.3.1 What translates directly #

Event header fields are columns, so a predicate on one can become a SQL WHERE comparison over an indexable column (§3.1). Today one predicate does per shard: the first of event.type == a string, which becomes a comparison of the event_type column, or a comparison of event.cpu or emitter.class with an integer, which compares cpu_id or origin_class, falling back to an indexed payload field (below). Other header predicates, emitter.process.guid among them, are applied after loading. A column's own name in a predicate is a payload field, not the column.

Timestamps bound every read already, through SINCE and UNTIL. A top-level comparison of the record's time with an integer; event.time for events, timestamp for logs; narrows that range further, so a page of older records; WHERE event.time <= T; starts reading at T rather than at the newest record. One inside an OR does not narrow, since it need not hold.

Log fields are all columns; log mode has no payload and its field set is closed (§4.2).

Metric selection resolves names and labels through series; from the in-memory cache where possible; and reads samples for the range, ordered by the composite index that already provides (timestamp, id) (§5.2).

6.3.2 What does not #

Event payload predicates have no column. They become eventd-internal payload extraction predicates, and can use an adaptive payload expression index to narrow candidates (§3.4).

HAS, array containment, narrows nothing. The payload expression index stores one key per field, and a field holding an array of group SIDs has no single key to store, so a HAS predicate is answered by decoding each candidate row and testing its array in full. The operator is correct on every row and costs a scan of whatever the rest of the query left; a query using it wants a time range or another predicate beside it.

The rule governing every such translation is that SQL narrows, the query language decides. Where a SQL construct cannot reproduce a predicate's comparison semantics exactly, eventd uses it only to reduce the candidate set and then applies the real predicate after loading the row.

SQLite's native dynamic-type equality and ordering never substitute for the query language's ASCII case folding, exact numeric comparison, binary comparison, array comparison, or null and missing-field handling (§6.2). An index that returns a smaller set faster is useful; one that returns a different set is a wrong answer arriving quickly.

6.3.3 Where access control sits #

Access filtering is part of the logical execution, not a filter over the output (PSPU §3.18, §3.28). eventd can push authorization predicates down into SQL when the concrete identifier set is known at planning time, or read candidate rows and discard them before aggregating.

Which it does is a performance decision. What is fixed is that the externally visible result is identical to the one filtering-first would produce; aggregates, ordering and pagination included, since all three would otherwise leak the existence of rows the caller cannot read.

6.3.4 Aggregation #

Aggregation is never pushed into SQL. SQL reads the candidate rows, and eventd folds them into groups as they are read (§6.4), under the language's own equality (§6.2) and after access filtering has discarded what the caller cannot read; grouping over columns included, not only grouping over payload paths whose comparison semantics SQL cannot reproduce.

For an event query this means every shard yields its matching rows, so the work is proportional to the row count, while what the aggregation holds is proportional to the group cardinality (§6.4).

6.4 Cross-Shard Fan-Out

Peios / Reference / eventd / Query Execution

Event queries execute against every database in the event store directory — active shards and historical ones alike (§3.3). Log and metric queries touch one database each and need none of this.

Shards carry no meaning for the query path (§2.3). A shard holds whatever CPUs routed to it during whatever lifetimes wrote it, so there is no shard a query can skip on the basis of its contents, and a predicate on event.cpu scans all of them.

6.4.1 Merging #

How results combine depends on the query.

Queries in the default order. A non-aggregating query with no SORT reads every shard at once, each newest first through idx_events_timestamp, and the coordinator takes whichever shard's next row comes first under the tiebreakers of §6.2: an N-way merge of the sorted streams. Each row that passes access control and every predicate is sent as soon as it is taken. Once SKIP + TAKE rows have passed, the merge stops. What the query holds is one row per shard, the merge frontier, whatever the size of its result.

Sorted queries. A SORT on any other field reads the shards in turn and gathers the visible rows. With TAKE it keeps only the best SKIP + TAKE of them, trimming to that whenever it holds twice as many or a thousand, whichever is more. Without TAKE it holds every visible row. Either way it holds them within MaxQueryHeldBytes (§6.5).

Aggregating queries. Rows from every shard fold into one set of groups as they are read, and no row is kept. Each group keeps:

QueryEach group keeps
COUNT BY, TOP N BY, GROUP … COUNTa count; at the end the groups are sorted by count descending and TAKE applies
GROUP … SUMthe exact integer sum while every value is an integer and it fits, and the binary64 sum
GROUP … AVGthe binary64 sum and count, divided once at the end
GROUP … MIN / MAXthe extreme so far
DISTINCTthe value

GROUP … SUM, AVG, MIN and MAX groups are sorted by their keys ascending, in the order the fields are named, before SKIP and TAKE apply. An explicit SORT overrides that order, with group-key order breaking its ties (PSPU §3.21).

AVG is the one that cannot be composed from its own output: averaging partial averages weights each part equally, regardless of how many rows it held, so the sum and the count are kept and divided once.

A group is found by hashing a key that every pair of language-equal values shares — numbers by their nearest binary64, text with ASCII case folded — and then by the language's own equality against each group's representative in the order the groups appeared (§6.2). The hash only narrows the search; equality decides.

What an aggregation holds is bounded by the number of its groups rather than by its rows, within MaxQueryHeldBytes (§6.5).

6.4.2 The unbounded case #

A non-aggregating query without TAKE has no implicit row limit. EVENTS SINCE 7d ago can match millions of rows, all of which pass through the merge.

In the default order that costs time and no memory, so the query timeout is the only backstop (§6.5). The timeout covers sending as well as reading, so a client that reads slowly can run out of time on a result the merge would have finished.

6.4.3 Descriptors #

An event query opens a read-only connection per database, and each SQLite connection holds one or two descriptors for the database and its write-ahead log. With many historical shards this adds up quickly across concurrent queries.

Active shard writer connections stay open for the process lifetime and are not negotiable. Historical shard read connections are the pool worth bounding — opened when a query touches them, closed after a period of inactivity (§C).

6.5 Accounting and Limits

Peios / Reference / eventd / Query Execution

6.5.1 Recording what was asked #

Every event query is recorded by the adaptive indexing system (§3.4). For each WHERE predicate:

  • a header field reference increments the frequency counter of that field's column, kept under the field's path (event.type, emitter.process.guid); event.time, whose column is always indexed, is not counted
  • a payload field reference increments that path's counter

Cross-type WHERE predicates are counted like any other, since they narrow the same data by the same fields.

This applies to event queries only. The log and metric stores have fixed write-time indexes and no candidate space for a policy to explore (§4.2, §5.2), so their queries increment nothing.

Counters are in-memory and are flushed to the metadata database at each policy interval (§3.5). Query handlers never write to that database directly, which is what keeps the once-per-query update off any lock a writer thread contends for.

6.5.2 Concurrency #

eventd bounds concurrent queries — streaming and non-streaming together — at MaxConcurrentQueries (§A).

Beyond it a query is rejected with an error rather than queued.

The per-query cost that limit is protecting is real: read-only SQLite connections, one per shard for an event query (§6.4), memory for the merge, and CPU for execution and payload decoding.

MaxStreamingQueries is enforced separately and is lower. A streaming query holds its resources for as long as its client stays connected, where an ordinary one holds them for at most a timeout, so the two populations need different bounds.

Both are global. Every authenticated caller can connect (§7.1), so eventd also bounds the queries one caller can have running at once, at MaxQueriesPerUser. The caller is the user SID of the token read at connect. The slot is taken as soon as the token is read, before the request, so connections held open without a query count too. SYSTEM's queries are not counted: SYSTEM is the machine, not one caller among others. Over the limit, the query is rejected with an error, as over the global ones.

The per-user limit counts users, not processes or sessions: two windows of the same person share one budget, and two people never share one.

Queries and ingestion are separate channels, so exhausting the query side cannot exhaust ingestion (PSPU §3.3).

6.5.3 Memory #

eventd can not be killed: it runs with oom_score_adj −1000, so if its memory alone fills the machine, the kernel has nothing left to reclaim and panics. What bounds a query's memory therefore has to hold however many queries run at once.

A query in the default order holds one row per shard and nothing more (§6.4), and is never refused for the size of its result (PSPU §3.16).

Everything else a query must hold — a sorted query's rows, an aggregation's groups, a watch batch — counts against MaxQueryHeldBytes (§A), one budget for every running query together. A query takes from it in 64 KiB granules as it grows, gives back what it does not need when a sorted query trims, and gives back all of it when it ends. A query that would take more than is left fails with an error, rather than being truncated or answered from part of the data.

What a row or group costs is estimated from its fields and values, not measured from the allocator, so the budget is approximate. It is still a bound: with the default of 256 MiB, no number of concurrent queries holds much more than that.

A metric query reads each series' samples in order and holds none of them: a transform keeps only the sample before, and an aggregation folds each sample into its window, or its series, as it is read. What it holds is what its result needs, and that counts against the same budget: the matched series, one fold per window or per series, the latest point of each series, and the result rows. A query whose result is the samples themselves — a range without an aggregation — holds them all, and is refused when they pass the budget like a sorted query. A window aggregation over the same range holds one fold per window, however many samples fall in it.

6.5.4 Request and response sizes #

eventd rejects an inbound frame above MaxQueryRequestBytes before allocating or reading its payload.

Outbound result records are grouped at record boundaries toward QueryResponseTargetBytes (§A).

The target is not a limit: a complete record that exceeds it is sent alone, never split, truncated, skipped or failed merely for exceeding the target (PSPU §3.15–§3.16). Only the protocol's u32 frame length is a hard outbound bound.

6.5.5 Timeouts #

Every query has a maximum execution time, QueryTimeoutMs (§A).

The clock starts once the request has been decoded and the caller's token obtained, and covers everything after: parsing, planning, access checks, cross-type pre-computation, SQL execution, merging, aggregation, pagination, projection, and transmitting the initial result set.

It bounds the initial result set only. A non-streaming query sends end before it expires; a streaming query sends watch. Past watch the stream is not time-limited, and what bounds it instead is MaxStreamingQueries, MaxDistinctStreamValues and backpressure (§6.6).

On expiry eventd cancels the query and sends an error.

Any result messages already sent are discarded by the client, since no terminal message arrived (PSPU §3.16).

Cancellation has to reach two kinds of work. SQLite work is interrupted through sqlite3_interrupt or an equivalent progress-handler check — the same responsiveness problem as canceling an index build (§3.4). Non-SQL work — MessagePack flattening, the cross-shard merge — checks the same deadline periodically, because a query can spend most of its time in neither the database nor the kernel.

Large scans over unindexed fields are the main timeout risk, and the adaptive indexing system reduces it over time by indexing whatever keeps being filtered on — which is also why a timeout is a signal worth watching rather than merely an error to retry.

6.6 The Streaming Machinery

Peios / Reference / eventd / Query Execution

The externally visible behavior of a streaming query — what can be streamed, what applies during the watch phase, how DISTINCT streams behave, and when a slow client is dropped — is PSPU §3.27. This is the machinery underneath.

6.6.1 Commit generations #

eventd keeps a monotonic u64 commit generation counter for each streamable store: one for the event store as a whole, and one for the log store.

Metric queries do not stream, so the metric store has none.

After a writer commits a batch it increments the counter for its store and wakes the streaming handlers waiting on it.

A handler records the last generation it processed and waits until the counter exceeds it.

The event counter covers the whole store rather than one per shard. Several writer threads increment it, so a wake is "something committed somewhere" and a handler re-examines every shard it cares about — which is what it would have to do anyway, since a shard means nothing to the query path (§6.4).

The counter is process-local and never persisted; it has no meaning across a restart, and a streaming query does not survive one.

On wraparound the next increment is treated as a wake for every handler and operation continues. At any commit rate a machine can sustain, wraparound of a 64-bit counter is not reachable.

6.6.2 Record order within a watch batch #

The initial result set uses the query's usual sorting and pagination. During the watch phase, newly visible event records are delivered by shard ordinal ascending, then database record ID ascending; log records are delivered by database record ID ascending. SORT, SKIP, and TAKE do not reorder or trim these watch records.

DISTINCT watches consider values in this same order. The first unseen value is emitted using its first record's representation; equivalent later values are suppressed by the stream's seen set. The initial distinct result retains its usual value ordering.

Record IDs preserve insertion order within each store. Event shards commit independently, so there is no durable total chronological commit order across shards. Shard ordinal supplies a deterministic order within each observed batch; successive batches follow the stream cursor. A batch can include several commits observed together. Producer timestamps do not change delivery order, even when they arrive out of order.

6.6.3 Latency #

Delivery latency is bounded below by the commit interval of the store concerned, because a record is not streamable until it is committed.

StoreApproximate floorFrom
EventsMaxBatchLatencyMs, default 100 ms§2.4
LogsLogMaxBatchLatencyMs, default 500 ms§4.1

Under light load the actual latency is lower, because the adaptive batcher commits as soon as its input drains rather than waiting out the cap (§2.4). Under sustained load it converges on the cap.

A consumer needing better than this is not served by eventd at all: the KMES ring buffers are the low-latency path, they are specified in PSPK, and attaching to them directly costs the per-event access control that eventd exists to apply (§7).

6.6.4 The DISTINCT seen set #

A DISTINCT stream holds a per-query set of the values it has already emitted, initialized from the initial result set and added to as new values appear (PSPU §3.27).

It is bounded by MaxDistinctStreamValues (§A), and exceeding the bound terminates the query with an error rather than evicting.

Eviction would make the output wrong rather than merely truncated: a forgotten value would be re-emitted as newly seen, and "newly seen" is the entire meaning of the result.

The set is per query and in memory, which is why the bound exists and why it is separate from the general query concurrency limit — sixty-four streams each holding a hundred thousand values is a different memory profile from sixty-four ordinary queries.

6.6.5 Cross-type re-evaluation #

Pre-computed cross-type ranges describe the past and are discarded when the watch phase begins (PSPU §3.27).

A metric condition costs one index seek per batch: the selector has already been constrained to exactly one series, so finding the active sample at the batch's latest candidate timestamp is a single lookup on idx_samples_series_timestamp (§5.2).

An existence condition is evaluated per candidate record rather than per batch, because the centered window is relative to each record's own timestamp and a matching record can be near some of a batch and not the rest.

The per-batch metric evaluation is an approximation, and the reason it is acceptable is the ratio between the two intervals: a commit batch spans a fraction of a second and a metric sample fifteen, so every record in a batch normally maps to the same sample. At sub-second metric resolution it filters more coarsely, and records near a threshold crossing are included or excluded as a group.

6.6.6 Backpressure #

Backpressure is detected on the socket send buffer. When a result message cannot be sent because the buffer is full, the query is terminated immediately; eventd never blocks on the send.

Blocking would put a slow reader in the path of eventd's own work, and the write path is what would suffer. A streaming client is the lowest-priority consumer of eventd's time, and dropping it is the same principle as dropping an ingestion datagram (PSPU §3.4), applied on the way out.

6.6.7 Commit notifications #

The commit notification counter changes while holding the same mutex used by a waiting query. This prevents a commit from falling between a query's last counter check and its condition-variable wait. Queries still inspect committed storage after waking; a notification does not carry a result.

7.1 The Model

Peios / Reference / eventd / Access Control

eventd authorizes queries using kernel access control subsystem (KACS) security descriptors and access-check operations. Every query is evaluated against descriptors that determine which records — and which fields within a record — the caller can see, and everything else is filtered out silently (PSPU §3.28).

7.1.1 eventd decides nothing itself #

eventd implements no access check logic of its own. Every decision is delegated to kacs_access_check and kacs_access_check_list, which run the full KACS AccessCheck pipeline: integrity checks, restricted token evaluation, confinement, conditional ACE evaluation, and the SACL audit walk.

What eventd contributes is the three things AccessCheck needs and cannot know — which descriptor applies (§7.2), which object type list describes the record (§7.3), and what the caller's token is (§7.4) — and then it acts on the verdicts.

The alternative would be reimplementing an access check algorithm that already exists, in a daemon that would then have to be kept in agreement with it forever.

7.1.2 Enforcement is at query time #

Records admitted by ingestion are stored independently of who is allowed to read them, and two callers querying the same store see different results.

Three reasons make this the only workable arrangement:

  • Audit integrity. An audit event has to be stored whether or not anyone can read it. Filtering at storage time would let a descriptor decide what gets recorded, which is the one thing an audit store must not permit.
  • Descriptors change. An administrator can grant or revoke access retroactively, and only query-time evaluation makes that meaningful.
  • Callers differ. Several principals with different access levels query the same store, and there is one copy of the data.

7.1.3 Who can connect #

The query socket lets every authenticated caller connect: its descriptor is D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;OW)(A;;FW;;;AU), set in place of the one it would inherit from eventd's closed runtime directory.

What a caller can read is decided by eventd, per identifier and per field, against the descriptors below, not by the socket. A socket that admitted fewer callers would only leave a grant to anyone else unusable. How many queries one caller can hold is bounded per user (§6.5).

7.1.4 Caller identity #

When a client connects to the query socket, eventd obtains its token by reading the peer-token socket option (getsockopt(SOL_KACS, KACS_SO_PEER_TOKEN)) on the connected descriptor. The token represents the peer's identity as captured at connection time.

If the call fails, eventd denies the query entirely. It has no fallback identification and no anonymous mode. A client that connects at the Anonymous impersonation level conveys the Anonymous token (S-1-5-7), and eventd answers it with an error and closes the connection, whatever a descriptor would grant Everyone.

The snapshot property matters most for streaming queries, which can run indefinitely: a client whose group memberships change, or whose access is revoked, continues to be evaluated against the token it connected with until it disconnects (§7.5).

7.1.5 Rights #

RightBitValueMeaning
EVENTD_READ00x0001Read records matching the pattern.
EVENTD_CLEAR10x0002Delete records matching the pattern.
EVENTD_ADMINISTER20x0004Change eventd's own policy — the INDEX command (§7.2).
EVENTD_PUBLISH30x0008Publish metric records under the matching name (§7.6).

The generic mapping passed to AccessCheck is in §B.

EVENTD_ADMINISTER is distinct from EVENTD_READ deliberately. Accelerating a field costs write throughput on every record thereafter, so INDEX is a way for a caller to degrade the system for everybody, and a caller permitted only to read has not been permitted to do that (PSPU §3.23).

Note

EVENTD_CLEAR is defined and nothing yet uses it: no operation deletes records on a caller's behalf, and retention deletes on nobody's behalf (§3.6). It is reserved for administrative deletion. The consequence worth knowing is that a descriptor written today with GENERIC_WRITE already grants it, and will start granting a real capability the moment one exists.

7.1.6 What is not controlled here #

Event emission is KMES's: kmes_emit and kmes_emit_batch require SeAuditPrivilege, and eventd is not involved.

Log ingestion admits the trusted output broker at its socket. Metric ingestion checks the sender's effective token and the EVENTD_PUBLISH right for every metric name (§7.6). Read grants do not grant publication rights.

7.2 Patterns and Descriptors

Peios / Reference / eventd / Access Control

Access is defined on named patterns, each standing for a category of observability data and each carrying a descriptor. The three data types have independent pattern namespaces:

NamespacePatterns match
Eventsevent type
Logslog origin
Metricsmetric name

7.2.1 Matching #

A pattern matches by dot-delimited prefix.

The pattern kacs matches the exact string kacs and any string beginning kacs. — and matches neither kacs_extended nor kacsfoo, because the dot is the hierarchy separator and not a mere character.

* is the wildcard default and matches everything.

Ingestion constrains metric names to the identifier grammar and origins to that grammar plus a producer component (PSPU §3.7, §3.10), which is what keeps a producer from choosing a name containing the wildcard or a backslash — a name that would otherwise match a rule its producer was never meant to satisfy, or store its descriptor somewhere other than where the administrator who wrote it believes.

An origin naming a producer within a service — jellyfin/HealthCheck, jobs/<guid> — resolves from the part before the slash, so the matching above starts at jellyfin and at jobs. A service's hooks, reload commands and health checks therefore answer to the descriptor written against the service itself, and every submitted job's output answers to one descriptor at Logs\jobs.

The slash never enters a descriptor path, which is what keeps it out of the registry namespace it would otherwise be a separator in.

7.2.2 Resolution #

For a concrete identifier, eventd resolves the applicable descriptor by walking up the hierarchy:

  1. Look for an exact match on the full identifier, kacs.audit.access.checked.
  2. Remove the last dot-separated component and look again, kacs.audit.access.
  3. Repeat: kacs.audit, then kacs.
  4. Fall back to the wildcard, *.

The first match wins; a more specific pattern overrides a less specific one.

7.2.3 Storage #

Descriptors are registry values under the eventd security subtree:

Machine\System\eventd\Security\Events\*
Machine\System\eventd\Security\Events\kacs
Machine\System\eventd\Security\Events\kacs.audit.access.checked
Machine\System\eventd\Security\Logs\*
Machine\System\eventd\Security\Logs\loregd
Machine\System\eventd\Security\Metrics\*
Machine\System\eventd\Security\Metrics\cpu
Machine\System\eventd\Security\Admin

Each type's wildcard default is load-bearing. If a default is missing, eventd denies access to all data of that type: resolution that reaches the end of the hierarchy without a match is a denial, not a grant (PSPU §3.28).

Storing them in the registry rather than in eventd's own databases means the registry's access control protects them, and an administrator edits them with the ordinary registry tools rather than through eventd.

7.2.3.1 Who can change them #

A descriptor is stored whole, as one value, SACL included. Whoever can write that value can therefore replace the SACL as well as the DACL, and removing a SACL this way needs no SeSecurityPrivilege: the registry checks the right to set the value, not the right to change audit policy.

Write access to the Security subtree is therefore audit-policy authority, and only those trusted to change audit policy should hold it. A tool that edits a descriptor's DACL must write the SACL back unchanged.

eventd gives Machine\System\eventd\Security a protected DACL: SYSTEM and Administrators full control, Authenticated Users read, which is what eventd and its clients need to resolve descriptors. Protection stops a broader grant on Machine\System\eventd, such as one made to let someone tune eventd, from reaching the audit policy. eventd sets it only while the key's DACL is still wholly inherited, so an administrator's own choice there is never overwritten.

7.2.4 Defaults on first boot #

eventd creates the three wildcard keys, the descriptor for its own health metrics and the administrative descriptor if they do not exist:

KeyDefault
…\Security\Events\*SYSTEM and Administrators: EVENTD_READ on all fields.
…\Security\Logs\*SYSTEM, Administrators, and Authenticated Users: EVENTD_READ.
…\Security\Metrics\*SYSTEM and Administrators: EVENTD_READ | EVENTD_PUBLISH; Authenticated Users: EVENTD_READ.
…\Security\Metrics\eventdSYSTEM, Administrators, and Authenticated Users: EVENTD_READ; nobody EVENTD_PUBLISH, because eventd writes its own health without the socket (§5.7).
…\Security\AdminSYSTEM and Administrators: EVENTD_ADMINISTER.

Every one of the five also carries a SACL with one failure-audit ACE for Everyone, covering EVENTD_READ, EVENTD_ADMINISTER and EVENTD_PUBLISH, and nothing else: a check under a default descriptor that is denied any of them is audited, whoever made it, and a granted one is not (§7.4).

The asymmetry reflects sensitivity. Events include security audit data and are restricted to administrators; logs and metrics are operational data and are readable by any authenticated user. Publication is fail-closed for ordinary services until a more-specific pattern grants their service SID EVENTD_PUBLISH (§7.6). An administrator can tighten either side independently.

On upgrade, eventd replaces a stored descriptor only when its binary form exactly matches a default an earlier eventd shipped at that key: the Metrics wildcard's former read-only default, and each key's former default without a SACL. Those are replaced by the current default, SACL and all. A value an administrator changed is never treated as a default and never rewritten.

7.2.5 Conditional ACEs #

Descriptors on eventd security objects can carry conditional ACEs, and KACS evaluates them as it would anywhere.

eventd passes no eventd-specific local claims to AccessCheck: local_claims_ptr is null and local_claims_len is zero. Conditions referencing token claims that KACS itself supplies still evaluate; conditions referencing eventd-local claims observe them as absent.

A stable set of eventd-local claims — the event's type, the log's origin, the time of day — is a plausible later addition, and defining one is a commitment to keep those claim names meaningful thereafter.

7.2.6 The administrative descriptor #

INDEX (PSPU §3.23) is checked against Machine\System\eventd\Security\Admin, with EVENTD_ADMINISTER as the desired access. Its default grants SYSTEM and Administrators.

eventd refuses INDEX outright if no administrative descriptor exists, by the same fail-closed rule as the read path. Keeping it in the registry means the registry's own descriptor protects the policy and a recreated eventd-meta.db cannot reset it (§3.5).

7.3 Per-Field Control

Peios / Reference / eventd / Access Control

A descriptor can grant read access to some fields of a record and not others, using KACS object ACEs and object type lists. A caller authorized for a pattern but not for a field receives the records with that field absent — indistinguishable from a record that never carried it (PSPU §3.28).

7.3.1 Object type lists #

For each access check eventd builds an object type list: a tree with the data type's root at level 0 and, beneath it, the fields' dotted paths, one node per segment. subject is at level 1, subject.token at level 2, subject.token.sid at level 3.

A field's node is the one at the end of its path, and every node above it is a prefix of the path, ending before a ., named as a field would be (below): the node for subject.token has the GUID of the name subject.token. A prefix that several fields share is one node, so the list names no GUID twice, and the list is in preorder, each node's subtree directly after it, as KACS requires.

Level 0: root GUID for the data type
  Level 1: event
    Level 2: event.time
    Level 2: event.type
    Level 2: event.cpu
  Level 1: emitter
    Level 2: emitter.class
    Level 2: emitter.token
      Level 3: emitter.token.guid
    Level 2: emitter.true-token
      Level 3: emitter.true-token.guid
    Level 2: emitter.process
      Level 3: emitter.process.guid
  Level 1: access
    Level 2: access.granted
  Level 1: subject
    Level 2: subject.token
      Level 3: subject.token.sid
  Level 1: source
    Level 2: source.name

The list is as deep as the deepest path, with no level limit. MS-DTYP's object type lists stop at level 4; KACS sets no depth limit, only one on the number of nodes, 1024 to a list (KACS_ACCESS_CHECK_MAX_OBJECT_TYPE_COUNT). Every prefix counts toward it. A record whose list would be longer cannot be checked, and a query reaching one fails rather than showing it.

A name with no . — a log field, a fixed metric field, most metric labels — is a node at level 1. A metric label key can contain ., and is then a path like any other: a label disk.read is beneath the node disk.

kacs_access_check_list returns a verdict per node, and eventd uses the verdict on each field's node to include or exclude that field. The verdicts on the prefix nodes are not used.

The three root GUIDs — one for events, one for logs, one for metrics — are in §B.

7.3.2 Field GUIDs are derived, not registered #

A field's GUID is computed deterministically with UUID v5 (RFC 4122):

field_guid = uuid_v5(EVENTD_FIELD_NAMESPACE, field_name)

with the namespace UUID in §B, and field_name the field's query-language name as UTF-8.

There is no registry of field GUIDs and no allocation step. The same name always yields the same GUID, so an administrator writing a descriptor computes the GUID from the field name with the same algorithm that eventd will use when it builds the list.

This is the one part of eventd's access control that a third party reproduces rather than merely consumes.

Derivation rather than registration is what makes payload fields tractable at all: event payload schemas belong to the emitting subsystems, eventd has no catalog of them, and a new event type carrying a new field needs no registration anywhere before a descriptor can name it.

Which names are used:

Datafield_name
Event header fieldits field path (PSPU §3.22) — event.time, event.type, event.cpu — never its column's name
Event payload fieldthe flattened dot path — access.granted, subject.token.sid, source.name
Log fieldthe column name — origin, message, is_error
Fixed metric fieldtimestamp, boot_id, name, type, value
Metric labelthe label key — core, device

Payload fields suppressed by flattening or by a header collision — a value or map at a header field's path — are not query-language fields, so they get no GUID (PSPU §3.22). A GUID naming a header field's path is the header field's, whatever the payload holds there.

A descriptor written before header fields were named by path, granting timestamp or cpu_id by GUID, now grants the payload field of that name rather than the header field, because the GUID is the name's. Such a grant must be rewritten with the path to keep its meaning. Metric label keys cannot collide with the fixed metric fields, because ingestion rejects records whose labels do.

7.3.3 The GUID does not encode scope #

A field GUID names a field and nothing else. access.granted produces the same GUID whatever event type carries it.

Scoping comes from the descriptor hierarchy: an object ACE naming the access.granted GUID inside the descriptor for pattern kacs means "the access.granted field of KACS events". The same ACE in a different pattern's descriptor means the same field of that pattern's records.

7.3.4 Granting a subtree #

An object ACE applies to its node and to every node beneath it, so an ACE naming a prefix applies to every field whose path it begins: subject covers subject.token.sid, subject.process.pid, and any subject field an emitter adds later. The header fields are paths like the rest: event covers every event.* header field, and emitter every emitter.* header field together with the payload fields beside them, such as emitter.process.pid.

KACS decides each node once, first ACE first. A field can therefore be read when, of the ACEs that match the caller and name its GUID, the GUID of any prefix of its path, the data type's root, or no object type at all, the first in DACL order to decide EVENTD_READ allows it.

Neither the more specific nor the more general ACE wins as such:

DACL, in ordersubject.token.sidsubject.process.pid
deny subject, allow subject.token.siddenieddenied
deny subject.token.sid, allow subjectdeniedread
allow subject.token.sid, deny subjectreaddenied

A canonically ordered DACL (PCDS §5.5) puts every deny before every allow, so there a deny anywhere on a field's path hides it.

A deny on a field does not reach its siblings: denying subject.token.sid leaves subject.token.auth-id and subject.process.pid as the rest of the DACL decides them, and denying subject.token hides every token field and leaves subject.process. KACS does carry a deny up to the node's ancestors, and a grant up to a node all of whose children are granted, but only onto the prefix nodes and the root, never onto another field.

A field can also be a prefix of another in the same record, since a payload is opaque: a payload value at emitter sits beside the header's emitter.class. Its node in the record's list then has nodes beneath it, whose grants and denies KACS carries up to it. eventd therefore checks such a field again in a list of its own, holding only its prefixes and itself, and uses that verdict, so that the same first-ACE rule decides it as decides any other field.

A descriptor written before the list was a tree keeps its meaning for every field it names by full path: that field's GUID, and so its node, is unchanged. What is new is that an ACE naming a prefix, which named a node in no list before, now covers the fields beneath it.

7.3.5 Writing one #

An object ACE with no object type GUID applies to the root and therefore to every field. One with a field GUID applies to that field.

To grant a security team full read access to KACS events, and a monitoring team only the time, type and CPU:

  • Allow SecurityAdmins, EVENTD_READ, no object GUID
  • Allow MonitoringTeam, EVENTD_READ, object GUID = event.time
  • Allow MonitoringTeam, EVENTD_READ, object GUID = event.type
  • Allow MonitoringTeam, EVENTD_READ, object GUID = event.cpu

MonitoringTeam querying KACS events receives records containing exactly those three keys. Payload fields, identity GUIDs, and the remaining header fields are absent.

To let an auditing team see who acted but not the token's groups:

  • Deny AuditTeam, EVENTD_READ, object GUID = subject.token.groups
  • Allow AuditTeam, EVENTD_READ, object GUID = event
  • Allow AuditTeam, EVENTD_READ, object GUID = subject

AuditTeam receives every event.* header field and every subject field except subject.token.groups.

7.3.6 Building the list per record #

The list is constructed from the fields actually present in the record being checked: the root node, then the tree of their paths.

Event records contribute every header field plus every non-suppressed flattened payload field present in that particular payload.

Different event types produce different lists, because they carry different payloads — and two events of the same type can too, since a payload is opaque MessagePack and nothing requires two of a type to agree.

Log records have a fixed field set — timestamp, origin, is_error, message, job_id, boot_id — so the list is the same for every log record.

Metric records contribute the five fixed fields plus the series' label keys, which vary per series.

Derived aggregate outputs — count, sum, avg, min, max — are omitted from the list entirely. They are not source fields, have no GUID and no access identity of their own, and are visible when the caller is authorized for the records and source fields they were computed from (PSPU §3.28).

7.3.7 Metric aggregate headers #

A metric aggregate or window result does not restore timestamp, name or type if source-field authorization removed that header. The private time used for window placement and ordering is independent of the returned record, so hiding timestamp does not change the numeric result or move samples into another window.

When an output combines several contributing series or metric identifiers, each returned header must be visible in every contributing source. A first contributor with broader access cannot restore a header denied by another. Per-series output retains each series' own visibility. This also applies to latest-value aggregates, transformed windows, and cached rollup results: a cached value does not bypass the current source-field check. Explicit references to a denied field still filter the source records as specified by PSPU §3.28.

7.4 Enforcement

Peios / Reference / eventd / Access Control

The order in which eventd evaluates a query is fixed (PSPU §3.18), and access control is the third phase — before predicates, transforms, grouping, aggregation, ordering and pagination. What follows is the sequence within that phase.

  1. Obtain the caller's token from the connection (§7.1). Failure denies the query.
  2. Parse the query to establish its data sources and filters (§6.1).
  3. Discover the concrete identifiers the query could touch — event type strings, log origin strings, metric name strings. A broad selector authorizes nothing by itself: EVENTS, EVENTS kacs.*, LOGS without FROM, and METRIC cpu.* are each resolved identifier by identifier.
  4. Resolve and check each discovered identifier: find its descriptor by hierarchical matching (§7.2), and build the object type list for the fields the query references (§7.3). A query that references none asks instead about every field the descriptor's allowing object ACEs name, since those can make its records visible though the query names none of them; a GUID does not say its path, so each is a level-1 node of that list. Call kacs_access_check_list, and cache the verdict for this (token, identifier, field set) (§7.5).
  5. Apply record verdicts. An identifier is invisible when the caller can read neither its root nor any field: its records are excluded from the logical row set before aggregation, ordering, pagination and formatting. One whose root is denied but some field granted stays, for its records to be shaped to those fields (step 10). For a cross-type source, a denied identifier is treated as having no matching data.
  6. Apply field verdicts to predicates. Where the query references a field in a predicate or shaping clause and a matching identifier does not grant it, that identifier's records contribute nothing — exactly as if its root had been denied. The query is not rejected.
  7. Cross-type sources get the same treatment. An invisible identifier, or a denied field needed to evaluate the condition, makes the condition evaluate as though no matching cross-source data existed.
  8. Execute, with root filtering already part of the logical row set.
  9. Re-resolve per result identifier. For each distinct concrete identifier in the resulting rows, resolve its descriptor, build the object type list with field GUIDs, call kacs_access_check_list with the token, the descriptor, EVENTD_READ, the list and an audit context naming the pattern the descriptor was resolved from (below), and cache the per-field results.

10. Shape each record. Look up the cached results for its identifier and fields. Exclude the record entirely if neither the root nor any of its fields was granted; otherwise include it, with each field only if its node was granted. A grant of the root alone grants every field, since an ACE with no object type applies to the whole tree (§7.3). A grant of some fields alone gives records holding exactly those fields, and a record carrying none of them is excluded.

7.4.1 Which clauses count as referencing a field #

Step 6 applies to every clause that reads a value rather than merely displaying one:

  • ordinary WHERE predicates
  • metric label filters in a primary selector
  • GROUP, COUNT BY, TOP N BY, SORT, and DISTINCT fields

  • event and log aggregation arguments — SUM, AVG, MIN, MAX
  • metric transforms and terminal aggregations, all of which read the fixed value field: RATE, DELTA, P50, P95, P99, AVG, MIN, MAX, SUM, AVG_OVER, MIN_OVER, MAX_OVER, SUM_OVER
  • a metric boot filter, which reads boot_id; and an explicit metric type predicate, grouping, sort or distinct, which reads type

SELECT is not on this list. It shapes output and is applied last, so a field it omits was still available to every earlier phase — and conversely, selecting a field the caller can not read removes the field, not the record.

7.4.2 Denial is silent, not fatal #

Step 6 excludes rather than rejects, and this is the decision most worth being explicit about, because rejecting is the more informative behavior and that is exactly the objection to it.

A rejection would tell the caller that some identifier exists, matches its query, and carries a field it can not read — three facts about data it was not permitted to see, delivered by the mechanism meant to withhold them, and enumerable by trying queries and watching which ones fail. Excluding costs the caller a result narrower than it appears; rejecting costs the model the property it rests on.

Cross-source fields already worked this way (step 7); primary-source fields now match them.

7.4.3 Field authorization does not depend on presence #

A field's authorization is resolved from the name as written, against each concrete identifier, whether or not any record of that identifier actually carries it.

Payload fields vary between records of the same type, so a rule turning on presence would require the scan that authorization is meant to precede.

7.4.4 Internal values are not fields #

Row identifiers, series identifiers, ordering tiebreakers, and series type checks are not query-language source fields unless the mode exposes them as fixed fields or the query names them (§6.2). Errors raised by internal checks never carry a denied field's value.

A metric result's value is a source field, because it is either a raw sample or a scalar derived from raw samples.

7.4.5 Filtering is part of the logical result #

Access filtering is not a presentation step. Aggregating, ordering or paginating over unreadable records would leak them through counts, through ordering, and through the gaps in pagination.

eventd can push authorization predicates into SQL when the identifier set is known, or read candidates and filter them before aggregating (§6.3). The externally visible result is identical to filtering first, and COUNT, COUNT BY, TOP N BY and every other aggregate reflect only what the caller can see.

7.4.6 The audit trail #

Whether an access check produces a KACS audit event is decided by the SACL audit walk in the AccessCheck pipeline, against the descriptor's SACL. Every default descriptor eventd creates carries a failure-audit ACE for Everyone at every eventd right (§7.2), so out of the box every denied check produces a kacs.audit.access.checked record, and a granted one produces none unless an administrator adds a success ACE.

KACS writes such a record from the AccessCheck syscall only when the caller holds SeAuditPrivilege enabled. eventd's service definition requires that privilege, and its token holds it enabled; without it the check would be made and nothing recorded.

eventd passes each check an audit context naming the object it guards, in the form PGSS §6.7 defines: a MessagePack map of the object's kind and, under the kind's own name, the pattern whose descriptor was checked.

CheckAudit context
Reading events{kind: "event-namespace", event-namespace: {pattern: "kacs"}}
Reading logs{kind: "log-namespace", log-namespace: {pattern: "loregd"}}
Reading or publishing metrics{kind: "metric-namespace", metric-namespace: {pattern: "cpu"}}
INDEX (§7.2){kind: "eventd-admin"}

The pattern is the one the descriptor was found under (§7.2), not the identifier asked about, and for a log origin it never holds the producer after a /. KACS copies the map into its kacs.audit.access.checked record as object.kind and object.<kind>.pattern, and marks the record with fields.attestation.userspace, since those values are eventd's claim. The audit trail therefore records exactly which observability data was read, by whom — the client, as subject.* — rather than merely that eventd performed a check. Reading and publishing a metric name the same object; the record's access.requested says which was checked.

Those audit events are themselves KMES events, which eventd consumes and stores, and which are governed by the event patterns like any other, under kacs (§7.2). Reading the audit store is auditable.

7.5 Caching

Peios / Reference / eventd / Access Control

An access check is a syscall through the full AccessCheck pipeline. A query returning ten thousand records cannot afford ten thousand of them, so results are cached — at two levels, plus the descriptor resolution underneath both.

7.5.1 Record-level #

Verdicts are cached for the life of one query — for a stream, the whole stream — under the connection's token (§7.1), and keyed by concrete identifier, not by pattern: two event types under one pattern are two keys. When a descriptor contains no object ACEs, the check is a plain grant or deny on the root, so every check of an identifier reaches the same verdict.

Each identifier costs one pre-check before any record is read, for the fields the query references (§7.4 step 4), and one result check for each distinct field set its records carry (§7.4 step 9). A query returning ten thousand events across twenty event types, each type's records of one shape, performs at most forty checks.

7.5.2 Field-level #

When the descriptor does contain object ACEs, the verdict depends on which fields the record carries, since different payloads produce different object type lists (§7.3). The result check is therefore cached per (identifier, field set), and is so whatever the descriptor holds.

In practice events of one type carry the same fields, so this is effectively one result check per event type. Log records have a fixed field set, so a log query reaches two checks per origin: the pre-check and one result check. Metric records vary by series label keys.

The pathological case is an event type whose payload fields differ from record to record, which produces a distinct field set — and a distinct cache entry, and a distinct syscall — for each shape encountered.

7.5.3 Descriptor resolution #

Resolving a pattern to a descriptor is itself cached, across queries rather than within one, since it costs a registry read and a hierarchy walk (§7.2).

eventd watches the security registry subtree and invalidates cached resolutions and cached check results when a descriptor changes. That is what makes a revocation take effect on the next query rather than at the next restart.

If the registry watch fails after startup, eventd discards the descriptor cache and operates fail-closed for new resolutions until the watch is re-established.

A cache it cannot trust to be current is worse than none: continuing to serve from stale entries would make a revocation silently ineffective, and the failure would be invisible. With the cache discarded every resolution is new, so the descriptors resolved before the failure are not kept either. This is a degraded state, not a failure — eventd keeps ingesting and keeps answering queries, which see no records until the watch is re-established (§9.3).

7.5.4 During a stream #

Verdicts reached for a streaming query's initial result set are reused through the watch phase, with two exceptions.

A new concrete identifier appearing in a streamed batch — an event type or log origin not present in the initial results — is resolved and checked before the record or its distinct value is used. It has never been authorized, and inheriting a verdict from a sibling pattern would be a grant nobody made.

A descriptor change invalidates the cache as it does anywhere, and subsequent batches are re-checked against the new one.

The token is not re-examined. It was captured at connection (§7.1), so a client whose memberships change mid-stream continues under what it connected with, and a client whose access is revoked keeps receiving records until it disconnects. The bound on that exposure is the client's own connection lifetime, which for a dashboard can be days.

Note

Re-obtaining the peer token periodically would narrow the window, and would also mean a streaming query could change what it returns halfway through for reasons the client cannot see. The snapshot is the simpler contract and is what PSPU §3.14 states; the exposure is the cost.

7.5.5 Metric publication #

The metric ingestion thread owns a separate bounded cache for EVENTD_PUBLISH checks (§7.6). It is keyed by the conveyed token's token_id and modified_id plus concrete metric name. It caches denials as well as grants, clears as a unit when full, and is invalidated by the same descriptor generation as the read caches.

This cache is deliberately thread-local. A recurring metric performs a borrowed string lookup without allocation, shared locking or AccessCheck; the only per-datagram identity operation left is querying the fresh token fd's stable statistics before that fd is closed.

7.6 The Write Path

Peios / Reference / eventd / Access Control

The three write paths establish provenance differently because their inputs come from different places.

7.6.1 Events #

Emission is KMES's business. kmes_emit and kmes_emit_batch require SeAuditPrivilege, and eventd is not in the admission path — it consumes what KMES delivers (§2.2).

The identity stamps on an event are the kernel's, captured from kernel state at the write. An emitting process cannot set, influence, or suppress them.

That is what makes an event's emitter.process.guid evidence, and why a payload value at that path never shadows it (PSPU §3.22).

7.6.2 Logs use peinit as a broker #

Service processes do not reach the log socket. eventd replaces the inherited DACL on LogSocketPath with this protected DACL before its first receive:

D:P(D;;0x2;;;SU)(A;;GA;;;SY)(A;;GA;;;OW)

It sets the DACL alone. The socket stays owned by the service SID of eventd's own virtual Service identity, which created it, and the OW allow lets that owner manage it; making SYSTEM the owner would need a privilege the long-running daemon deliberately does not hold.

SU is the Service logon group, S-1-5-6. Every phase-2 service token, including a SYSTEM service token, carries it. peinit's bootstrap SYSTEM token does not. The deny is evaluated before the SYSTEM allow, so a service cannot write merely because its user SID is SYSTEM; peinit can.

peinit determines origin from the output pipe it is draining and can batch records from several origins in one datagram.

eventd therefore does not request or check a KACS token for each log datagram. The socket admission attests the broker and the broker attests the origin, without token-fd churn or an AccessCheck on the log hot path.

A log origin proves which service context peinit associated with the line. It does not prove that the line's message is truthful.

7.6.3 Metrics carry the producer token #

Every authenticated caller can send to the metric socket: eventd replaces the descriptor it would inherit from its closed runtime directory with D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;OW)(A;;FW;;;AU).

Who can publish what is decided below, per metric name, against the token each datagram carries, so a socket that admitted fewer callers would only leave a grant of EVENTD_PUBLISH to anyone else unusable.

The cost of an open socket is that anyone signed in can send datagrams, and the socket is lossy (§9.1): a caller sending in bulk can crowd out other producers' samples, though none of its own unauthorized records is stored. An operator who wants the socket narrower sets another descriptor on it after eventd starts, for example with sd set. eventd sets its own again each time it starts.

A metric producer enables KACS_SO_PASS_TOKEN once on its persistent sending socket. KACS attaches the producer's effective identity to each datagram as KACS_SCM_TOKEN. eventd uses recvmsg with room for exactly one token and no ordinary file descriptors.

eventd discards the whole datagram before MessagePack parsing when:

  • no token arrived
  • the data was truncated
  • the ancillary data was truncated
  • querying the token or resolving policy failed

For a valid datagram, eventd resolves each record's metric name through the ordinary hierarchical Metrics descriptor namespace (§7.2) and runs AccessCheck against the conveyed token for EVENTD_PUBLISH.

A denied record is discarded; authorized sibling records in the same datagram continue.

The wildcard Metrics descriptor grants EVENTD_PUBLISH to SYSTEM and Administrators, not Authenticated Users. A package that owns a metric prefix installs a more-specific descriptor granting its service SID that right. Existing wildcard descriptors that exactly match eventd's old read-only default are upgraded in place; administrator-modified descriptors are never rewritten.

Authorization covers the metric name, not its labels or value. An authorized producer can create arbitrarily many valid label sets under that name (§5.3).

7.6.4 The publication cache #

A full AccessCheck is not performed per sample or per datagram. The metric ingestion thread owns a bounded verdict cache keyed by:

(token_id, modified_id, concrete metric name)

KACS reuses the captured token object while a persistent sender socket keeps the same effective identity, so ordinary traffic repeatedly hits the same entry. A hit performs no allocation and no AccessCheck.

MetricAuthorizationCacheSize bounds the total entry count.

When full, eventd clears the cache rather than maintaining an LRU list on the write path. This makes churn expensive for the producer causing it without adding pointer updates to every successful lookup.

The descriptor cache carries a generation. Any security-registry change advances it and clears all local publication verdicts before they are reused.

The cache stores denials as well as grants, so repeatedly sending an unauthorized name does not repeatedly invoke KACS.

7.6.5 Rejected input #

Missing identity, truncation, denied records, and policy errors increment in-memory diagnostic counters. Policy errors can produce rate-limited standard-error text.

None produces a durable event or log record of eventd's own: doing work proportional to hostile input would create an amplification path (PSPU §3.4). The one record a denial can cause is KACS's: under a descriptor whose SACL audits failure, as every default does (§7.2), the publication check that denies a name writes a kacs.audit.access.checked record. Denials are cached like grants, so that is one record per token and name until the cache is cleared, not one per datagram.

8.1 Dependencies

Peios / Reference / eventd / Startup and Shutdown

eventd needs four subsystems before it can do anything.

SubsystemFor
KMESEvent ingestion. Provided by the Peios kernel.
LCS and loregdConfiguration. eventd reads every setting from the registry.
KACSAccess control — the AccessCheck API for query authorization, and the peer-token socket option (KACS_SO_PEER_TOKEN) for caller identification.
peinitLifecycle management and pre-start state-directory provisioning.

eventd is a peinit-managed service, started after loregd is available — it cannot read a single configuration value without the registry, and it has no compiled-in defaults for the six paths it needs (§A).

The boot ID is not a service-manager API. eventd reads Linux's /proc/sys/kernel/random/boot_id, validates its UUID text, and converts it to PCDS GUID layout (§3.7).

8.1.1 The dependency that is not one #

KACS authorizes queries and metric publication. The established event drain, write, and retention paths do not perform per-record KACS checks.

That asymmetry is what lets eventd keep draining attached event rings when fresh access checks fail (§9.3), and it is the right way round: losing the ability to read the audit store is recoverable, losing the events is not.

8.1.2 Ordering in the boot #

eventd is one of the platform daemons and is Critical: peinit reboots the system rather than continuing without it. It comes up after loregd and authd, and it stops before them on the way down — it is among the last services shut down, because everything else's shutdown is worth recording.

The window before eventd exists is real and peinit covers it by buffering service output until the log socket appears. Events emitted during that window remain available only while they survive in the finite KMES rings. The first drain after attachment reads survivors from tail_pos (§2.2).

8.2 The Bootstrap Sequence

Peios / Reference / eventd / Startup and Shutdown

Startup proceeds in seven phases, and either completes or fails entirely. The phases group the work by concern rather than fixing its order: eventd reads the boot ID (step 13) before it opens any store, so that each shard can be searched for it as it is opened; it opens eventd-meta.db (step 12) before the shards; and it binds each ingestion socket as soon as its store is open, so the log socket (step 18) is bound before metrics.db (step 11) is opened.

8.2.1 Phase 1 — configuration #

  1. Read every configuration key under Machine\System\eventd\. The six required keys are EventStorePath, LogStorePath, MetricStorePath, QuerySocketPath, LogSocketPath and MetricSocketPath; a missing or invalid one fails startup.

2. Open and validate the three provisioned store directories without following symbolic links. A missing directory, unsafe component, or descriptor that is not equivalent to the protected platform default fails startup (§3.3). SQLite retains each validated directory handle in database and journal paths. It does not resolve that handle back to the configured pathname. Replacing the original directory path therefore cannot redirect an open store. The service needs no metadata-read grant on private ancestors that its traversal privilege permits it to pass through. 3. Read the optional keys and apply compiled-in defaults for those absent (§A). 4. Arm a persistent watch on the subtree, for runtime changes (§8.3).

8.2.2 Phase 2 — KMES attachment and shard sizing #

  1. Query the KMES logical slot count with kmes_attach(KMES_ATTACH_QUERY_SLOTS, …), walk every slot, skip EINVAL holes, and assign dense internal ordinals to successful logical CPU IDs (§2.2).

The calls require SeSecurityPrivilege in the effective token.

Discovering no buffers fails startup. 6. Map each per-CPU ring buffer. 7. Resolve the active shard count from StorageShards — the attached KMES-buffer count when it is 0, the configured value otherwise. 8. Compute the shard-to-CPU assignment (§2.3).

8.2.3 Phase 3 — storage #

  1. Open or create each active event shard: verify the schema version, open in WAL mode with synchronous=FULL, create tables and indexes if new, and quarantine on reported corruption (§3.3).

Discover historical shards matching the naming pattern, and open those with a recognized schema read-only; exclude the rest from the query path.

10. Open or create logs.db in the log store directory — schema verified, WAL, synchronous=NORMAL, quarantine on corruption (§4.3). 11. Open or create metrics.db in the metric store directory, likewise (§5.4).

<a class="citation-anchor" id="cite-bootstrap.metrics-db-is-opened-or-created-in-wal-mode-with-synchronous-normal" href="#cite-bootstrap.metrics-db-is-opened-or-created-in-wal-mode-with-synchronous-normal" data-citation="*bootstrap.metrics-db-is-opened-or-created-in-wal-mode-with-synchronous-normal" title="*bootstrap.metrics-db-is-opened-or-created-in-wal-mode-with-synchronous-normal" aria-label="Citation *bootstrap.metrics-db-is-opened-or-created-in-wal-mode-with-synchronous-normal"><sup></sup></a>
The series cache starts empty and fills on demand.
<a class="citation-anchor" id="cite-bootstrap.the-series-cache-starts-empty" href="#cite-bootstrap.the-series-cache-starts-empty" data-citation="*bootstrap.the-series-cache-starts-empty" title="*bootstrap.the-series-cache-starts-empty" aria-label="Citation *bootstrap.the-series-cache-starts-empty"><sup></sup></a>
  1. Open or create eventd-meta.db.
<a class="citation-anchor" id="cite-bootstrap.eventd-meta-db-is-opened-or-created" href="#cite-bootstrap.eventd-meta-db-is-opened-or-created" data-citation="*bootstrap.eventd-meta-db-is-opened-or-created" title="*bootstrap.eventd-meta-db-is-opened-or-created" aria-label="Citation *bootstrap.eventd-meta-db-is-opened-or-created"><sup></sup></a> Load the index counters and desired
set, load the sequence checkpoints for diagnostics only, and
discover each shard's material indexes from its schema (§3.5).
<a class="citation-anchor" id="cite-bootstrap.sequence-checkpoints-are-loaded-for-diagnostics-only" href="#cite-bootstrap.sequence-checkpoints-are-loaded-for-diagnostics-only" data-citation="*bootstrap.sequence-checkpoints-are-loaded-for-diagnostics-only" title="*bootstrap.sequence-checkpoints-are-loaded-for-diagnostics-only" aria-label="Citation *bootstrap.sequence-checkpoints-are-loaded-for-diagnostics-only"><sup></sup></a>
<a class="citation-anchor" id="cite-bootstrap.each-shards-material-indexes-are-discovered-from-its-schema" href="#cite-bootstrap.each-shards-material-indexes-are-discovered-from-its-schema" data-citation="*bootstrap.each-shards-material-indexes-are-discovered-from-its-schema" title="*bootstrap.each-shards-material-indexes-are-discovered-from-its-schema" aria-label="Citation *bootstrap.each-shards-material-indexes-are-discovered-from-its-schema"><sup></sup></a>

8.2.4 Phase 4 — the boot boundary #

  1. Read /proc/sys/kernel/random/boot_id, require valid UUID text, and convert it to PCDS GUID layout. An unavailable or malformed value fails startup.
  2. Read and merge every committed receipt_ranges row for that boot from every readable active and historical shard, grouped by logical CPU ID (§2.2, §3.1).
<a class="citation-anchor" id="cite-bootstrap.receipt-ranges-for-the-boot-are-merged-from-every-readable-shard-by-cpu" href="#cite-bootstrap.receipt-ranges-for-the-boot-are-merged-from-every-readable-shard-by-cpu" data-citation="*bootstrap.receipt-ranges-for-the-boot-are-merged-from-every-readable-shard-by-cpu" title="*bootstrap.receipt-ranges-for-the-boot-are-merged-from-every-readable-shard-by-cpu" aria-label="Citation *bootstrap.receipt-ranges-for-the-boot-are-merged-from-every-readable-shard-by-cpu"><sup></sup></a>
  1. Search those shards for any committed row or receipt carrying the boot ID. None means the boot's first successful eventd start; otherwise this is a restart within the boot (§3.7).
<a class="citation-anchor" id="cite-bootstrap.a-boot-id-with-no-committed-row-or-receipt-marks-the-boots-first-start" href="#cite-bootstrap.a-boot-id-with-no-committed-row-or-receipt-marks-the-boots-first-start" data-citation="*bootstrap.a-boot-id-with-no-committed-row-or-receipt-marks-the-boots-first-start" title="*bootstrap.a-boot-id-with-no-committed-row-or-receipt-marks-the-boots-first-start" aria-label="Citation *bootstrap.a-boot-id-with-no-committed-row-or-receipt-marks-the-boots-first-start"><sup></sup></a>
  1. Initialize each drain's recovery coverage from the merged receipts. It begins at the ring's oldest survivor, skips covered sequences, re-ingests uncovered survivors, and records as gaps only sequences in neither source (§8.5).
<a class="citation-anchor" id="cite-bootstrap.each-drains-recovery-coverage-is-initialised-from-the-merged-receipts" href="#cite-bootstrap.each-drains-recovery-coverage-is-initialised-from-the-merged-receipts" data-citation="*bootstrap.each-drains-recovery-coverage-is-initialised-from-the-merged-receipts" title="*bootstrap.each-drains-recovery-coverage-is-initialised-from-the-merged-receipts" aria-label="Citation *bootstrap.each-drains-recovery-coverage-is-initialised-from-the-merged-receipts"><sup></sup></a>

8.2.5 Phase 5 — sockets #

  1. Create the query socket at QuerySocketPath.
<a class="citation-anchor" id="cite-bootstrap.the-query-socket-is-created-at-querysocketpath" href="#cite-bootstrap.the-query-socket-is-created-at-querysocketpath" data-citation="*bootstrap.the-query-socket-is-created-at-querysocketpath" title="*bootstrap.the-query-socket-is-created-at-querysocketpath" aria-label="Citation *bootstrap.the-query-socket-is-created-at-querysocketpath"><sup></sup></a> A stale pathname left
by a crash is unlinked first if it is an `AF_UNIX` socket; if the
path exists and is not a socket, startup fails.
<a class="citation-anchor" id="cite-bootstrap.a-stale-socket-at-a-socket-path-is-unlinked-first" href="#cite-bootstrap.a-stale-socket-at-a-socket-path-is-unlinked-first" data-citation="*bootstrap.a-stale-socket-at-a-socket-path-is-unlinked-first" title="*bootstrap.a-stale-socket-at-a-socket-path-is-unlinked-first" aria-label="Citation *bootstrap.a-stale-socket-at-a-socket-path-is-unlinked-first"><sup></sup></a>
<a class="citation-anchor" id="cite-bootstrap.a-non-socket-at-a-socket-path-fails-startup" href="#cite-bootstrap.a-non-socket-at-a-socket-path-fails-startup" data-citation="*bootstrap.a-non-socket-at-a-socket-path-fails-startup" title="*bootstrap.a-non-socket-at-a-socket-path-fails-startup" aria-label="Citation *bootstrap.a-non-socket-at-a-socket-path-fails-startup"><sup></sup></a> Its
inherited descriptor is replaced with the protected one that lets
every authenticated caller connect (§7.1).
<a class="citation-anchor" id="cite-bootstrap.the-query-socket-gets-the-authenticated-users-descriptor" href="#cite-bootstrap.the-query-socket-gets-the-authenticated-users-descriptor" data-citation="*bootstrap.the-query-socket-gets-the-authenticated-users-descriptor" title="*bootstrap.the-query-socket-gets-the-authenticated-users-descriptor" aria-label="Citation *bootstrap.the-query-socket-gets-the-authenticated-users-descriptor"><sup></sup></a>
  1. Create the log socket at LogSocketPath, then replace its inherited DACL with the protected deny-Service, allow-SYSTEM broker DACL, leaving it owned by eventd's service SID (§7.6).
<a class="citation-anchor" id="cite-bootstrap.the-log-socket-gets-the-deny-service-allow-system-broker-descriptor" href="#cite-bootstrap.the-log-socket-gets-the-deny-service-allow-system-broker-descriptor" data-citation="*bootstrap.the-log-socket-gets-the-deny-service-allow-system-broker-descriptor" title="*bootstrap.the-log-socket-gets-the-deny-service-allow-system-broker-descriptor" aria-label="Citation *bootstrap.the-log-socket-gets-the-deny-service-allow-system-broker-descriptor"><sup></sup></a>
  1. Create the metric socket at MetricSocketPath, then replace its inherited descriptor with the protected one that lets every authenticated caller send (§7.6).
  2. Establish and verify the Security Descriptor on all three, before any of them accepts or receives anything (§7.6).
<a class="citation-anchor" id="cite-bootstrap.socket-descriptors-are-verified-before-any-socket-accepts-or-receives" href="#cite-bootstrap.socket-descriptors-are-verified-before-any-socket-accepts-or-receives" data-citation="*bootstrap.socket-descriptors-are-verified-before-any-socket-accepts-or-receives" title="*bootstrap.socket-descriptors-are-verified-before-any-socket-accepts-or-receives" aria-label="Citation *bootstrap.socket-descriptors-are-verified-before-any-socket-accepts-or-receives"><sup></sup></a>

The stale-socket rule distinguishes the two cases deliberately. Unlinking a leftover socket is recovery from eventd's own crash; unlinking a regular file at a configured path would be destroying something that is not eventd's, and a path pointing at the wrong thing is a configuration error worth failing on.

Recognizing a leftover socket needs no right on it. If an operator has narrowed its descriptor so that eventd cannot delete it, eventd, which still owns it, first puts its own descriptor back, so a narrowed socket never stops the next start.

8.2.6 Phase 6 — threads #

  1. One writer thread per active shard.
  2. One drain thread per attached logical CPU, each beginning to reconcile and read its ring buffer.
  3. The log ingestion thread.
  4. The metric ingestion thread.
  5. The retention coordinator thread.
  6. The adaptive indexing policy thread.

8.2.7 Phase 7 — ready #

  1. Write and commit an eventd.daemon.started event in the boot recording whether this start is a restart, the shard count and the per-CPU recovered coverage points (§3.2).
<a class="citation-anchor" id="cite-bootstrap.an-eventd-daemon-started-event-records-restart-shard-count-and-per-cpu-coverage" href="#cite-bootstrap.an-eventd-daemon-started-event-records-restart-shard-count-and-per-cpu-coverage" data-citation="*bootstrap.an-eventd-daemon-started-event-records-restart-shard-count-and-per-cpu-coverage" title="*bootstrap.an-eventd-daemon-started-event-records-restart-shard-count-and-per-cpu-coverage" aria-label="Citation *bootstrap.an-eventd-daemon-started-event-records-restart-shard-count-and-per-cpu-coverage"><sup></sup></a>
The commit
happens before readiness is signaled.
<a class="citation-anchor" id="cite-bootstrap.the-startup-event-is-committed-before-readiness-is-signalled" href="#cite-bootstrap.the-startup-event-is-committed-before-readiness-is-signalled" data-citation="*bootstrap.the-startup-event-is-committed-before-readiness-is-signalled" title="*bootstrap.the-startup-event-is-committed-before-readiness-is-signalled" aria-label="Citation *bootstrap.the-startup-event-is-committed-before-readiness-is-signalled"><sup></sup></a>
  1. Signal readiness to peinit.
<a class="citation-anchor" id="cite-bootstrap.readiness-is-signalled-to-peinit-last" href="#cite-bootstrap.readiness-is-signalled-to-peinit-last" data-citation="*bootstrap.readiness-is-signalled-to-peinit-last" title="*bootstrap.readiness-is-signalled-to-peinit-last" aria-label="Citation *bootstrap.readiness-is-signalled-to-peinit-last"><sup></sup></a>

Committing before signaling is what makes the startup record trustworthy. A readiness signal sent before the commit could be followed by a crash that loses the record, leaving a boot in which eventd demonstrably ran and left no trace of having started.

8.2.8 Failure #

If any phase fails, eventd does not signal readiness.

It logs the failure to standard error where standard error exists, and exits non-zero. peinit's restart policy decides what happens next.

Partial startup is not permitted. There is no degraded mode in which eventd runs without one of its three stores, or without KMES. It either completes the sequence or fails.

The all-or-nothing rule is a simplification. A later revision might allow log and metric ingestion to proceed with KMES unavailable, but that means partial-failure state to manage in every subsequent path — what a query against a store that was never opened does, what happens when the missing subsystem returns — and the failure mode it protects against is one peinit already handles by restarting.

8.2.9 Failed socket setup #

Each newly bound socket pathname has a cleanup guard before later setup steps run. If socket security or another required setup step fails, the guard removes that pathname as the socket closes. A failed start therefore does not leave its own bound socket pathname behind.

8.3 Configuration at Runtime

Peios / Reference / eventd / Startup and Shutdown

eventd watches Machine\System\eventd\ and reacts to changes without restarting — for the settings that can be changed that way.

Notifications arriving during startup are queued and processed after readiness is signaled (§8.2).

Applying a configuration reload to half-initialized state would mean every phase having to tolerate its inputs changing underneath it.

8.3.1 What applies immediately #

Tuning parameters: batch sizes and latencies for all three writers, retention periods and the delete batch size, adaptive index thresholds and windows, the WAL checkpoint threshold, the query request and response sizes, the query timeout, the cross-type window and lookback limit, and the query and streaming concurrency limits.

A live MaxBatchSize change is an atomic update to the event writers' next commit threshold.

It does not resize, replace, or drain their startup-fixed handoff channels (§2.3). The log and metric batch settings likewise affect only subsequent transaction thresholds.

Every applied change, whichever key it touches, also requests an index policy run (§3.4), which writes the metadata database (§3.5), and a retention pass (§3.6), so a changed threshold or a shortened retention period takes effect without waiting for either interval.

8.3.2 What waits for a restart #

ChangeWhy
Socket pathsThe sockets are bound and clients are connected to them.
Store pathsThe databases are open, and moving a store is a data migration, not a setting.
StorageShardsShard-to-CPU assignment, writer threads, and handoff channels are all built from it at startup (§2.3).

The watch notices these changes and eventd defers them rather than attempting a live migration.

Shard count changes in particular are expected once in a machine's life, and rebalancing writer threads while events are in flight is a large mechanism for a rare event.

8.3.3 What is neither #

Security Descriptors under Security\ are not configuration in this sense. The registry watch invalidates the descriptor cache and the next query resolves afresh (§7.5), so a grant or revocation takes effect immediately without anything being "applied".

8.3.4 Recording it #

eventd emits an eventd.config.changed event for every change applied at runtime, carrying the value's name and its old and new values as integers, each left out when no value was stored (§3.2).

Invalid values are ignored and the previous value is retained — an administrator who types a batch size outside its range does not get a daemon that stops working, and the retained value is the one already in use rather than the compiled-in default.

Unknown keys in the subtree are ignored entirely.

8.3.5 SIGHUP #

SIGHUP re-reads the configuration, equivalent to a watch notification (§8.5). It exists for the case where the watch itself is not delivering — a registry outage, or a watch that failed and has not re-armed (§9.3) — and gives an administrator a way to force the read rather than restarting the daemon.

8.4 Shutdown

Peios / Reference / eventd / Startup and Shutdown

When peinit signals a stop, eventd persists as much in-flight data as it can without blocking indefinitely.

8.4.1 The sequence #

  1. Stop accepting. Unlink all three socket paths so no new client can reach them, and stop accepting query connections.

Existing streaming queries are terminated with an error. The log and metric socket descriptors stay open, and eventd goes on reading them until every query connection still being served has ended: a sender that reached either socket before its path was unlinked can still deliver to it. 2. Drain ingestion. Shut the log and metric sockets for reading, so that a later send fails with EPIPE and its sender keeps the datagram (peinit buffers it and replays it to the next eventd), rather than having it queued where nothing will read it.

Then read and process the datagrams still in the receive queues, and close those descriptors.

This is bounded by the receive queue, at most net.unix.max_dgram_qlen datagrams plus one (§4.1), so it completes quickly. 3. Final event drain. Each drain thread performs one last drain cycle from its ring buffer. 4. Final commit. Every writer commits its current batch immediately, whatever its size. The log and metric writers do the same. 5. Record sequence state. Derive each logical CPU's highest contiguously covered sequence from committed receipt ranges and write it to sequence_checkpoints for diagnostics (§3.5).

6. Emit the shutdown event. Write eventd.daemon.stopped with the per-CPU sequences, using the daemon-wide shard assignment rule (§2.6). If the receipt ranges could not be read in step 5, the record carries no sequences rather than zeroes (§3.2). If no shard is writable, the event is skipped and the failure logged to standard error.

7. Close databases. Close every connection, writer, and reader. SQLite checkpoints the write-ahead log automatically on close. 8. Unmap. Unmap every ring buffer and close the per-CPU descriptors. 9. Exit.

Steps 1 and 2 are deliberately split. Unlinking the pathnames stops new senders finding the socket while the descriptors stay open, so whatever is already queued is still readable — closing them at step 1 would discard the queue, which is the data last produced and therefore most likely to explain why the system is being stopped. Shutting the sockets for reading before the drain is what makes the drain final: nothing can join the queue behind it to be discarded when the descriptors close.

The final checkpoint in step 7 matters most for the log and metric stores, which run synchronous=NORMAL and whose durability boundary is the checkpoint rather than the commit (§4.1).

8.4.2 A failed event writer #

When an event-shard writer exits, it closes its handoff queue and releases the pending control requests. A caller waiting for a final-commit barrier, synthetic-event commit or maintenance result then observes failure instead of waiting for a reply from a writer that has stopped. These requests are not acknowledged as committed. Producers waiting for queue capacity wake with a closed-queue error; already admitted handoffs are released once their producer publishes or cancels them. Healthy writers retain their normal backpressure and commit acknowledgements.

A reservation racing with closure either joins the admitted handoffs or fails with a closed-queue error. The final drained check cannot miss a reservation that succeeds, including on processors with weaker memory ordering. Closing also wakes threads that are entering a queue wait; it does not depend on another publication to release them.

8.4.3 The timeout #

Shutdown is bounded by peinit's service stop timeout. If the sequence has not finished, eventd aborts and exits immediately.

What an aborted shutdown costs:

  • Uncommitted event batches are lost. Those events remain in the KMES ring buffers and are available at the next start, provided they have not been overwritten by then.

  • Uncommitted log and metric batches are lost, which is acceptable by design.
  • The diagnostic sequence metadata can be stale. It does not matter: startup derives coverage from committed receipt ranges and reconciles it with the ring buffer (§2.2).

Every consequence is one the restart path already handles, which is why aborting is safe rather than merely tolerable.

8.5 Crash Recovery and Signals

Peios / Reference / eventd / Startup and Shutdown

8.5.1 After a crash #

An ungraceful termination — a segmentation fault, a kill, an out-of-memory kill — leaves four things true.

The ring buffers are unaffected. KMES writes regardless of consumer state, and events emitted while eventd was down accumulate there.

The databases are consistent. WAL mode guarantees committed transactions survive, and SQLite rolls back the in-flight batch on the next open.

There can be uncovered sequences. Events in an uncommitted batch were not persisted, but some can still survive in KMES. On restart eventd merges committed receipt ranges from all shards, re-ingests each uncovered survivor, and writes a gap only for a sequence present in neither receipts nor the ring (§2.2, §2.5).

Socket-buffered data is gone. The kernel discards a socket receive queue on process exit, taking whatever logs and metrics were waiting. Acceptable by the loss model.

No manual recovery is needed and none is offered. eventd restarts, re-attaches, resumes draining, and records only what was truly missed. The boot-boundary logic recognizes the restart from committed rows or receipts rather than a flag written in advance (§3.7) — which is the point, since a crash is precisely the case where nothing was written in advance.

8.5.2 Signals #

SignalBehavior
SIGTERMBegin graceful shutdown (§8.4).
SIGINTBegin graceful shutdown.
SIGQUITWrite a diagnostic dump to standard error, then begin graceful shutdown.
SIGHUPRe-read configuration from the registry (§8.3).
SIGPIPEIgnored, so a write to a socket whose peer has gone — a query client that disconnects mid-response — fails with EPIPE on that connection instead of ending the daemon.

Every other signal keeps its default behavior.

8.5.3 The diagnostic dump #

SIGQUIT writes human-readable text to standard error before step 1 of the shutdown sequence, so that it reflects the daemon's state while it is still running rather than while it is tearing down. It includes at least:

  • the current boot ID
  • the active shard count and the readable historical shard count
  • the per-CPU committed receipt coverage and highest covered sequence

  • the current non-streaming and streaming query counts
  • the metric series cache occupancy
  • KMES events discarded for claiming one of the five types eventd writes itself (§3.1)
  • log records discarded for an origin outside the origin grammar, and the most recent such origin where one exists (§4.1)

  • metric datagrams missing identity, truncated, denied by name policy or rejected by an authorization error

  • the cumulative metric type-mismatch count and the latest conflicting metric name and expected and received types, where one exists
  • the last observed write error for each store, where one exists

The format is not a stable machine interface and its wording can change.

Most of what an operator asks of a running eventd — whether the writers keep up, whether the series cache is thrashing (§5.3), whether query slots are exhausted (§6.5), whether a store has been failing writes — is answered over time by its health metrics (§5.7). The dump is for what those cannot carry: the counts of rejected ingestion input, which no query client can see (PSPU §3.4), the latest error text and rejected names, and the receipt coverage. It also still works when the metric store is the thing that is broken. Standard error is the destination because peinit captures it, so the dump reaches the log store by the ordinary path — and reaches standard error directly when the log store is broken.

9.1 Losing Events

Peios / Reference / eventd / Failure Modes

Every other failure in this chapter costs something recoverable. This one does not, which is why the whole ingestion pipeline is shaped around delaying it.

9.1.1 Ring buffer overrun #

When events are emitted faster than eventd drains them, the per-CPU ring buffers fill and KMES overwrites its oldest entries.

  • eventd sees it as a sequence gap on the affected CPU (§2.5).
  • An eventd.events.lost record is written, naming the missing range.

  • The range is added to that CPU's eventd.events.lost (§5.7).
  • Draining resumes from the oldest survivor at tail_pos.

The events are gone. No other copy exists, and a gap record is a tombstone rather than a recovery — it records what was lost and when, which is the most that can be offered.

Four mechanisms delay it:

MechanismEffect
Adaptive batch sizing (§2.4)Commits as often as throughput allows, so the writer stays close to the drain rate.
Index shedding (§3.4)Drops per-insert index cost under pressure, including all of it at once in the emergency case.
Sharding (§2.3)Scales write throughput with the shard count.
Ring buffer capacityThe absorption window, sized by an administrator.

The first three are eventd's and operate automatically. The fourth is KMES's and is the one an operator can enlarge for a workload that bursts predictably.

9.1.2 Query timeouts #

A query exceeding QueryTimeoutMs is canceled and the client receives an error (§6.5).

Read-only connections are released; nothing is lost, and the query did not finish.

Streaming queries are bounded only up to watch; past that the watch phase is not time-limited.

The main risk is a large scan over a field with no index, which adaptive indexing reduces over time by indexing whatever keeps being filtered on (§3.4). A timeout is therefore worth reading as a signal about the index set rather than only as an error to retry.

9.1.3 Ingestion backpressure #

When a log or metric socket's receive queue is full, the kernel refuses the send: a non-blocking sender receives EAGAIN, and a blocking one waits (§4.1). eventd is not notified and does not count the refusal, so no health metric shows it (§5.7).

This is by design and is not a failure to be tuned away (PSPU §3.4). The one operational note is that the queue is not being drained while a batch is committing, because the same thread does both jobs (§4.1) — so a burst arriving during a commit is the common case for log loss.

9.2 Storage Failure

Peios / Reference / eventd / Failure Modes

9.2.1 Disk full #

When the filesystem holding a store reaches capacity, SQLite writes fail.

After any write failure consistent with disk-full or quota exhaustion, eventd schedules an immediate retention run across every store whose retention is enabled, under the ordinary bounded-batch rules (§3.6, §4.4, §5.5).

Retention is the only lever eventd has that frees space, and waiting up to an hour for the next scheduled pass would waste the window in which recovery is still cheap.

A write refused for want of space emits no eventd.store.quarantined; that event reports only a store found corrupt and quarantined (§2.6).

Capacity diagnostics name the operation that failed. A synthetic-event, quarantine-report, maintenance, or rollup-maintenance failure is not by itself a report of a discarded ingestion batch. Actual failed batches are reported as discarded, with event-batch loss ranges as described below.

9.2.1.1 The event store #

A failed INSERT or COMMIT does not crash the writer thread.

The batch is lost, and it is not recoverable: those events were already consumed from the ring buffer, so KMES does not have them. The writer records the per-CPU sequence ranges of the failed batch in an in-memory lost-batch list, and on its next successful commit emits eventd.events.lost records for every accumulated range before writing new events. Each record's timestamp is that of the last lost event in its range, since no later event revealed it (§2.5).

That ordering matters. Emitting the gap records first means the store never contains events written after a loss without the record of the loss preceding them.

The writer also logs the failure to standard error immediately — including the CPU identifiers and sequence ranges — which peinit captures.

That is the only visibility available while the disk is still full and the gap record cannot yet be written.

If eventd crashes before the disk recovers, the in-memory list dies with it. Nothing is silently lost even so: on restart, committed receipt ranges are reconciled with the current ring survivors. Uncovered survivors are ingested again, and sequences present in neither source become ordinary restart gaps (§2.2, §3.7). The record can be coarser — one gap rather than several — but the loss is still recorded.

Meanwhile events accumulate in the ring buffers. If the disk stays full long enough, they overrun and additional loss occurs, detected by the same mechanism (§9.1).

9.2.1.2 The log and metric stores #

A failed commit loses the batch. The writer retries on the next one.

Acceptable under the loss model, and no lost-batch accounting exists for either — there is nothing to reconcile against, since neither has sequence numbers.

9.2.2 Corruption #

Corruption from a hardware error, a filesystem bug, or an incomplete write during a kernel crash.

Detection at startup is structural: eventd verifies that the required tables and indexes exist.

It does not run PRAGMA integrity_check, which scans the entire database and costs time proportional to its size — unacceptable for a large event store on every boot. Corruption that leaves the schema intact, such as a single bad page, is found later, at query or write time, when SQLite touches it.

At startup, when SQLite reports corruption in a required active store, eventd quarantines the files, creates a fresh empty database at the original path, and continues (§3.3).

It logs the corruption and emits eventd.store.quarantined once a shard is available to hold it.

At write time, eventd stops writing to the affected database, emits eventd.store.quarantined if it can, quarantines and replaces the database, and resumes writes to the replacement.

At query time, a handler encountering corruption fails the affected query with an error.

It does not return the rows it managed to read: partial data from a database SQLite has declared corrupt is indistinguishable from complete data, and silently under-reporting an audit query is worse than failing it.

A missing or unrecognized schema version is not corruption.

It is not repaired and not migrated: a required store with one fails startup, and a historical shard with one is excluded from the query path (§3.3).

Recovering data from a quarantined file is an administrative operation. eventd never attempts automatic repair, and the quarantined file is the only copy of whatever it held.

9.3 Losing Dependencies

Peios / Reference / eventd / Failure Modes

Two of eventd's four dependencies can disappear after startup without stopping it, and in both cases the ingestion path survives while the query path does not. That asymmetry is deliberate: events that are not collected are gone, and queries that cannot be answered can be asked again.

9.3.1 The registry becomes unavailable #

If LCS or loregd goes away after eventd has started:

  • eventd keeps its last known configuration. Changes are not applied until the registry returns.
  • Descriptor lookups fall back to the cache. A pattern the cache does not hold is denied, fail-closed (§7.5).
  • eventd keeps ingesting and keeps serving queries for descriptors it already resolved, indefinitely.

  • When the registry returns, the watch fires and eventd re-reads.

This is a degraded state, not a failure. eventd does not exit, and it does not stop collecting.

The related case is the watch failing while the registry is otherwise reachable. eventd discards the descriptor cache and operates fail-closed for new resolutions until the watch is re-established (§7.5), because a cache it cannot trust to be current would make a revocation silently ineffective.

SIGHUP forces a configuration re-read in the meantime (§8.3).

9.3.2 KACS becomes unavailable #

If KACS goes away after startup:

  • reading the peer token (KACS_SO_PEER_TOKEN) fails on new query connections, so new queries are denied.
  • kacs_access_check and kacs_access_check_list fail, so a query in progress that needs a fresh check is denied.
  • Cached check results stay valid for the duration of the query that obtained them.

  • Event ingestion is unaffected. Neither the drain nor the write path calls KACS (§8.1).
  • Log ingestion is unaffected.
  • Metric ingestion continues, but every record needs an EVENTD_PUBLISH check (§7.6). A record whose verdict is cached for the sender's token and name is stored as usual; one needing a fresh check is refused and counted as an authorization error, and the rest of its datagram is still taken.

Established event ingestion continues. Queries or metric records that need a fresh failing access check are rejected. Those operations resume when KACS checks succeed.

9.3.3 KMES #

There is no partial mode. eventd attaches to every per-CPU ring buffer at startup and fails to start if it cannot (§8.2); there is no subsequent state in which KMES is present but unusable, because the mapping is established once and the read protocol has no call that can fail afterward. A ring buffer resize is handled as a generation change, not as a failure (§2.2).

9.3.4 peinit #

peinit manages eventd's lifecycle but supplies no runtime service to it. The boot ID comes from /proc/sys/kernel/random/boot_id (§8.1). There is therefore no separate peinit-loss mode once eventd is running — peinit going away means the system is going away.

9.4 Resource Exhaustion

Peios / Reference / eventd / Failure Modes

9.4.1 Memory #

If the out-of-memory killer takes eventd, it is treated exactly as a crash (§8.5): the databases are consistent, the ring buffers are untouched, peinit restarts the daemon, and the gap is recorded.

The principal long-lived memory consumers are:

ConsumerProportional toBounded by
Series cachedistinct metric series held in memoryMetricSeriesCacheSize (§5.3)
Event-type and log-origin intern setsdistinct committed identifiers not yet cleaned from active catalogscatalog cardinality; no independent memory setting (§3.1, §4.2)
Adaptive index countersdistinct event fields queriedthe event query surface
SQLite page cachesconnections and active indexesper-connection configuration (§C)
Event handoff channelsoccupied slots and copied event bytesstartup-fixed internal slot and byte limits (§2.3)

The handoff limits do not follow live MaxBatchSize changes. The channels are small scheduling handoffs; KMES remains the real event backlog.

High-cardinality producers are the likely surprise. The series cache cannot grow past its limit, but the series table can grow and make it thrash on the thread that also drains the metric socket (§5.3). Identifier intern sets intentionally trade memory for zero catalog work on known-name ingestion. The default 1 GiB metric retention ceiling and low-priority orphan cleanup bound persistent growth indirectly, but do not bound the number of active series between retention passes.

9.4.2 Query slots #

Reaching MaxConcurrentQueries, MaxStreamingQueries, or MaxQueriesPerUser rejects new queries with an error rather than queueing them (§6.5). The per-user bound keeps one caller from occupying every slot; several callers together, or SYSTEM, still can.

Ingestion is unaffected, because queries and ingestion are separate channels and separate threads.

That separation is what makes query-side exhaustion an inconvenience rather than data loss.

9.4.3 Descriptors #

An event query opens a read-only connection per shard database, and each connection holds one or two file descriptors (§6.4). Many historical shards multiplied by many concurrent queries reaches a process limit faster than anything else eventd does.

Where eventd cannot allocate what an admitted query needs, it fails that query rather than blocking a writer or exceeding its own limit (§6.1).

9.4.4 Writer stalls #

Two things stall a writer thread briefly, and both are bounded by design.

An index build in progress. Drain threads detect rising write pressure and signal cancellation; the writer aborts the CREATE INDEX, SQLite rolls back the partial index, and event writing resumes immediately (§3.4).

A writer-owned maintenance command. Retention and adaptive-index maintenance execute only as bounded, low-priority commands at transaction boundaries.

Ingestion wins before the next command; there is no competing read-write connection or writer mutex (§3.6).

Neither stall loses anything by itself. Both contribute to ring buffer pressure, and prolonged enough, both end at §9.1.

9.5 Power Loss

Peios / Reference / eventd / Failure Modes

Sudden power loss is the failure the three stores' durability settings were chosen against, and it is where the hierarchy the whole daemon is built on becomes visible as three different outcomes.

StoreSettingWhat survives
Eventsynchronous=FULLEvery committed transaction.
Logsynchronous=NORMALTransactions up to the last checkpoint.
Metricsynchronous=NORMALTransactions up to the last checkpoint.

The event store loses only the in-flight batch — the events accumulated since the last commit, which the adaptive batcher keeps as small as throughput allows (§2.4).

Unlike a process crash, a power cycle destroys the old KMES rings and changes the boot ID. eventd can neither recover that batch nor determine its final sequence range, so it cannot honestly manufacture an eventd.events.lost record for it. The last receipt coverage and the following boot's eventd.daemon.started bound the unknown loss.

The log and metric stores can lose everything committed since their last write-ahead log checkpoint, which under synchronous=NORMAL is the real durability boundary rather than the commit. How much that is depends on WalCheckpointPages and the write rate, and it can be considerably more than one batch.

The difference is bought and paid for deliberately. FULL costs an fsync on every commit, which at ten thousand events a batch is amortized and at three events a batch is not — and eventd commits small batches constantly under light load. The event store pays it because an event can be an audit record whose absence is itself the finding. The other two do not, because their loss is defined as acceptable and paying for durability they do not need would slow the paths that are most likely to be bursty.

Events are sacred; logs and metrics are important but not fundamental. Every durability decision in this manual is that sentence applied to a particular store.

9.5.1 What restart does #

Nothing manual. eventd starts, finds its databases consistent — WAL recovery is SQLite's, and an incomplete transaction is rolled back on open — reads the new kernel boot ID and starts that boot's per-CPU coverage before sequence 1 (§3.7). It does not compare a new boot's ring against the previous boot's receipts: those are different sequence namespaces.

This is the irreducible difference from a process crash. In the latter, KMES survives and receipt/ring reconciliation can distinguish committed, recoverable and truly missing sequences (§8.5). Across power loss, the old volatile source do not exists.

10.1 Using evctl

Peios / Reference / eventd / Clients

evctl is eventd's native command-line client. Its normal operation has no subcommand: the one positional argument is a PSPU observability query.

evctl 'EVENTS kacs.* SINCE 1h ago TAKE 50'
evctl 'LOGS FROM authd ERROR ONLY STREAM'
evctl 'METRIC cpu.usage SINCE 10m ago AVG'

Quote the complete query. Without the quotes, the shell can split string literals or expand * patterns before evctl sees them. Query syntax and semantics remain those of PSPU §3.18–§3.27; evctl does not maintain a second flag-based query language.

10.1.1 Commands and queries #

Exact standalone words such as help and version occupy the command namespace. Anything whose first word is EVENTS, LOGS or METRIC, matched without regard to ASCII case, is a query. This leaves room for administrative commands without requiring the common query operation to be written as evctl query ....

The query can instead be read from a UTF-8 file or standard input:

evctl --file denied-events.evq
printf '%s\n' 'EVENTS eventd.* SINCE 1d ago' | evctl -

The default socket is /run/eventd/query.sock. --socket PATH selects a nonstandard configured socket. The server obtains the caller from the Unix socket peer token and performs every identifier and field access check; the client never opens an eventd database or substitutes its own authorization decision.

10.1.2 Output #

Data is written to standard output. Diagnostics and query errors are written to standard error, so redirecting or piping the result does not mix the two.

FormatSelectionUse
Pretty--format pretty (default)One self-describing record per line, with terminal emphasis on field names.
JSON Lines--format jsonlOne JSON object per record for text pipelines. Binary, extension, and non-finite floating-point values use tagged objects rather than being discarded.
MessagePack--format msgpackA lossless binary sequence. Each record is preceded by a four-byte little-endian payload length.

Records do not have a uniform schema. A field absent from one line is not necessarily absent from later lines. Scripts should select the fields they need in the query or tolerate missing object keys.

10.1.3 Result commitment #

An ok response is not, by itself, a completed result. A non-streaming query only succeeds when eventd sends end; a streaming query's initial result only succeeds when eventd sends watch (PSPU §3.16). If eventd reports an error before that point, every preceding record belongs to an invalid partial result and must be discarded.

evctl therefore renders initial records into an anonymous temporary spool. It publishes the spool to standard output only after end or watch. The spool bounds heap use independently of the result count and has no pathname to clean up after a crash.

After watch, new records are written directly as they arrive. Closing evctl, including with Ctrl-C, closes the query connection and ends the watch.

As with every streaming client, a blocked output pipeline eventually applies socket backpressure. eventd can terminate that stream rather than allowing a slow observer to interfere with ingestion.

10.2 The Rust Client Library

Peios / Reference / eventd / Clients

eventd-client is a Rust library, in the eventd source tree, for programs that query eventd: evctl itself, Event Viewer, and any third-party tool. It speaks the query channel of PSPU §3.14–§3.17 and adds what every client would otherwise have to get right on its own.

It depends on the peios crate and nothing of eventd's own, so a program using it brings in neither SQLite nor eventd's storage.

10.2.1 Whole results or none #

PSPU §3.16 says an error that arrives before the terminal message voids every result message before it. The library keeps that rule itself, so a program cannot show part of a result as if it were all of it.

  • query(socket, text) runs a query that does not stream and returns every record once end has arrived, or the error and no records.
  • Tail::start(socket, text, capacity) follows a STREAM query. It reports the initial result once, complete, when watch arrives; then each live batch; then why the tail ended. If the query fails before watch, the only report is that it ended.

A query blocks until eventd's terminal message, for as long as eventd's query timeout (§6.5), so a program with a window to keep responsive runs it on another thread.

10.2.2 A tail that stops rather than grows #

A tail reads the socket on a thread of its own, as fast as eventd writes, and passes reports through a channel that holds at most capacity of them.

If the program stops taking reports, the channel fills, the thread stops reading, the socket's buffer fills, and eventd ends the query, since it never waits for a slow reader (§6.6). The program's next report is that the tail ended. Nothing grows without bound, in eventd or in the program.

Dropping the Tail closes the connection, which eventd treats as canceling the query (PSPU §3.14).

10.2.3 Writing query text #

The text module writes a value into query text so that it is always exactly one value (PSPU §3.19).

  • string writes a quoted string: the quote and backslash escaped, and every control character as \n, \r, \t or \uXXXX.
  • binary writes x"…"; duration writes 90s, 2h and so on, in the largest unit that holds the duration exactly.

Every place the language takes an identifier or a pattern also takes a quoted string, so text a person typed should always go through string. Written bare, an event type called STREAM or WHERE would be read as the clause, since the pattern after EVENTS is optional. After LOGS FROM, which always takes an origin, the same word is read as the origin, but quoting is never wrong there either.

eventd's own tests parse the library's quoted text back through eventd's parser for strings chosen to break naive quoting, and require the value to come back unchanged.

10.2.4 What a caller can read #

eventd removes what a caller can not read and says nothing about it (PSPU §3.28). A program that wants to tell its user "you can't read events here", rather than show an empty list, has to work it out from the same descriptors eventd checks (§7). The access module does that.

  • The rights, eventd's generic mapping, the three namespaces with their root GUIDs, and the walk from an identifier to its pattern come from this module, and eventd uses the same definitions, so a client and eventd cannot disagree on them.
  • field_guid derives a field's GUID (§7.3). eventd-core computes the same derivation for itself, and a test holds the two equal.
  • resolve finds the descriptor eventd would check an identifier against: the identifier, each shorter dotted prefix, then *, with an origin's producer left off (§7.2).
  • access checks a descriptor the way eventd does: the calling process's own token, eventd's mapping, and the object type list of the data type's root and the paths of any fields asked about (§7.3), then every field the descriptor grants by name. Records are visible with EVENTD_READ on the root or on any field, as eventd shows them (§7.4).
  • field_tree builds that list for a set of field names, and field_reads makes the check over it, answering per field; eventd uses both, so the tree a client asks about is the one eventd builds.
  • field_grants lists the fields a descriptor grants by name: the object GUIDs of its allowing object ACEs. eventd uses it too, to find which identifiers a field-only grant makes visible.
  • readable says how much of events, logs or metrics the caller can read across every pattern written for them, since a more specific pattern can grant what * denies, and the other way round: everything, some (and which patterns it can not read), nothing, or unknown.

When the policy itself can't be read, readable says unknown and why, never "nothing": a caller denied the registry keys can still be granted the data.

Appendix A Configuration Keys

Peios / Reference / eventd

Every key lives under Machine\System\eventd\. eventd ignores unknown keys in the subtree. An invalid value is ignored and the value already in use is retained, and eventd emits an eventd.config.changed event for every change actually applied (§8.3).

A.1 Required #

No compiled-in defaults. A missing or invalid value fails startup (§8.2).

KeyTypeDescription
EventStorePathREG_SZProvisioned directory for event shards and eventd-meta.db; standard deployment /var/state/eventd/events/.
LogStorePathREG_SZProvisioned directory for logs.db; standard deployment /var/state/eventd/logs/.
MetricStorePathREG_SZProvisioned directory for metrics.db; standard deployment /var/state/eventd/metrics/.
QuerySocketPathREG_SZUnix socket path for queries.
LogSocketPathREG_SZUnix socket path for log ingestion.
MetricSocketPathREG_SZUnix socket path for metric ingestion.

A.2 SQLite storage #

KeyTypeDefaultRangeDescription
WalCheckpointPagesREG_DWORD1000100–100000WAL page threshold triggering a passive checkpoint, on shard, log, metric and metadata databases alike.

A.3 Event ingestion #

KeyTypeDefaultRangeDescription
StorageShardsREG_DWORD00–256Number of event shards. 0 means the successfully attached KMES-buffer count. Each shard costs at least three file descriptors, plus about two for every running query that reads every shard; a high count needs eventd's LimitNOFILE raised (§2.3).
MaxBatchSizeREG_DWORD10000100–100000Maximum events per writer transaction.
MaxBatchLatencyMsREG_DWORD10010–5000Maximum ms before an event batch commits.

A.4 Log ingestion #

KeyTypeDefaultRangeDescription
LogMaxBatchSizeREG_DWORD5000100–100000Maximum log records per transaction.
LogMaxBatchLatencyMsREG_DWORD50010–5000Maximum ms before a log batch commits.
MaxLogDatagramBytesREG_DWORD262144262144–1048576Maximum accepted log datagram size; the PSPU portable floor cannot be lowered.

A.5 Metric ingestion #

KeyTypeDefaultRangeDescription
MetricMaxBatchSizeREG_DWORD5000100–100000Maximum metric samples per transaction.
MetricMaxBatchLatencyMsREG_DWORD100010–5000Maximum ms before a metric batch commits.
MaxMetricDatagramBytesREG_DWORD262144262144–1048576Maximum accepted metric datagram size; the PSPU portable floor cannot be lowered.
MetricSeriesCacheSizeREG_DWORD500001000–1000000Entries in the LRU series resolution cache.
MetricAuthorizationCacheSizeREG_DWORD16384256–1000000Cached KACS publication verdicts, invalidated by security-policy generation.
HealthMetricIntervalSecondsREG_DWORD150–3600How often eventd records its own health as eventd.* metrics; 0 turns them off (§5.7).

A.6 Adaptive indexing #

KeyTypeDefaultRangeDescription
AdaptiveIndexWindowHoursREG_DWORD241–168Rolling window over which query frequency is measured.
AdaptiveIndexPolicyIntervalMinutesREG_DWORD6060–1440How often the desired index set is recomputed. The minimum of 60 prevents index churn.
AdaptiveIndexCreateThresholdREG_DWORD10010–10000Queries on a field within the window needed to add it.
AdaptiveIndexDropThresholdREG_DWORD101–1000Queries below which it is removed. Less than the create threshold, which is what supplies the hysteresis.

A.7 Index shedding #

KeyTypeDefaultRangeDescription
SheddingWindowSecondsREG_DWORD3010–300Sliding window for graduated shedding.
SheddingBatchPercentREG_DWORD7550–100Percentage of batches in the window exceeding 75% of MaxBatchSize that triggers graduated shedding.
EmergencySheddingBufferPercentREG_DWORD7550–95Ring buffer fill percentage triggering emergency shedding.

A.8 Retention #

KeyTypeDefaultRangeDescription
EventRetentionDaysREG_DWORD301–3650Maximum age of events.
EventRetentionMaxBytesREG_QWORD00–2^64−1Maximum total logical live size of the event shards. 0 means no limit.
LogRetentionDaysREG_DWORD141–3650Maximum age of log entries.
LogRetentionMaxBytesREG_QWORD00–2^64−1Maximum logical live size of the log store. 0 means no limit.
MetricRetentionDaysREG_DWORD901–3650Maximum age of metric samples.
MetricRetentionMaxBytesREG_QWORD1073741824 (1 GiB)0–2^64−1Maximum logical live size of the metric store. 0 explicitly disables the limit.
RetentionCheckIntervalMinutesREG_DWORD601–1440How often the retention coordinator runs.
RetentionDeleteBatchRowsREG_DWORD10000100–100000Maximum rows deleted in one retention transaction.

A.9 Querying #

KeyTypeDefaultRangeDescription
QueryTimeoutMsREG_DWORD300001000–300000Maximum query execution time.
MaxConcurrentQueriesREG_DWORD1281–4096Concurrent finite and streaming queries globally.
MaxStreamingQueriesREG_DWORD641–1024Concurrent streaming queries globally.
MaxQueriesPerUserREG_DWORD161–4096Concurrent queries, streaming or not, held by one caller's user SID; SYSTEM's are not counted (§6.5).
MaxDistinctStreamValuesREG_DWORD1000001000–10000000Values tracked by one DISTINCT streaming query.
MaxQueryRequestBytesREG_DWORD655361024–16777216Hard maximum query request payload.
QueryResponseTargetBytesREG_DWORD655361024–16777216Soft response batching target; one complete record can exceed it (§6).
MaxQueryHeldBytesREG_DWORD268435456 (256 MiB)16777216–4294967295What every running query together can hold to answer: sorted rows, aggregation groups, and watch batches. A query in the default order holds nothing against it (§6.5).

A.10 Adaptive metric rollups #

KeyTypeDefaultRangeDescription
AdaptiveRollupMinSamplesREG_DWORD1000100–1000000Minimum raw inputs an eligible window query must scan before it can seed rollups.
AdaptiveRollupBatchRowsREG_DWORD51216–4096Maximum missing windows submitted in one bounded writer command.
AdaptiveRollupMaxRowsREG_DWORD1000000–10000000Global rollup-cache row cap. 0 disables cache reads and writes without changing results.

A.11 Cross-type filtering #

KeyTypeDefaultRangeDescription
CrossTypeWindowMsREG_DWORD150001000–300000Centered window for cross-type event and log existence checks.
CrossTypeMaxLookbackSecondsREG_DWORD6048003600–2592000Maximum range a cross-type filter can scan.

A.12 The security subtree #

Read-path descriptors live under Machine\System\eventd\Security\ and are not configuration in the sense above (§7.2):

Machine\System\eventd\Security\Events\*
Machine\System\eventd\Security\Events\<pattern>
Machine\System\eventd\Security\Logs\*
Machine\System\eventd\Security\Logs\<pattern>
Machine\System\eventd\Security\Metrics\*
Machine\System\eventd\Security\Metrics\<pattern>
Machine\System\eventd\Security\Admin

Security\Admin governs EVENTD_ADMINISTER, especially INDEX, and defaults to SYSTEM and Administrators.

It is registry-protected policy, not data in eventd-meta.db (§3.5, §7.2).

A.13 When a change takes effect #

ChangeEffect
Every tuning parameter aboveApplied immediately.
Socket pathsRestart.
Store pathsRestart.
StorageShardsRestart.
Security descriptorsNext query; the registry watch invalidates the cache.

Appendix B Constants

Peios / Reference / eventd

Wire-protocol constants — framing, ingestion limits, the query request ceiling and response target — belong to the interfaces rather than to eventd and are in PSPU §3.A.

B.1 Access rights #

RightBitValueMeaning
EVENTD_READ00x0001Read records matching the pattern.
EVENTD_CLEAR10x0002Delete records matching the pattern. Reserved; nothing uses it yet (§7.1).
EVENTD_ADMINISTER20x0004Change eventd's own policy — the INDEX command.
EVENTD_PUBLISH30x0008Publish metric records under the matching name.

B.2 Generic mapping #

Passed to AccessCheck in the generic_read, generic_write, generic_execute and generic_all fields.

Generic rightValueComposed of
GENERIC_READ0x00020001EVENTD_READ | READ_CONTROL
GENERIC_WRITE0x0002000EEVENTD_CLEAR | EVENTD_ADMINISTER | EVENTD_PUBLISH | READ_CONTROL
GENERIC_EXECUTE0x00020001EVENTD_READ | READ_CONTROL
GENERIC_ALL0x000F000FEVENTD_READ | EVENTD_CLEAR | EVENTD_ADMINISTER | EVENTD_PUBLISH | DELETE | READ_CONTROL | WRITE_DAC | WRITE_OWNER

EVENTD_ADMINISTER and EVENTD_PUBLISH are in GENERIC_WRITE and deliberately not in GENERIC_READ or GENERIC_EXECUTE (§7.1, §7.6).

B.3 Field GUID namespace #

EVENTD_FIELD_NAMESPACE = {e7d3a1b0-5c2f-4e8a-9b1d-0a6f3c8e2d4b}

Field GUIDs are uuid_v5(EVENTD_FIELD_NAMESPACE, field_name) with field_name as UTF-8 (§7.3).

B.4 Data type root GUIDs #

The level-0 node of an object type list.

Data typeGUID
Events{a1b2c3d4-0001-4000-8000-000000000001}
Logs{a1b2c3d4-0001-4000-8000-000000000002}
Metrics{a1b2c3d4-0001-4000-8000-000000000003}

B.5 Field names #

Field GUIDs are computed from the algorithm, never hardcoded. The names they are computed from are these.

Event header fields. event.time, event.cpu, event.sequence, emitter.class, event.type, emitter.token.guid, emitter.true-token.guid, emitter.process.guid, event.boot.guid, the paths of PSPU §3.22. The events table's column names are not field names (§3.1).

Log fields. timestamp, origin, is_error, message, job_id, boot_id.

Fixed metric fields. timestamp, boot_id, name, type, value.

Event payload fields use the flattened dot path (PSPU §3.22). Suppressed paths, and payload paths at or beneath a header field's path, are not query-language fields and have no GUID.

Metric label keys use the key itself: core produces uuid_v5(EVENTD_FIELD_NAMESPACE, "core"). A label key can never be one of the five fixed metric field names, because ingestion rejects records whose labels collide with them.

B.6 Origin class #

ValueOrigin
0userspace
1KMES
2KACS
3LCS
4NTFE

The origin class is the header field emitter.class, held in the origin_class column, and the query language accepts the names of classes 0 to 3 as aliases for their values (PSPU §3.23 names no alias for NTFE).

B.7 Synthetic event types #

TypeEmitted when
eventd.daemon.startedeventd starts and attaches to KMES.
eventd.daemon.stoppedGraceful shutdown has committed everything read.
eventd.events.lostA sequence gap is detected on a CPU.
eventd.config.changedA configuration value is applied at runtime.
eventd.store.quarantinedA store is found corrupt and quarantined.

All five are tier essential. These five names, and no others, are reserved: a KMES event of one of these types is not stored (§3.1). Payload schemas are in §3.2.

B.8 Metric types #

ValueType
0counter
1gauge
2histogram

Stored in series.type. The query language exposes the names, not the numbers (PSPU §3.22).

B.9 Log severity #

ValueMeaning
0Normal — standard output.
1Error — standard error, or explicitly marked.

Stored as an integer in logs.is_error; exposed as a boolean by the query language, which accepts both forms (§4.2).

B.10 Series hashing #

FNV-1a, 64-bit, over the exact bytes of the canonical label string or the boundary blob.

ParameterValue
Offset basis0xCBF29CE484222325
Prime0x100000001B3
Stored ashash & 0x7FFF_FFFF_FFFF_FFFF

The high bit is cleared so the value fits SQLite's signed INTEGER. Hashes narrow lookups; identity is always confirmed against the full string or blob (§5.2).

B.11 Schema versions #

StoreVersion
Event shard1
Log store1
Metric store3
eventd-meta.db1

An unrecognized version is never migrated. For a required store it fails startup; for a historical shard it excludes the shard from the query path; for the metadata database it recreates from defaults (§3.3, §3.5).

Appendix C Performance Review

Peios / Reference / eventd

Performance changes must preserve receipt accounting, authorization, and bounded memory use. A faster path that loses either property changes the service contract rather than optimizing its implementation.

C.1 Implemented mechanisms #

The implementation uses these mechanisms:

  • Bounded handoff reservations before copying kernel events (§2.3).
  • Independent writer threads and receipt commits per shard (§2.4).
  • Cached SQLite statements and event-type identifiers (§2.4).
  • Pressure-sensitive payload indexes (§3.4).
  • Bounded metric-series and authorization caches (§5.3 and §7.5).
  • Query-driven metric rollups checked against raw samples (§5.6).

The host hot-path benchmark exercises queue handoff and SQLite ingestion. It does not measure kernel ring attachment, native access checks, or a complete production workload. Build and benchmark commands belong in the repository's contributor guide.

C.2 Measurement boundaries #

Record the hardware, storage, build profile, data shape, shard count, and configuration with each result. Compare throughput together with commit latency, queue occupancy, memory use, and loss reports.

Increasing concurrency can increase memory, thread, and descriptor use. Increasing batch sizes can amortize commits while increasing the amount of uncommitted work. Evaluate those costs together rather than treating a single throughput number as the result.

C.3 Changes requiring evidence #

Allocation pools, thread affinity, batched datagram reads, and connection pools need workload evidence before adoption. A pool must have an explicit bound and account for every retained object. No performance multiplier is guaranteed by selecting one of these techniques.

1.1 Overview

Peios / Reference / netd / Introduction

netd is the Peios network manager. It is the executor of the interface layer of PNP, the Peios Network Policy: it reads which interfaces join which networks, and how they stand there, from Machine\System\Network, and makes the kernel match. It runs as a SYSTEM service started at boot, and it is the only program on a Peios machine that configures links, addresses and routes.

Three decisions shape everything else in this manual.

It is a reconciler, not a command interpreter. netd keeps no list of things it has done. On every input — a kernel link or address event, a registry change, a DHCP or router-discovery packet, a timer, a control request — it re-derives what each interface should look like and applies the difference from what the kernel reports. Nothing happens imperatively in a handler. Two consequences follow directly: a manual change to an interface netd manages lasts until the next pass, and a restarted netd derives its desired state afresh. While its first INIT-REBOOT is pending, it preserves the requested IPv4 address already installed and applicable netd-owned routes (§2.1). Static configuration is desired from the first pass and stays.

It owns addresses wholly and routes only by mark. On an interface netd has joined, every IPv4 address and every non-link-local IPv6 address is netd's: anything else is removed. Routes are netd's only when they carry routing protocol 200, the number netd stamps on every route it adds, so a route another program adds for itself survives. The kernel's own IPv6 link-local address is never touched.

It is the only router-advertisement listener. netd switches the kernel's own RA processing off on every interface before it does anything else, and acts on advertisements itself, so exactly one place decides what an advertisement means. The kernel still makes link-local addresses and answers neighbor solicitations; everything an advertisement could configure — addresses, the default route, DNS, the MTU — is netd's decision, filtered through the interface's profile.

netd builds and judges the interface layer with pnp-core, the same engine the kernel's NTFE uses for the packet layers, so a rule means the same thing in every layer. The kernel never reads Rules\Interface; netd never reads the packet layers. Each executor validates and refuses its own layers on its own.

1.1.1 Where netd sits #

   registry (Machine\System\Network)          peinit
        │ Rules\Interface, Profiles,            ▲ READY=1, LEVEL=<level>
        │ Hostname, Duid, ControlSecurity       │
        ▼                                       │
   ┌─────────────────────── netd ──────────────────────┐
   │ interface layer (pnp-core) → profile per interface │
   │ DHCPv4 · router discovery/SLAAC · DHCPv6           │──▶ rtnetlink (links,
   │ reconciler · network identification                │     addresses, routes)
   └────────────────────────────────────────────────────┘
        │ Interfaces\<id>\Status, Networks\<id>,        │ /run/netd/control.sock
        │ Readiness                                     ▼
        ▼                                         net, resolvd (subscribe)
   registry (written back)

What netd writes back to the registry is read by others: the kernel reads each interface's Status Network to give the packet layers their Network.* facts (PKM §6.5), services and scripts watch Readiness, and resolvd subscribes to netd's DNS snapshots over the control socket (PSPU §6.9).

1.1.2 What netd does not do #

  • Answer names. netd reports what each interface contributes to name resolution; resolvd routes and answers queries.
  • Filter packets. The packet layers are NTFE's. netd's own DHCP and router-discovery traffic passes them only because the shipped baseline policy permits it.
  • Decide who can bind a port. That is the kernel's port reservation table.
  • Associate with wireless networks. A supplicant brings a wireless link up; netd then treats it as any other interface.
  • Hold leases across a reboot. Nothing about a lease is persisted; a rebooted machine asks for the address its network last gave it (§5.7).

1.2 What This Manual Covers

Peios / Reference / netd / Introduction

This manual describes netd as built: the netd workspace's netd daemon, the dhcp4, dhcp6, and ndp state machines, and the net command. It also covers the public libnetd.so.1 client library, its Rust wrapper, and the internal netd-core policy and protocol types. The source version is 0.1.8; this manual does not establish installation or release qualification.

1.2.1 What is covered elsewhere #

SubjectWhere
The interface layer's vocabulary — facts, verdicts, the collation laws — and every profile value, as an operator writes themThe network policy reference (~peios/networking/network-policy-reference)
The rule engine itself: ingestion, conditions, collation, refusalKernel TRM chapter 6 (PKM §6.4, §6.5); netd links the same pnp-core crate
The kernel's side of the network context — how Status Network becomes Network.* facts in the packet layersPKM §6.5
The netd → resolver channel's contractPSPU §6.9
What a resolver does with the snapshotsPSPU book 6 and the resolvd manual
The query-channel framing the control socket usesPSPU book 3
How peinit holds a service until a readiness level is publishedThe peinit manual
Every registry value netd reads or writes, one entry eachregman 'Machine\System\Network' on a Peios machine

Where this manual and the network policy reference both mention a profile value, the reference owns the meaning and this manual owns what netd does with it: how the value is parsed, when it takes effect, and how it combines with what a network offers.

1.2.2 Conventions #

Section numbers in this manual are written §n.m. A reference into another book is qualified with the book's short name: PKM §6.5 is the Kernel TRM, PSPU §6.9 the userspace protocols book.

Times are given as netd's monotonic clock sees them. Every timer netd runs — DHCP retransmission, lease boundaries, advertisement lifetimes, solicitation backoff — is measured on CLOCK_MONOTONIC, so setting the wall clock moves none of them.

1.3 Terminology

Peios / Reference / netd / Introduction

Terms from the policy language — rule, fact, verdict, backstop, priority, exception — mean what the network policy reference says. The terms below are netd's own.

TermMeaning
interfaceA kernel network link netd has seen, keyed by its kernel index while it exists and named in the registry by its interface id.
interface idA UUID-shaped digest of an interface's bus path and MAC (§4.1). Stable across boots and kernel renames.
verdictWhat the interface layer said about an interface: JOIN(profile), IGNORE, or DOWN.
joined (managed)An interface whose verdict is JOIN. Loopback is never joined. Only joined interfaces get clients, contribute readiness, and appear in DNS snapshots.
profileA resolved key under Profiles\, inheritance applied: how a joined interface stands on its network.
generationOne build of the interface layer and the profiles from one reading of the registry. netd holds the last good generation; a refused one changes nothing.
passOne run of netd's converge sequence (§2.2): identify networks, judge links, start or stop clients, reconcile, publish.
desired stateWhat one interface should look like: up or down, its MTU, its addresses and its routes (§4.2).
reconcileDiffing desired state against the kernel's and applying the difference (§4.3).
networkWhat is on the other side of a joined interface's carrier, identified from what it has offered (§7.1) and recorded under Networks\<id>.
offerEverything a network has said: a DHCPv4 lease, router advertisements, a stateless DHCPv6 reply.
levelHow far an interface has got toward being usable: absent, link, addressed, or routed (§8.2).
scopeWhat one interface contributes to name resolution, as sent to resolvd (§8.3).

2.1 Startup

Peios / Reference / netd / The Daemon

Startup reads configuration and kernel state before the first reconciliation. A restart can preserve applicable IPv4 state while the lease is revalidated.

2.1.1 The service definition #

The netd package ships its service definition as a registry seed, netd-service.reg, applied by an image that names it. The definition:

ValueSettingWhy
ImagePath/usr/sbin/netd
Triggersboot
IdentitySYSTEMrtnetlink changes, the packet socket, and a bind to udp/68 each need a privilege only SYSTEM holds
Providesnetworkthe role a dependent names: Requires = ["network:routed"]
Readiness0 (Notify)readiness is READY=1 on the notify socket
RuntimeDirectoriesnetdpeinit creates /run/netd for the control socket
RestartPolicy2 (Always)a stopped network manager is a machine whose leases silently expire
ErrorControl0

The same seed declares /var/state/netd as the required netd-state entry under Machine\System\Init\ProvisionedPaths. peinit creates it before phase 2 with a SYSTEM-owned, protected inheritable descriptor granting full control to SYSTEM and Administrators:

O:SYG:SYD:P(A;OICI;GA;;;SY)(A;OICI;GA;;;BA)

The image or installer supplies /var/state; peinit does not create unnamed parents.

A second seed, netd-default-profile.reg, ships the baseline policy: the profile default and the rule wired (§3.1). It is separate so an image can run netd without agreeing that every wired interface joins whatever it is plugged into.

2.1.2 The startup sequence #

netd does these steps in this order:

  1. Opens rtnetlink: one socket for requests and dumps, and a second subscribed to the link, IPv4 and IPv6 address, and IPv4 and IPv6 route multicast groups. Failure is fatal.
  2. Opens the control socket at /run/netd/control.sock, removing a stale one first (§9.1). Failure is fatal.
  3. Opens the udp/68 absorber (§5.6). Failure is a warning: netd runs without it, and a DHCP server's unicast reply can draw an ICMP port-unreachable from the kernel.
  4. Switches the kernel's RA processing off on every interface that exists, and in all and default (§6.1). This happens before any link is brought up.
  5. Reads the configuration (§2.3) and builds a generation from it (§3.2). A generation that fails to build at startup is logged as refused, and netd runs with an empty policy, so the backstop ignores every interface until a good generation is written.
  6. Arms the registry watch on Machine\System\Network. Failure is a warning, and the configuration is then read once, never again.
  7. Dumps the kernel's state (links, addresses and routes, both families). Failure is fatal.
  8. Runs the first pass (§2.2): every interface is judged, every static address applied, every client that is due started.
  9. **Sends READY=1 ** on the notify socket.

Readiness is reported after the first pass, not after any lease arrives. A lease is a network event, not a startup one. A service that needs an address waits on a readiness level (§8.2), not on netd being ready.

A tie between two rules is not checked at startup: the startup build refuses a generation only for the build errors of §3.2. A tie present at startup is judged per interface as a conflict (§3.3), so the interfaces it covers are ignored with a warning rather than the generation being refused.

If Machine\System\Network does not exist when netd starts, the configuration is empty and the watch cannot be armed, so a key created later is never read; a restart of netd picks it up.

2.1.3 Restart #

netd re-derives everything from the registry and the kernel. Its DHCP clients start again, and a client remembers nothing across a restart: each one begins with an INIT-REBOOT request for the address its network last leased (§5.7), and holds no lease until that request is answered.

During an interface's first DHCP start in this process, netd preserves its requested IPv4 address at the prefix already installed in the kernel. It also preserves its netd-marked IPv4 routes while Route.Offered allows them; an explicit Route.Gateway takes precedence and the current profile's metric applies. This provisional state lasts only while INIT-REBOOT is pending. An unchanged ACK replaces it with the confirmed lease without deleting the address or route, so IPv4 readiness stays in place.

A NAK or two unanswered requests end revalidation and discard the provisional state as the client enters fresh discovery (§5.2). Carrier loss or a changed profile clears it too. Later client restarts in the same process do not adopt kernel state again. A requested address that is not already installed is never added merely because it was remembered.

This is not a restored lease: no lease duration, expiry, DNS servers, or other offered information is inferred from the installed address. Status still reports no lease until the ACK. DHCP-provided DNS information and IPv6 router-discovery state must be reacquired; this does not promise that every aspect of a daemon restart is invisible. IPv6 addresses and routes from advertisements remain desired only after discovery hears the routers again (§6.1). Static addresses are desired from the first pass and stay.

2.2 The Loop

Peios / Reference / netd / The Daemon

netd is one thread around one poll(2). Every input is a descriptor in the poll set or a timer deadline, and every handler records what it learned and lets the end of the iteration act on it. Because there is one thread, a handler that blocks holds everything up: no DHCP timer fires and no kernel event is read until it returns.

2.2.1 Inputs #

InputDescriptorWhat it leads to
Kernel eventsthe rtnetlink multicast socketa fresh dump, then a full pass
Registry changesthe watch on Machine\System\Networka reload (§2.3), then a full pass
udp/68 absorberthe absorber socketdrained and discarded
DHCPv4 repliesone packet socket per running clientthe client's actions; a reconcile if the network changed
Router advertisementsone ICMPv6 socket per interface doing router discoverythe engine's actions; a full pass if anything changed
DHCPv6 repliesone UDP socket per running DHCPv6 clientthe client's actions; a reconcile if the DNS facts changed
Control requeststhe listener and accepted client socketsthe request (§9.2); reconcile runs a full pass
Timethe earliest deadline of any clientevery client's timers, each acted on as above

The poll timeout is the earliest deadline any DHCPv4, router-discovery or DHCPv6 client holds, or a pending control request or reply holds (§9.1); with none, netd waits indefinitely. A deadline already acted on is not held again: once an address is deprecated, its preferred lifetime is behind it, and its next deadline is the end of its valid lifetime. So netd sleeps while addresses sit deprecated, which on an IPv6 network with temporary addresses is most of the time.

After a kernel event netd does not fold the event into its model. It dumps the whole state again and always runs a full pass, because a dump taken after an apply can already show a state whose consequences have not been decided yet.

2.2.2 A full pass #

A full pass runs these steps, in this order:

  1. identify networks on joined interfaces with carrier (§7.1);
  2. bring the interface table in line with the kernel's links and judge every non-loopback interface (§3.3), stopping the clients of an interface that lost carrier or whose outcome changed;
  3. start DHCPv4 clients where due (§5.1);
  4. start or stop router discovery and DHCPv6 (§6.1, §6.3);
  5. reconcile every interface (§4.3) and dump the kernel's state again.

It then repeats steps 1 to 5 while the dump differs from the one before the reconcile. The steps run at most four times in one pass, the first run included, even if the dump is still changing after the fourth.

Applying changes alters what the next decisions see: bringing a link up gives it carrier, carrier starts a DHCP client, and a lease adds an address. One pass would leave that chain waiting for a later event that, on a virtual NIC, has already arrived.

After the repeats, the pass applies the hostname (§8.4) and publishes: the machine level to peinit and the registry, every joined interface's Status, and a DNS snapshot to subscribers if it changed (§8.2, §8.3).

2.2.3 Reconcile without a full pass #

A DHCPv4 lease arriving, a lease being lost, link-local fallback, and a DHCPv6 answer each change only what an interface should carry, so they lead to a reconcile of every interface, the hostname, and a publish, without re-judging anything. If the same iteration also needs a full pass, only the full pass runs.

A DHCPv4 lease also marks its interface for re-judgment, because the network on the other side might now be identifiable (§7.1). Any interface so marked makes the iteration run a full pass.

2.3 Reading the Registry

Peios / Reference / netd / The Daemon

netd reads its configuration from Machine\System\Network, whole, every time it reads it.

2.3.1 What is read #

Value or keyUsed for
Hostname (REG_SZ)the machine's name (§8.4). An empty string counts as unset.
ControlSecurity (REG_BINARY)the control object's descriptor (§9.1). An empty value counts as unset.
Duid (REG_SZ)the machine's DHCP unique identifier, as hex (§5.7). Invalid hex rejects the configuration read.
Rules\Interface\ and everything under itthe interface layer (§3.2)
Profiles\ and everything under itthe profiles (§3.1)

Nothing else under the key is configuration to netd. Interfaces\ and Networks\ are read only for the values netd shares with the operator (§5.7, §7.2), at the moment it needs them.

A missing Machine\System\Network means no configuration: no hostname, no rules (so the backstop ignores every interface), no profiles.

2.3.2 Lowering #

Every value in the two trees is lowered to one of four shapes before anything interprets it:

Registry typeLowered to
REG_DWORD (4 bytes)an integer
REG_QWORD (8 bytes)an integer
REG_SZ, REG_EXPAND_SZa string, cut at the first NUL; invalid UTF-8 rejects the read
REG_MULTI_SZa list of strings with empty items removed; invalid UTF-8 rejects the read
anything else, or a DWORD or QWORD of the wrong lengthother

The rule builder refuses an other by name (§3.2), and the profile parser refuses it as a value of the wrong shape (§3.1), so an unusable value is never silently dropped. The default (unnamed) value of a key is skipped in both trees.

Values and subkeys are sorted by name, so two readings of an unchanged tree compare equal.

The root of each tree is depth zero. A leaf at depth 16 is accepted, but children below it reject the read instead of producing a partial tree.

A failed value query, failed child enumeration, unreadable child, or invalid UTF-8 name rejects the entire read. An enumerated child that disappears before it can be opened also rejects the read. Missing optional keys and values remain valid absences; permission and I/O errors do not mean absence.

At startup, an incomplete read stops netd. During a reload, it logs the error and retains the last complete configuration, including the control security descriptor. The next registry notification triggers another attempt. This completeness check does not turn separate registry calls into an atomic snapshot: concurrent successful writes can still span a read.

2.3.3 A registry change #

The watch is armed on the whole Machine\System\Network subtree. On any event, netd reads the whole configuration again and compares it with what it holds:

  • If anything differs, the control object is rebuilt from ControlSecurity. If the rules or the profiles differ, a new generation is built (§3.2), and taken or refused.
  • After a complete read, a full pass follows even if nothing differs.

netd's own writes to Interfaces\ and Networks\ come back through the same watch. They cause a reload that finds nothing changed, and a pass that plans nothing.

A failed read of the watch's events re-arms the watch.

There is no reload command: a write is noticed within the time it takes the watch to deliver and a pass to run.

3.1 Profiles

Peios / Reference / netd / The Interface Layer

The profile vocabulary — what each value means to an operator — is the network policy reference's (~peios/networking/network-policy-reference#profiles). This article is what netd does with it.

3.1.1 Resolution #

Every key under Profiles\ is a profile, at every depth, named by its path below Profiles with / between levels. The Profiles key's own values are ignored.

Profiles are looked up case-insensitively: netd keys them by the lower-cased path and keeps the path as written for display and for Status Profile.

A key whose name is empty or contains / or \ refuses the generation.

3.1.1.1 Inheritance #

A profile's effective values are its ancestors' values with its own laid over them, per value name. A value a profile names replaces the inherited one whole — a list replaces a list, never appends to it — and a value it does not name is inherited. Value names compare case-insensitively, so address.offered overrides Address.Offered.

Each profile is parsed from its own effective values. A malformed value in a parent therefore refuses the generation at the parent, before any child is reached.

3.1.1.2 Enabled #

Enabled is a profile's switch, not a value: it is never inherited as one. A profile is enabled when its own Enabled and every ancestor's say so; absent means enabled. A child cannot re-enable itself under a disabled parent. A disabled profile is still resolved and parsed — a malformed value in it still refuses the generation — but a rule that names it abstains (§3.2).

Enabled accepts the boolean shapes below; anything else refuses the generation.

3.1.2 Accepted shapes #

Every value is parsed from its lowered form (§2.3):

ShapeAccepted
booleanan integer (non-zero is true), or a string on, yes, true, 1, off, no, false, 0 in any case
numbera non-negative integer that fits 32 bits, or a string of one, surrounding space trimmed
lista multi-string (empty items dropped), or a single string as a one-item list; an empty string is the empty list
stringa string, or an integer written as its decimal text

A value of any other shape — a list where a boolean belongs, a binary value — refuses the generation with the message profile <path>: <name> has the wrong shape, where <name> is the value's name in lower case.

3.1.3 Values #

ValueShapeWhat netd does with it
Address.Offeredbooleanruns a DHCPv4 client while IPv4 is in the families, and router discovery while IPv6 is
Address.Familieslistitems ipv4 and ipv6, in any case. The list replaces the default of both, so an empty list means neither family. Any other item refuses the generation.
Address.Staticlisteach item address/prefix, either family, prefix at most 32 or 128. An item that does not parse refuses the generation.
Address.LinkLocalbooleanlink-local fallback (§5.5)
Address.Temporarybooleantemporary IPv6 addresses (§6.2)
Address.OnExpirystringDrop or Keep, in any case. Anything else refuses the generation.
Route.Offeredbooleantakes the lease's gateway and classless routes and the routers' default route (§4.2)
Route.Gatewaylisteach item an address of either family. The last IPv4 item is the IPv4 gateway, the last IPv6 item the IPv6 gateway. An item that does not parse refuses the generation.
Route.Metricnumberthe metric of every route netd adds for the interface, and its place in DNS scope order
Mtu.Offeredbooleantakes the lease's MTU, else the routers'
Mtu.Valuenumberthe MTU to set. Below 68 refuses the generation.
Hostname.Announcebooleansends the machine's Hostname in DHCP option 12
Hostname.Offeredbooleanadopts a lease's hostname when Hostname is unset (§8.4)
Dns.Offeredbooleanadds the network's DNS servers and search domains after the profile's own (§8.3)
Dns.Serverslisteach item an address of either family. An item that does not parse refuses the generation.
Dns.Domainslisttaken as written; nothing validates a domain
Dns.Defaultbooleanpresent sets the scope's default-route flag; absent follows the interface's level (§8.3)
Dns.Exclusivebooleansets the scope's exclusive flag

A value name not in this table (case-insensitively) refuses the generation with profile <path>: unknown value <name>, the name as written.

After parsing, any Address.Static entry outside the profile's families is dropped without an error: the family switch wins.

3.1.4 A bare profile #

Every compiled default is false, empty or absent, apart from the families (both) and OnExpiry (Drop). A profile that sets nothing therefore brings its interface up and does nothing else: no clients, no addresses, no routes, no DNS. The friendly behavior of the shipped default profile is four values in its seed: Address.Offered, Address.LinkLocal, Route.Offered and Dns.Offered, each 1.

3.2 Building a Generation

Peios / Reference / netd / The Interface Layer

A generation is built whenever the rules or the profiles have changed (§2.3), and once at startup.

3.2.1 The order of the build #

  1. Profiles are resolved (§3.1). Any error refuses the generation.
  2. If Rules\Interface does not exist, the generation has no forest. Every interface meets the backstop, IGNORE, and the profiles are kept for nothing to name.
  3. Each subkey of Rules\Interface is a root rule. Its tree is lowered to pnp-core's input and built as the Interface layer with build_forest — the same ingestion, condition parsing, and lints the kernel applies to the packet layers (PKM §6.5). Every build error refuses the generation.
  4. Every profile a JOIN names is looked up. A JOIN naming no profile refuses the generation with JOIN(<path>) names no profile.

3.2.2 Lowering a rule #

Integers and strings pass through. A value of any other lowered shape (§2.3) refuses the generation with rule <path>: value <name> has an unsupported type.

A list is passed through item by item, except in Actions. There, an item that is a JOIN naming a profile that exists and is disabled is replaced by NULL before the build, so the rule abstains and the forest's own collation answers without it: its parent, another tree, or the backstop. A JOIN of a disabled profile is not a fault.

A JOIN target is recognized loosely. Whitespace anywhere is ignored, JOIN( matches in any case, \ in the path is read as /, and the path is compared case-insensitively. So join ( Office\London ) names the profile office/london.

3.2.3 What refuses a generation #

Everything pnp-core refuses at the interface layer refuses it here, with netd's wording:

CauseMessage
An unknown fact in a conditionrule <path>: unknown fact <key>
A malformed operatorrule <path>: bad operator in <key>
A malformed patternrule <path>: bad pattern in <key>
Actions not a listrule <path>: Actions is not a list
A malformed actionrule <path>: bad action (…)
An action the interface layer does not speak (PASS, DROP, TAG, …)rule <path>: an action the interface layer does not speak
A key that does not exist at the interface layerrule <path>: <key> does not exist at the interface layer
Present on a fact never present at this layerrule <path>: <key> on a fact that never exists at this layer
Priority not an integerrule <path>: Priority is not an integer
Enabled not 0 or 1rule <path>: Enabled is not 0 or 1
A malformed rule namerule <path>: bad name
A JOIN naming no profileJOIN(<path>) names no profile
A malformed profilethe profile parser's message (§3.1)

The depth of a rule tree refuses nothing. It is bounded only by netd's registry read, which takes rules to 16 levels below Rules\Interface and ignores anything deeper (§2.3).

A condition on a fact that exists in the vocabulary but can never be present at the interface layer, such as DstPort, is not refused. It is a lint: logged as a warning, rule <path>: <key> can never hold at the interface layer, and the generation is taken.

3.2.4 A tie refuses at runtime #

A generation built while netd is running is judged against every non-loopback interface before it is taken. If any interface meets a conflict (two rules tied on priority naming different profiles, §3.3), the generation is refused with rules <a> vs <b> tie on interface <name>.

3.2.5 Taken or refused #

A taken generation replaces the old one whole, clears any recorded refusal, and is logged with its counts of rule trees and profiles. The pass that follows judges every interface against it.

A refused generation changes nothing. The last good generation stays in force, netd logs interface layer refused: <why>; the last good generation stands at error level, and records the reason, which status reports as refusal and net status prints as a policy REFUSED line. The refusal stays recorded until a generation builds.

The interface layer's refusal is netd's alone. The kernel reads the packet layers from the same registry state and refuses or takes them on its own (PKM §6.5): a dangling JOIN never stalls the firewall, and a bad Flow rule never stops an interface joining.

3.3 Judging an Interface

Peios / Reference / netd / The Interface Layer

netd evaluates interface facts against the accepted policy generation. The result determines whether it ignores, stops, or configures that interface.

3.3.1 The facts #

An interface is judged on a snapshot carrying only interface and network facts:

FactValue
Interfacethe kernel's name for the link
Interface.Kindwired, wireless, loopback, or other (§4.1)
Interface.Idthe interface id (§4.1)
Interface.Macthe hardware address, when the link has a 6-byte one
Interface.Paththe bus path; absent when sysfs gives none
Interface.Driverthe driver; absent when sysfs gives none
Network.Idthe id of the network identified on the link (§7.1); absent until one is
Network.Namethe record's Name; absent when unset or empty
Network.Trustthe record's Trust; absent when unset or empty
Network.Kindthe interface's kind, once a network is identified; absent before

A fact the interface lacks is absent, which makes a condition on it false, never an error.

3.3.2 When an interface is judged #

Every non-loopback interface is judged on every full pass (§2.2). Loopback is never judged and never managed: it has no verdict, no record under Interfaces\, and netd never changes it.

3.3.3 The verdict #

pnp-core evaluates the forest and netd reads the result:

  • JOIN(i): the profile the forest's i th JOIN names, looked up case-insensitively. netd stands the interface in that profile.
  • DOWN: the interface is kept administratively down.
  • anything else, including the backstop: IGNORE.

The attribution is the evaluation's: the path of the rule that spoke, or backstop when none did.

3.3.4 Conflicts #

When the evaluation reports a conflict — the highest-priority candidates tie and name different profiles — netd does not choose. The interface's outcome is IGNORE, its attribution is the tied rules' paths, sorted and joined with vs, and its warning is rules <a> vs <b> tie; the interface is ignored. The first time an interface meets a conflict, netd logs a warning.

A conflict reaches an interface in two ways. A generation taken at startup is not checked for ties (§2.1), and an interface that appears after a generation was taken is judged against it with no check. A generation built at runtime that ties on an interface already present is refused instead (§3.2).

3.3.5 A change of verdict #

The outcome compares the verdict and the profile's resolved values. When either differs from the interface's previous outcome, netd logs the new verdict and its rule, and stops the interface's clients:

  • the DHCPv4 client sends a RELEASE if it holds a lease (§5.4) and is discarded, along with its lease and any link-local address;
  • router discovery and DHCPv6 are discarded, and their addresses go at the next reconcile.

The pass then starts whatever clients the new outcome wants. Editing any value of the profile an interface stands in is a change of outcome, so it restarts the interface's clients against the new profile, rather than trusting a lease obtained under the old one.

3.3.6 What each verdict does #

VerdictClientsDesired state (§4.2)
JOIN(profile)started as the profile asksup, with the profile's addresses and routes
DOWNnonedown, carrying no addresses, and no netd routes
IGNOREnonenone: netd plans nothing for the interface

An IGNORE d interface is left exactly as it is. If it was joined before, the addresses and routes netd gave it stay where they are, because nothing desires their removal.

4.1 Identity and Carrier

Peios / Reference / netd / Interfaces

An interface has a stable Peios identity as well as its kernel name and index. Carrier changes determine when its network clients start and stop.

4.1.1 Kind #

netd classifies each kernel link once per dump:

LinkInterface.Kind
the loopback flag setloopback
link type Ethernet, with /sys/class/net/<name>/wireless or /sys/class/net/<name>/phy80211 presentwireless
link type Ethernet otherwisewired
any other link typeother

A bridge, a veth, or a TAP device has link type Ethernet and is wired.

4.1.2 Bus path and driver #

The bus path comes from sysfs. netd resolves /sys/class/net/<name>/device and walks up from it to the nearest ancestor whose name is a PCI address (dddd:bb:dd.f), and names it pci-<address>. A device with no PCI ancestor is named by the device's own directory name. A link with no device (a virtual device) has no bus path. A virtio NIC sits one level below its PCI function, so it is named by the function.

The driver is the name the device/driver link points at (virtio_net, for example), and empty when there is none.

Both are read once, when netd first sees the link.

4.1.3 The interface id #

The interface id is a SHA-1 digest of the bytes peios-netd-ifid|, then the bus path if there is one, then |, then the six MAC bytes — or, for a link with no 6-byte hardware address, its name. The first 16 bytes of the digest are stamped as a version 5, RFC 4122 variant UUID and written in lower-case hyphenated form.

So the same card in the same slot has the same id on every boot, however the kernel names it, and a renamed link keeps its id. A virtual device has no bus path, so its id follows its MAC alone.

The id is the key of the interface's record under Interfaces\ (§8.1), the Interface.Id fact, the key of the RFC 7217 address derivation (§6.2), and the basis of its DHCP IAID (§5.7).

4.1.4 Appearing and disappearing #

When netd first sees a link, it reads the link's identity, logs interface <name> (<path>) is <id>, and, unless it is the loopback, writes accept_ra = 0 for it (§6.1).

When a link disappears from the kernel's dump, netd drops it and everything it held: its clients, lease, network, and judgment. Nothing is sent on the wire. Its record under Interfaces\ stays.

4.1.5 Carrier #

netd counts an interface as having carrier when it is administratively up and the kernel reports IFF_LOWER_UP. When an interface that had carrier loses it, netd logs interface <name>: carrier lost and:

  • stops its DHCPv4 client: a RELEASE is sent if a lease was held, and the lease and any link-local address are forgotten (§5.4);
  • stops router discovery and DHCPv6;
  • forgets the network identified on it (§7.1), so Status Network is cleared and the Network.* facts go absent, for netd's own judgment and the kernel's packet layers alike.

The next reconcile then removes the leased and autoconfigured addresses and the routes that depended on them, because nothing desires them any more. Static addresses stay.

When carrier returns, the pass starts the clients again from scratch (§5.1, §6.1), and the DHCPv4 client asks first for the address the network last gave (§5.7).

4.2 Desired State

Peios / Reference / netd / Interfaces

On every reconcile netd computes, for each interface, what it should look like. That desired state is a link state, an MTU, a set of addresses and a set of routes. It is derived from the interface's verdict, its profile, and its clients' current state. During the first INIT-REBOOT it also includes the provisional IPv4 kernel state described in §2.1; netd keeps no general record of what it applied.

4.2.1 By verdict #

  • Loopback, or an IGNORE d interface: there is no desired state, and netd plans nothing for the interface.
  • DOWN: the link down, with no addresses and no routes.
  • JOIN: the link up, and everything below.

4.2.2 The metric #

Every route netd adds for an interface carries the interface's metric: the profile's Route.Metric when it is set, otherwise 600 for a wireless interface and 100 for anything else.

4.2.3 The MTU #

The profile's Mtu.Value when set. Otherwise, with Mtu.Offered, the lease's MTU (DHCP option 26), else the routers' advertised MTU (§6.1). Otherwise no MTU is desired and the link's MTU is left as it is.

4.2.4 IPv4 addresses #

  • every IPv4 entry of Address.Static, at its prefix;
  • the lease's address at the lease's prefix (§5.3), when a lease is held;
  • while the first INIT-REBOOT is pending, the requested address at its already-installed prefix (§2.1);
  • the link-local address (§5.5) at prefix 16, only when the client has fallen back to one and no lease is held and the profile has no static address of either family.

The order in which they are listed, or written in Address.Static, has no effect. netd adds the addresses an interface lacks in ascending address order (§4.3), and the kernel makes an address primary only when the interface holds no other address in the same subnet, so the first one added in a subnet is its primary. Of two statics in one subnet written 10.0.0.9/24, 10.0.0.3/24, both added in one pass, 10.0.0.3 is the primary.

While a lease that carried a broadcast address (option 28) is held, that broadcast is the one netd sets on every IPv4 address it adds to the interface: the lease's own address, and a static added in that time, whatever its subnet (§4.3).

4.2.5 IPv4 routes #

  • The default route goes through Route.Gateway's IPv4 entry when it is set. Otherwise, with Route.Offered, it goes through the lease's gateway: the first router of option 3, or, when the lease carried classless routes, the gateway of the classless 0.0.0.0/0 route. With neither, there is no IPv4 default route.
  • Classless static routes (option 121) with a prefix above zero are added, each through its gateway, only with Route.Offered.

During the first INIT-REBOOT, existing netd-marked IPv4 routes accompany the provisional address when Route.Offered is enabled. The profile's explicit gateway and current metric still take precedence (§2.1).

Route.Gateway is used as written; netd does not check that the gateway is on a subnet the interface has. A gateway the kernel cannot reach makes the route's add fail on every reconcile, logged each time (§11).

4.2.6 IPv6 addresses #

  1. every IPv6 entry of Address.Static, at its prefix, preferred, with a prefix route;
  2. every address router discovery wants (§6.2): stable-privacy and temporary addresses, each deprecated or not, each with or without a prefix route according to the prefix's on-link flag.

4.2.7 IPv6 default route #

Through Route.Gateway's IPv6 entry when it is set. Otherwise, with Route.Offered, through the default router router discovery has chosen (§6.1). With neither, there is no IPv6 default route.

4.2.8 Not desired #

netd never desires the kernel's own IPv6 link-local address, the kernel's prefix routes, or any route without netd's protocol mark. Those are outside what reconciliation compares (§4.3).

4.3 Reconciliation

Peios / Reference / netd / Interfaces

Reconciliation compares desired interface state with a complete kernel snapshot. It orders changes so addresses and routes converge without removing state owned by another route manager.

4.3.1 What netd owns #

On an interface with a desired state:

  • Every IPv4 address, including a 169.254 address, and every IPv6 address except a link-local one is netd's. An address netd does not desire is removed, whoever added it.
  • A route is netd's only if it carries routing protocol 200 (RTPROT_NETD). netd stamps it on every route it adds, and removes no route without it.
  • The kernel's IPv6 link-local addresses (fe80::/10) are never compared, added, or removed. Every up interface has one, and neighbor discovery needs it.

Only routes in the main table, of unicast type and with an output interface, are read from the kernel at all.

4.3.2 The plan #

For each interface with a desired state, netd plans these operations, in this order:

  1. Link up, if it is desired up and is down.
  2. MTU, if one is desired, differs from the link's, and is at least 68.
  3. Address deletions: every address netd owns whose address and prefix length together match no desired address.
  4. Address additions: every desired address the kernel does not hold with the same flags, in ascending address order, IPv4 before IPv6.
  5. Route deletions: every protocol-200 route on the interface that is not desired.
  6. Route additions: every desired route the kernel does not hold.
  7. Link down, if it is desired down and is up — last, after its addresses, and routes have gone.

Addresses compare by address and prefix length, plus the two flags netd sets: deprecated and no-prefix-route. A tentative flag (duplicate address detection still running) is erased before comparing. A change of flags alone is therefore an addition of the same address, which replaces it (below), never a delete and re-add that would reset standing connections.

An IPv4 address's broadcast address is not compared. An address keeps the broadcast it was added with: a lease whose broadcast changes, or a lease that arrives after a static was added, changes nothing on an address the interface already holds.

Routes compare on everything: destination, prefix length, gateway, metric, and protocol. A change of metric or gateway is a deletion and an addition. For IPv6 routes, configured metric zero uses the kernel default of 1024: netd sends and compares that effective value, so an unchanged route converges. IPv4 metric zero and all nonzero metrics are unchanged. The configured Route.Metric still controls DNS scope ordering.

An interface whose desired state the kernel already matches gets an empty plan, and nothing is sent.

4.3.3 Applying #

Operations are applied one at a time, each as an rtnetlink request with an acknowledgment:

OperationRequest
link up or downRTM_SETLINK changing only IFF_UP
MTURTM_SETLINK with IFLA_MTU
address addRTM_NEWADDR with NLM_F_CREATE and NLM_F_REPLACE
address deleteRTM_DELADDR
IPv4 route addRTM_NEWROUTE with NLM_F_CREATE and NLM_F_APPEND, main table, protocol 200
IPv6 route addRTM_NEWROUTE with NLM_F_CREATE and NLM_F_EXCL, main table, protocol 200
route deleteRTM_DELROUTE

IPv4 route additions append a distinct gateway/interface at the configured metric. Two joined interfaces might therefore both hold default routes at the same metric; adding one preserves the other, and withdrawing one removes only its own route. Exact duplicates remain EEXIST. Equal-metric route selection follows the kernel's routing behavior; set distinct metrics when one interface should have a defined preference.

How addresses are phrased:

  • An IPv4 address carries IFA_LOCAL and IFA_ADDRESS set to itself, link scope for 169.254/16 and universe scope otherwise. Below a /31 it also carries a broadcast address: the broadcast of the lease the interface holds, if that lease gave one, otherwise the address's own subnet's all-ones address. The lease's broadcast goes on every IPv4 address added while the lease is held, statics included.
  • An IPv6 address carries universe scope and, when its prefix is not on-link, IFA_F_NOPREFIXROUTE. Its lifetimes are netd's to manage, so the kernel is told a valid lifetime of forever and a preferred lifetime of forever, or of zero when the address is deprecated. Source address selection then stops choosing a deprecated address, and connections already using it keep it.

A route with a gateway has universe scope, and one without has link scope. A route carries a metric only when it is above zero.

A failed operation is logged as reconcile: <operation> failed: <error> and the rest of the plan carries on, so one bad route never stops an address landing. EEXIST on an add and ENOENT or ESRCH on a delete mean the kernel got there first, and are not logged.

After every interface's plan is applied, netd dumps the kernel's state again, so readiness and the status reply describe what actually landed.

5.1 The Client

Peios / Reference / netd / Dhcpv4

netd's DHCPv4 client is the dhcp4 crate: the RFC 2131 state machine as a pure, clock-injected type, driven by netd's loop and sockets.

5.1.1 Starting and stopping #

On every full pass, for each joined interface:

  • the interface wants a client when its profile has Address.Offered and IPv4 in its families;
  • it can run one when it is up with carrier.

A running client is stopped (§5.4) in the step of the pass that brings the interface table in line with the kernel's links, before clients are started (§2.2):

  • when the link loses carrier or goes down, logged as interface <name>: carrier lost;
  • when the interface's outcome changes, logged as the new verdict (§3.3). Any edit to the profile the interface stands in is a change of outcome, so it stops the client even when the edited profile still wants one, and the same pass starts a new one.

Only a change of outcome changes what an interface wants, so a client its interface does not want is always stopped the second way. A link that leaves the kernel takes its client with it (§5.4).

An interface that wants and can run a client but has none starts one, logging interface <name>: dhcp starting, provided:

  • the link has a 6-byte hardware address — otherwise no client is started, silently;
  • its packet socket opens (§5.6) — otherwise netd logs no packet socket and tries again on the next pass.

A new client starts with no lease. It is configured with:

SettingValue
chaddrthe interface's MAC
client identifier (option 61)the interface's ClientId (§5.7)
hostname (option 12)the machine's Hostname, only when the profile has Hostname.Announce and Hostname is set
randomness8 bytes of /dev/urandom XORed with the interface index, seeding transaction ids and jitter
a previous addressthe RequestedAddress of the interface's network, if one is known; otherwise that of the network named by its Status LastNetwork (§5.7)

With a previous address the client begins in Rebooting (RFC 2131 §3.2, INIT-REBOOT). Without one it begins in Selecting.

5.1.2 States #

StateEnteredLeaves on
Selectingstart without a previous address; a NAK while requesting or rebooting; a request that went stale; a reboot nobody confirmed; a lost leasean acceptable OFFER
Requestingan OFFER in Selectingan ACK (Bound), a NAK (Selecting), four unanswered transmissions (Selecting)
Rebootingstart with a previous addressan ACK (Bound), a NAK (Selecting), two unanswered transmissions (Selecting)
Boundan ACKT1 (Renewing)
RenewingT1; or an operator renew while bound, renewing or rebindingan ACK (Bound), a NAK (lease lost, Selecting), T2 (Rebinding)
RebindingT2an ACK (Bound), a NAK or the lease's end (lease lost, Selecting)

The status reply shows a client's state only inside its lease, which is present only while the client holds a lease (§9.2), and net status prints it on the lease line. So the state shown is always bound, renewing or rebinding. A client in Selecting, Requesting or Rebooting holds no lease, and neither shows a state for it. The init state exists only between a stop and the client being discarded.

A new transaction id is drawn on entering Selecting, Rebooting, Renewing and Rebinding. Requesting keeps the id of the Selecting exchange it came from.

5.1.3 What every message carries #

Every message is a BOOTREQUEST with hardware type 1 and length 6, the current transaction id, chaddr, and secs set to the whole seconds since the client started, capped at 65535. Every message except a RELEASE carries, in this order:

OptionContent
53the message type
61the client identifier
57maximum message size 1500
55the parameter request list: 1, 3, 6, 12, 15, 26, 28, 42, 51, 58, 59, 119, 121
12the hostname, when configured

The encoded message ends with option 255 and is padded with zeros to 300 bytes. An option longer than 255 bytes would be cut to 255.

5.1.4 The messages #

MessageWhenBroadcast flagciaddrOption 50Option 54Sent
DISCOVERSelectingset0the address of a lease that expired, until a NAK or a reboot timeout forgets it—broadcast
REQUESTRequestingset0the offered addressthe offer'sbroadcast
REQUESTRebootingset0the previous address—broadcast
REQUESTRenewingclearthe lease address——unicast to the server
REQUESTRebindingclearthe lease address——broadcast
RELEASEa stop while holding a leaseclearthe lease address—the serverunicast to the server

A RELEASE carries only options 53, 54 and 61.

"Broadcast" and "unicast" are the paths of §5.6: a broadcast leaves the packet socket from 0.0.0.0 to 255.255.255.255, rebinding included; a unicast leaves an ordinary UDP socket bound to the lease address.

5.2 Timers

Peios / Reference / netd / Dhcpv4

Every timer is on netd's monotonic clock.

5.2.1 Retransmission while acquiring #

In Selecting, Requesting and Rebooting each transmission schedules the next one after the current backoff plus a jitter drawn uniformly from −1 s to +1 s, then doubles the backoff, up to 64 s. The backoff starts at 4 s on entering each of the three states. So transmissions follow at roughly 4, 8, 16, 32, 64, 64, … seconds.

StateTransmissions before it gives upThen
Selectingnever gives up—
Requestingfour REQUESTs (about 0, 4, 12 and 28 s)at the next timer, about 60 s, Selecting with a new DISCOVER
Rebootingtwo REQUESTs (about 0 and 4 s)at the next timer, about 12 s, Selecting with a new DISCOVER and no option 50

5.2.2 "Nobody answered" #

On the third retransmission of a DISCOVER — the fourth DISCOVER, about 28 s after the first — the client reports that no offer came. netd then records the interface warning asked for an address; nobody answered and, when the profile wants it, falls back to a link-local address (§5.5). The client keeps discovering. The warning survives full reconciliation passes, including the pass triggered by adding the link-local fallback. It clears when a lease binds or that DHCP client stops (for example, on carrier loss or a profile change). A rule-conflict warning takes display precedence; rejudging an unchanged client does not erase its discovery warning.

In source 23af1f6 , the report is made at most once between client starts: the flag is reset only when a client is started. A client that reported it, then got a lease, then lost it, does not report it again, so it does not fall back to a link-local address a second time.

The proposed source correction resets the flag after a valid ACK produces a lease. If that lease is later lost, unanswered discovery can report again at the same fourth-DISCOVER threshold, allowing the profile's link-local fallback to be requested again. An uninterrupted unanswered acquisition still reports only once: a malformed ACK, a NAK while Requesting, or a Requesting timeout does not rearm it. This describes the proposed source behavior, not a released package or an installed image; check the installed build before relying on repeat fallback.

5.2.3 Lease boundaries #

A lease's T1, T2 and length are measured from the moment its ACK arrived, and are fixed when the lease is read (§5.3).

  • At T1 a Bound client enters Renewing and sends a unicast REQUEST.
  • At T2 a Renewing client enters Rebinding and sends a broadcast REQUEST.
  • At the lease's end a Rebinding client loses the lease (§5.4) and enters Selecting.

A boundary is acted on before any retransmission due at the same moment.

5.2.4 Renewal retransmission #

Each REQUEST in Renewing or Rebinding schedules the next for half the time remaining to the state's next boundary (T2 while renewing, the lease's end while rebinding), but never sooner than 60 s from now. With a short lease the 60 s floor means a state's boundary usually arrives before its second REQUEST: a 20 s lease renews once at 10 s and rebinds once at 17 s, then lapses at 20 s.

An ACK in either state starts the lease's clock again from that moment.

5.3 Replies and Leases

Peios / Reference / netd / Dhcpv4

The DHCPv4 client accepts replies only when they match its exchange and contain a usable lease. The checks below define those boundaries.

5.3.1 Which replies are looked at #

A received message is ignored unless all of these hold:

  • it is a BOOTREPLY;
  • its transaction id is the client's current one;
  • its chaddr is the interface's MAC;
  • it carries a message type (option 53) the client knows.

5.3.2 The server lock #

Once a server has been chosen — the server of the lease held, or else the server identifier of the offer being requested — an ACK or NAK is accepted only if its option 54 names that server. A stranger who guesses the transaction id cannot take a lease away or substitute one.

In Rebooting, with no lease and no offer, no server has been chosen, so an ACK or NAK from any server is accepted.

5.3.3 What each state accepts #

StateMessageResult
SelectingOFFER with a non-zero yiaddr and a server identifiertaken: Requesting. The first acceptable OFFER wins; there is no comparison between offers.
SelectingOFFER without eitherignored
Requesting, Rebooting, Renewing, RebindingACK that reads as a lease (below)Bound, with the lease
Requesting, Rebooting, Renewing, RebindingACK that does not read as a leaseignored; retransmission continues
Requesting, RebootingNAKSelecting; the previous address and the offer are forgotten
Renewing, RebindingNAKthe lease is lost (§5.4); Selecting
any other combinationignored

An ACK in Renewing or Rebinding that grants a different address replaces the lease. The next reconcile removes the old address and adds the new.

5.3.4 Reading an ACK #

An ACK is a lease only when it has:

  • a non-zero yiaddr;
  • a server identifier (option 54);
  • a lease time (option 51) of exactly 4 bytes, and at least 4 seconds.

A lease time under 4 s is refused: it cannot hold T1 < T2 < lease, and a server asking for it wants the client to spin.

5.3.4.1 The prefix #

From the subnet mask (option 1) when it is a non-zero run of contiguous ones. Otherwise, absent or malformed, from the address's class: /8 for a first octet up to 127, /16 up to 191, /24 above.

5.3.4.2 Routes #

Classless static routes (option 121, RFC 3442) are read as a sequence of prefix length, the significant destination octets, and a 4-byte gateway. In source 23af1f6 , a prefix length above 32, or an entry running past the end of the option, makes the whole ACK fail to read as a lease: it is ignored like any other unusable ACK.

The proposed source correction instead discards the entire malformed optional route list, including any valid entries before the malformed one, and keeps an otherwise-valid lease. The existing router-option (3) fallback then applies; without that option, the lease has no routes or gateway. This recovery does not relax whole-message or option framing, the mandatory lease requirements above, or the client and server-identity checks. It describes the proposed source policy, not a released package or installed image, and does not assert an RFC requirement to recover malformed route lists.

When the decoded classless route list is nonempty, the router option (3) is ignored. The lease's gateway is the first router of option 3, or, when classless routes are present, the gateway of the classless route with prefix 0.

5.3.4.3 T1 and T2 #

  • T1 is option 58 when it is above 0 and below the lease time minus 2. Otherwise it is half the lease time.
  • T2 is option 59 when it is above T1 and below the lease time. Otherwise it is seven-eighths of the lease time, rounded down, raised to at least T1 + 1 and capped at the lease time minus 1.

So T1 < T2 < the lease time always holds, whatever the server sent.

5.3.4.4 Other options kept #

OptionKept as
6DNS servers, every 4-byte entry
15the domain name: the bytes up to the first NUL; dropped if not UTF-8
119the domain search list, RFC 1035 names with compression pointers followed, at most 16 jumps per name
12the hostname offered: the bytes up to the first NUL; dropped if not UTF-8
26the MTU, when it is at least 68
28the broadcast address
42NTP servers, every 4-byte entry

Where an option appears twice, its first occurrence is used. Nothing else in the ACK is kept.

How each of these is used — and whether, by the profile — is in §4.2 (addresses, routes, MTU), §8.3 (DNS and NTP) and §8.4 (the hostname).

5.3.5 The record of a lease #

A lease is logged as interface <name>: lease <address>/<prefix> from <server> for <seconds>s. Binding clears the interface's link-local address and its warning, and marks the interface for re-judgment, because the network might now be identifiable (§7.1).

5.4 Losing a Lease

Peios / Reference / netd / Dhcpv4

Lease expiry, network loss, and profile changes affect an interface differently. The configured expiry policy determines whether an expired address remains installed.

5.4.1 Lost by the network #

A lease is lost when a Rebinding client reaches the lease's end (§5.2), or when a NAK arrives while renewing or rebinding (§5.3). The client forgets the lease and enters Selecting, and netd acts on the interface's Address.OnExpiry:

  • Drop (the default): netd logs interface <name>: lease lost and forgets the lease. The next reconcile removes the address and the routes that came with it.
  • Keep: netd logs interface <name>: lease lost; keeping the address (Address.OnExpiry = Keep) at warning level and goes on desiring the lost lease — its address, gateway, and routes — while the client looks for a new one. The kept lease is replaced the moment a new one binds.

With Keep, the status reply's lease describes the client, not the kept lease: it disappears with the client's lease, while the address stays on the interface.

Keep lasts while the client lasts. A stop (below) forgets the kept lease as it would any other.

5.4.2 Stopped by netd #

netd stops a client when:

  • the interface's outcome changes: another verdict, another profile, or any value of its profile edited (§3.3);
  • the interface loses carrier (§4.1);
  • the profile does not want a client (§5.1).

A client in Bound, Renewing, or Rebinding sends a RELEASE to its server first: unicast from the lease address (§5.1, §5.6). After a carrier loss that RELEASE goes out on a link with no carrier, so the server never sees it. The client is then discarded, and the interface's lease and link-local address are forgotten, so the next reconcile removes both addresses.

A link that disappears from the kernel takes its client with it and sends nothing.

5.4.3 The operator's renew #

The control request renew (§9.2), and so net renew <interface>, moves a client in Bound, Renewing or Rebinding into Renewing at once: a new transaction id and a unicast REQUEST to the lease's server. The lease is not released first, and its address stays on the interface throughout. A client that holds no lease is left as it is, and the request still answers ok.

5.5 Link-local Fallback

Peios / Reference / netd / Dhcpv4

With Address.LinkLocal in the interface's profile, an interface whose DHCPv4 discovery goes unanswered gets an IPv4 link-local address (RFC 3927), so two machines on a cable with no server can still reach each other.

5.5.1 When #

At the client's "nobody answered" report (§5.2), about 28 s after discovery began, netd logs interface <name>: no DHCP offer; link-local <address> and the interface desires the address. Discovery carries on throughout.

The address is desired at prefix 16 only while no lease is held and the profile has no Address.Static entry of either family (§4.2). A profile with a static address therefore never shows one, even after the report.

5.5.2 Which address #

A pure function of the interface, so it is the same every time:

  • the seed is the last four bytes of the MAC, read as a big-endian 32-bit number, or, for a link with no MAC, the interface index times 2654435761, wrapping at 32 bits;
  • the host part is 256 plus the seed modulo 64768;
  • the address is 169.254.<host / 256>.<host % 256>.

That lands in 169.254.1.0 to 169.254.254.255, the range RFC 3927 allows for self-assignment.

netd does not probe for a conflicting holder or announce the address (RFC 3927 §2.2 and §2.4). Two machines whose MACs share their last four bytes choose the same address.

5.5.3 When it goes #

The link-local address is forgotten when a lease binds, and when the client is stopped (§5.4). The next reconcile removes it, because netd owns every IPv4 address on a joined interface (§4.3).

5.6 Sockets

Peios / Reference / netd / Dhcpv4

Before an interface has an address, nothing but a packet socket can send from 0.0.0.0. So every DHCPv4 broadcast leaves through AF_PACKET, with an IPv4 and UDP header netd builds itself, and every reply is read from the same socket.

5.6.1 The packet socket #

One per running client: AF_PACKET, SOCK_DGRAM, protocol ETH_P_IP, bound to the interface. A classic BPF filter passes only an IPv4 UDP datagram that is not a fragment and is addressed to port 68. It refuses both a non-zero fragment offset and the more-fragments flag; the don't-fragment flag is allowed. Everything read is checked again for an IPv4 header and UDP port 68, then decoded as a DHCP message.

The socket sees every frame on the interface that passes the filter, so it receives both broadcast replies and replies unicast to the lease address.

5.6.2 The broadcast path #

DISCOVER, REQUEST in Requesting and Rebooting, and REQUEST in Rebinding go out on the packet socket to Ethernet ff:ff:ff:ff:ff:ff, as one IPv4 datagram:

FieldValue
source0.0.0.0
destination255.255.255.255
TOS0x10
identification0
flagsdon't-fragment
TTL64
UDP ports68 → 67
UDP checksum0 (none, which IPv4 permits)

5.6.3 The unicast path #

REQUEST in Renewing, and RELEASE, go out on a transient AF_INET UDP socket with SO_REUSEADDR and SO_BINDTODEVICE set to the interface, bound to the lease address on port 68, sent to the server on port 67, and closed. The kernel resolves the server's link-layer address. The reply is read from the packet socket.

Binding port 68 meets the kernel's port reservation for ports 1 to 1023, which the shipped seed grants to SYSTEM, netd's identity.

5.6.4 The absorber #

At startup netd binds one more UDP socket, to 0.0.0.0:68 with SO_REUSEADDR, and discards whatever arrives on it. Its only purpose is that a server's unicast reply finds a bound port, so the kernel does not answer it with ICMP port-unreachable. The packet sockets see the same datagrams. If it cannot be bound, netd runs without it (§2.1).

5.7 Identity and Memory

Peios / Reference / netd / Dhcpv4

A DHCP server recognizes a client by its client identifier, and a reservation on the server matches on it. netd keeps the identifier stable across boots and NIC swaps in the same slot, and remembers per network what it was given.

5.7.1 The DUID #

The machine's DHCP unique identifier, shared by DHCPv4, and DHCPv6 (RFC 4361), is decided once per netd process, the first time a client needs it:

  1. the registry's Machine\System\Network Duid, as hex, when it is set and parses;
  2. otherwise the file /var/state/netd/duid, when it holds at least 4 bytes;
  3. otherwise a new DUID-LL: 00 03 00 01 followed by the MAC of the interface whose client is starting. It is written to /var/state/netd/duid; a failure to write is logged and changes nothing else.

When the registry's Duid is absent, empty or not hex, the result of 2 or 3 is written to it, as colon-separated lower-case hex, replacing a value that was not hex.

Hex in Duid (and ClientId) can be written with :, - or spaces between digits, or none. A value with any other character, an odd number of digits, or no digits is not hex.

5.7.2 The client identifier #

Per interface, Interfaces\<id> ClientId:

  • when the value is set and is non-empty hex, it is sent as written;
  • when it is absent, the identifier is generated and written back: ff, then a 4-byte IAID, then the DUID. The IAID is the interface id's text folded into 4 bytes by XOR, byte i of the text into byte i mod 4;
  • when it is set but not hex, netd logs <id>: ClientId "<value>" is not hex; regenerating, where <id> is the interface id, generates one, and overwrites the value.

ClientId is a value both netd and the operator write. Writing it is how an operator makes netd present the identifier a server reservation expects. It is read when a client starts, so it takes effect at the next start (a carrier loss, a profile edit, a restart of netd).

5.7.3 The address a network gave #

While an interface holds a lease on an identified network (§7.1), netd writes the lease address to that network's Networks\<id> RequestedAddress whenever it differs from what is there.

When a client starts, it takes as its previous address (§5.1):

  1. the RequestedAddress of the network identified on the interface, when there is one; otherwise
  2. the RequestedAddress of the network the interface's Status LastNetwork names (§8.1).

With one, the client opens with an INIT-REBOOT REQUEST for it. A server that agrees answers with an ACK and the machine keeps the address in one round trip. One that refuses answers with a NAK and the client discovers afresh. Silence for two transmissions does the same (§5.2).

RequestedAddress is also the operator's: writing it is a soft reservation, an address the client asks for first and the server can refuse.

Nothing about a lease itself — its timers, its server, its options — is persisted. A machine that reboots asks for its address again.

6.1 Router Discovery

Peios / Reference / netd / Ipv6

Router discovery supplies IPv6 prefixes, routes, and resolver information. netd validates advertisements before passing them to the discovery engine.

6.1.1 The kernel's RA handling is off #

netd writes 0 to /proc/sys/net/ipv6/conf/<name>/accept_ra for all, for default, and for every interface listed there, at startup before any link is brought up (§2.1). It writes it again for each non-loopback interface the first time it sees it. A missing file — a kernel without IPv6 — is a warning only for all.

The kernel still creates link-local addresses and answers neighbor solicitations. That is the protocol, not policy. Everything an advertisement could configure is netd's to decide.

6.1.2 When router discovery runs #

On every full pass, for each joined interface:

  • it wants router discovery when its profile has Address.Offered and IPv6 in its families;
  • it can run it when it is up with carrier and the kernel's link-local address on it has finished duplicate address detection. A tentative address cannot source a solicitation.

Running discovery that is not wanted or possible is stopped (ipv6 stopping): the engine and any DHCPv6 client are discarded, and the next reconcile removes their addresses and route. Nothing is sent on the wire, because neither protocol has a goodbye. An interface that wants and can run it starts it (soliciting routers), provided its ICMPv6 socket opens — otherwise netd logs no icmpv6 socket and tries again on the next pass.

6.1.3 The socket #

One raw ICMPv6 socket per interface, bound to it with SO_BINDTODEVICE, filtered to receive only type 134 (router advertisement), sending with a multicast hop limit of 255, and asking for each received packet's hop limit. The kernel computes and checks ICMPv6 checksums.

6.1.4 Solicitation #

A router solicitation is type 133, code 0, with a source link-layer address option carrying the interface's MAC, sent to ff02::2 with hop limit 255.

The first is sent as soon as discovery starts. The interval is 4 s for the next two, then doubles before each later one, up to 3600 s. Each interval carries a jitter of ±10%. So solicitations go at about 0, 4, 8, 16, 32, 64, … s.

Soliciting stops when an advertisement arrives with a router lifetime above zero. It begins again, from the first interval, as soon as every default router has expired.

6.1.5 Which advertisements count #

An advertisement is dropped unless it arrived with hop limit 255 and from a link-local source (RFC 4861 §6.1.2). A lower hop limit has crossed a router, and a non-link-local source is not a router on this link.

It is then decoded. The whole advertisement is refused when:

  • it is shorter than 16 bytes, or its type is not 134 or its code not 0;
  • an option has length zero, or runs past the end of the message.

Within an accepted advertisement, an option that does not parse is skipped and the rest stand:

OptionAccepted whenLimits
Prefix information (3)32 bytes long; prefix length ≤ 128; the prefix neither multicast nor link-localthe first 16 per advertisement
MTU (5)8 bytes long
RDNSS (25)at least 24 bytes, and a whole number of addresses16 servers per option; unspecified, multicast, and loopback addresses dropped
DNSSL (31)at least 16 bytes16 domains per option; names uncompressed, lower-cased, labels of printable ASCII, 253 characters at most; a malformed name ends the list

Any other option is ignored. So are the advertisement's hop limit, reachable time and retransmission timer.

6.1.6 What an advertisement does #

  • Router lifetime above zero: the source becomes, or stays, a default router until that many seconds from now. Zero: the source is removed as a default router. Its prefixes, servers, and domains stay.
  • M or O flag: stateless DHCPv6 is wanted (§6.3). Once set it stays set until discovery restarts; a later advertisement without the flags does not withdraw it.
  • MTU option: remembered as the link's advertised MTU. It is used only with Mtu.Offered, only when no lease gave one, and only when it is at least 68 (§4.2, §4.3).
  • Prefixes: §6.2. RDNSS and DNSSL: §6.3.

Whenever what the interface should carry changes — an address, its deprecation, the default router, the servers, the domains, the MTU, the DHCPv6 flag — netd runs a full pass. That includes a change caused by time alone: a lifetime running out is a change.

6.1.7 The default router #

Of the routers whose lifetime has not run out, netd uses the one with the numerically lowest link-local address, so the choice is stable while the set is. Router preference (RFC 4191) is not read.

6.1.8 Receiving datagrams #

The receive path reads at most 4096 bytes per datagram. It rejects truncated bodies, truncated ancillary data, incomplete IPv6 source addresses, and missing or malformed hop-limit metadata. Rejected datagrams do not stop the receive loop. DHCPv6 uses the same bounded receive path without requiring hop-limit metadata.

6.2 Addresses

Peios / Reference / netd / Ipv6

netd derives stable and temporary IPv6 addresses from accepted router advertisements. Prefix lifetimes control when those addresses are preferred, deprecated, and removed.

6.2.1 Which prefixes form addresses #

A prefix information option forms addresses only when its A flag is set, its prefix length is exactly 64, and its preferred lifetime does not exceed its valid lifetime. Any other prefix option is ignored whole. A prefix with only the L flag gets no address, and no on-link route, because the kernel's RA handling is off.

A prefix seen for the first time is taken only with a valid lifetime above zero.

6.2.2 The stable address #

Each accepted prefix gets one stable address (RFC 7217): the prefix's first 64 bits, followed by the first 8 bytes of a SHA-1 digest of:

  1. the bytes peios-ndp-stable-iid|;
  2. the machine's 32-byte secret;
  3. the prefix's first 8 bytes;
  4. the interface id's text;
  5. a one-byte counter, starting at 0.

When the resulting interface identifier is reserved (RFC 5453: all zeros, 0200:5eff:fe00::/40, or fdff:ffff:ffff:ff80 to fdff:ffff:ffff:ffff), the counter is incremented and the digest taken again, up to 8 times.

So the same machine on the same network has the same address on every boot, a different network sees an unrelated address, and no MAC address ever appears in it. The address is a function of the interface id, so a kernel rename does not change it either.

6.2.2.1 The secret #

The 32-byte secret is read from /var/state/netd/secret the first time an interface starts router discovery. When the file does not hold exactly 32 bytes, a new secret is drawn from /dev/urandom and written there; a failure to write is logged and the new secret used for the rest of the process's life. If opening or reading /dev/urandom fails, netd logs the failure and skips IPv6 autoconfiguration for that attempt. It does not use a zero-filled secret. IPv4 continues independently.

Losing the stored secret changes the derived addresses on the next start.

6.2.3 Lifetimes #

A lifetime of 0xFFFFFFFF is forever. Others count from the moment the advertisement arrived.

When an advertisement updates a prefix already held:

  • the on-link flag and the preferred lifetime are taken as advertised;
  • the valid lifetime uses the two-hour rule from RFC 4862 §5.5.3(e), including prefixes whose previous lifetime was infinite:
Advertised valid lifetimeRemaining valid lifetimeResult
above two hours, or above what remainsany finitethe advertised lifetime
two hours or less, not above what remainstwo hours or lessunchanged
two hours or less, not above what remainsabove two hourstwo hours from now
above two hoursforeverthe advertised lifetime
two hours or lessforevertwo hours from the advertisement

When a prefix's preferred lifetime runs out, its addresses are deprecated: kept on the interface for standing connections, with a preferred lifetime of zero so that nothing new chooses them (§4.3). When its valid lifetime runs out, the prefix and its addresses are removed.

6.2.4 Flags on the address #

An address in a prefix advertised on-link (L set) is added normally, so the kernel adds the prefix route. One advertised off-link is added with IFA_F_NOPREFIXROUTE, so the kernel adds no prefix route for it.

6.2.5 Temporary addresses #

With Address.Temporary in the profile, each prefix also carries temporary addresses (RFC 8981):

  • one is formed with the prefix when the prefix arrives with a preferred lifetime above zero;
  • its interface identifier is random, avoiding the reserved identifiers, the stable address and the prefix's other temporaries;
  • its preferred lifetime is one day minus a random 0 to 599 s, so a rack of machines does not regenerate together, and its valid lifetime is two days. Each is cut to the prefix's own lifetimes.

When the newest temporary stops being preferred while the prefix still is, a new one is formed. The old one stays, deprecated, until its valid lifetime ends. A prefix keeps at most four temporaries, dropping the oldest beyond that.

A temporary is deprecated when its own preferred lifetime or its prefix's has run out, and removed when its own valid lifetime or its prefix's has.

Address.Temporary is read when router discovery starts. Changing it is a profile edit, which restarts discovery (§3.3).

6.3 DNS and DHCPv6

Peios / Reference / netd / Ipv6

Router advertisements and DHCPv6 information replies supply resolver facts. netd tracks their lifetimes and publishes the accepted facts to resolvd.

6.3.1 RDNSS and DNSSL #

Each server of an RDNSS option, and each domain of a DNSSL option, is held for the option's lifetime from the moment the advertisement arrived. 0xFFFFFFFF is forever, and a lifetime of zero removes that server or domain at once. A server or domain advertised again has its lifetime replaced.

6.3.2 Stateless DHCPv6 #

Peios gets IPv6 addresses by SLAAC alone. DHCPv6 is used for configuration only: an INFORMATION-REQUEST (RFC 8415 §18.2.6) for DNS servers and search domains. The stateful address exchange is not implemented, and an advertisement's M flag is treated as O.

6.3.2.1 When it runs #

A DHCPv6 client starts on an interface once its router-discovery engine has seen an advertisement with M or O (§6.1), provided the interface has a non-tentative link-local address and a MAC, and its socket opens. netd logs interface <name>: dhcpv6 information request. It stops with router discovery.

6.3.2.2 The socket #

UDP, bound with SO_BINDTODEVICE to the interface and to its link-local address on port 546, so two interfaces' clients never share a port. Messages go to ff02::1:2 port 547.

6.3.2.3 The request #

An INFORMATION-REQUEST (type 11) with a random 3-byte transaction id and these options:

OptionContent
1, client identifierthe machine's DUID (§5.7)
8, elapsed timehundredths of a second since this exchange began, capped at 65535
6, option request23 (DNS servers), 24 (domain list), 32 (information refresh time)

The first is sent when the exchange begins. Retransmissions follow after 1 s, doubling up to 3600 s, each with a jitter of ±10%, and never stop until a reply is accepted.

6.3.2.4 The reply #

A datagram is accepted only while an exchange is running, and only when:

  • it is a REPLY (type 7) with the exchange's transaction id;
  • it carries a client identifier equal to the machine's DUID;
  • it carries a non-empty server identifier.

Anything else is ignored, and retransmission continues. From an accepted reply, option 23 gives the DNS servers — when its length is a whole number of addresses, up to 16, with unspecified, multicast and loopback addresses dropped — and option 24 the search domains, read as a DNSSL's are (§6.1).

6.3.2.5 Refresh #

After a reply, the client asks again after the reply's information refresh time (option 32), or one day when there is none, but never sooner than 600 s. Each refresh is a new exchange with a new transaction id.

An answer that differs from the last logs dhcpv6 answered and leads to a reconcile and a publish. An identical one changes nothing.

6.3.3 Where these go #

Advertised and DHCPv6 servers and domains reach name resolution only through the profile's Dns.Offered, including link-local servers with the interface supplied by their DNS scope (§8.3). They are always part of what a network has shown for its identity and its record (§7).

7.1 Identification

Peios / Reference / netd / Networks

netd has to say "this is the same network as last time" with nothing on the wire that says so. The identity is a guess from what the network has offered, recorded with every signal it was made from, so that a later proof can replace the guess without changing the record's key.

7.1.1 Signals #

What a joined interface's network has shown, at the moment of the pass:

SignalFrom
kindthe interface's Interface.Kind
serverthe DHCPv4 lease's server identifier
subnetthe lease address masked to the lease prefix
gatewaythe lease's gateway (§5.3)
routerthe default router router discovery chose (§6.1)
prefixesthe subnet, then every non-deprecated autoconfigured address's prefix, each once
DNS serversthe lease's, then the routers' RDNSS servers, link-local ones included

7.1.2 The identity #

  • With a lease (a server and a subnet), the basis is dhcp:<server>|<subnet>/<prefix>.
  • Otherwise, with a default router and at least one autoconfigured prefix, the basis is ra:<router>|<prefix>/<length>, using the first prefix.
  • Otherwise there is no identity yet: nothing has been offered, or the interface is static only.

The network id is a SHA-1 digest of the bytes peios-netd-network|, the kind, |, and the basis, stamped and written as a version 5 UUID exactly as an interface id is (§4.1).

So two leases from the same server in the same subnet are the same network, whatever the address. A different server, a different subnet, or a different kind of interface is a different network. An IPv4 lease always wins over the IPv6 basis, so a dual-stack network is identified by its DHCPv4 server.

7.1.3 When #

Identification is the first step of every full pass (§2.2). It runs only on a joined interface that is up with carrier, and only when the signals yield an identity.

For each identity it creates or refreshes the network's record (§7.2) and reads back what the operator wrote on it. While a lease is held, it writes the lease address to the record's RequestedAddress (§5.7).

7.1.4 A newly identified network #

When the identity differs from the network the interface already had — including when it had none — netd logs interface <name>: network <name or id>, with (trust <trust>) when the record has one. It then marks the interface for re-judgment, so the same pass judges it with the Network.* facts present (§3.3). A rule conditioned on Network.Name or Network.Trust takes effect then. If it moves the interface to another profile, the interface's clients restart under that profile (§3.3).

The network an interface stands on is kept while it has carrier, even when a profile switch restarts the clients that identified it. A switch that its own identification triggered would otherwise forget the network and switch back. Losing carrier forgets it (§4.1).

The interface's Status Network names the identified network (§8.1). The kernel reads it to give the packet layers their Network.* facts (PKM §6.5), so it never names a network the link is not on.

7.2 Records

Peios / Reference / netd / Networks

Every network a joined interface has been identified on gets a record, Machine\System\Network\Networks\<id>. Records are never deleted by netd.

7.2.1 What netd writes #

On every identification (§7.1), netd creates the record if it is missing and writes these values under its Status subkey, each only when it differs from what is there:

ValueTypeContent
KindREG_SZthe interface kind it was seen on
ServerREG_SZthe DHCPv4 server; removed when there is none
GatewayREG_SZthe lease's gateway; removed when there is none
RouterREG_SZthe IPv6 default router; removed when there is none
PrefixesREG_MULTI_SZthe subnet and the autoconfigured prefixes, CIDR form
DnsServersREG_MULTI_SZthe DNS servers offered, either family
LastSeenREG_SZthe wall-clock time of the identification, in Unix seconds
LastInterfaceREG_SZthe kernel name of the interface it was seen on

LastSeen is rewritten on every pass that identifies the network, so a record's Status changes whenever netd runs a pass on a link that is on it.

Status is created with the descriptor O:SYG:SYD:P(A;;KA;;;SY)(A;;KR;;;WD) : SYSTEM has full control and Everyone has read access. It is protected, so the hive root's inheritable grants do not reach it, and a hand edit is refused rather than silently reverted at the next pass. The descriptor is set only when netd creates the key; a Status key that already exists keeps whatever descriptor it has.

7.2.2 What the operator writes #

On the record itself, not under Status:

ValueRead asMeaning
NameREG_SZ, empty is unsetthe Network.Name fact
TrustREG_SZ, empty is unsetthe Network.Trust fact
RequestedAddressREG_SZ, an IPv4 addressthe address the next DHCPv4 client asks for first (§5.7); netd writes it too

Name and Trust are read at every identification, so an edit reaches the interface layer on the pass that follows the registry write (§2.3). They are opaque: netd compares nothing about them and gives them no vocabulary.

The kernel reads Name and Trust itself, from the record that an interface's Status Network names (PKM §6.5).

8.1 The Inventory

Peios / Reference / netd / What Netd Publishes

netd publishes observed network state in the registry. Ownership of each key separates operator settings from the status that the daemon maintains.

8.1.1 The record #

Every non-loopback interface netd has seen has a key Machine\System\Network\Interfaces\<id>, named by its interface id (§4.1). netd creates it on the first pass that sees the interface. The key is the operator's, apart from ClientId, a value both write (§5.7). netd's findings are under its Status subkey.

Records are never deleted. The record of a card that has been removed stays, with what netd last wrote.

8.1.2 Status #

ValueContentPresent
Namethe kernel's name for the linkalways
Kindwired, wireless, or otheralways
Macthe hardware address, lower-case, colon-separatedwhen the link has one
Paththe bus pathwhen there is one
Driverthe driverwhen there is one
VerdictJOIN, IGNORE, or DOWNwhen a rule spoke; removed when the backstop answered or rules tied
Rulethe path of the rule that spoke, or the tied rules as <a> vs <b>when a rule spoke or rules tied; removed when the backstop answered
Profilethe profile path as writtenJOIN only
Readinessthe interface's level (§8.2)JOIN only
Networkthe id of the network identified on the link nowwhile one is identified; removed when the carrier goes
LastNetworkthe id of the network the link last stood onfrom the first identification; never removed

Every value is REG_SZ. A value is written only when it differs from what is there, and removed only when it is there, so a pass that changes nothing writes nothing to the registry.

Status is refreshed on every full pass for every non-loopback interface, and again at each publish (§2.2) for joined ones, so Readiness follows a reconcile that moved it without any link event.

Status Network is read by the kernel to give the packet layers their Network.* facts (PKM §6.5). It names the network only while netd has identified one on the link (§7.1).

8.1.3 The descriptor #

Status is created with the descriptor O:SYG:SYD:P(A;;KA;;;SY)(A;;KR;;;WD): SYSTEM has full control, Everyone has read access, and the DACL is protected, so the hive root's inheritable grant to Administrators does not reach it. Only netd, as SYSTEM, can write there. An administrator's hand edit is refused at the write, not reverted at the next pass. The descriptor is set only when netd creates the key.

8.1.4 The machine's values #

On Machine\System\Network itself netd writes:

  • Readiness, the machine level (§8.2);
  • Duid, when it was absent and netd generated or read one (§5.7).

8.2 Readiness

Peios / Reference / netd / What Netd Publishes

"The network is up" means different things to different services, so netd reports a level, not a flag. Levels are ordered: absent < link < addressed < routed.

8.2.1 An interface's level #

From the kernel's state after the last reconcile:

LevelWhen
absentthe interface is not up, or has no carrier
linkup with carrier, and no usable address
addresseda usable address, and no default route
routeda usable address, and a default route on the interface

A usable address is any IPv4 address other than a loopback one — a 169.254 link-local address counts, because it is the outcome of address acquisition — and any IPv6 address that is neither loopback nor link-local. Every up interface has an IPv6 link-local address, so counting one would make addressed mean nothing. Deprecated and tentative addresses count.

A default route is any route with prefix length 0, of either family, in the main table, out of the interface. It need not be one of netd's.

8.2.2 The machine's level #

The highest level among joined interfaces, or absent when none is joined. An IGNORE d or DOWN interface contributes nothing, whatever state it is in.

8.2.3 Publishing it #

At every publish (§2.2) netd computes the machine level. When it differs from the last one published — and at the first publish after startup, which precedes READY=1 — netd:

  1. logs machine readiness is <level>;
  2. sends the complete readiness set below in one datagram on the notify socket named by NOTIFY_SOCKET;
  3. writes Readiness on Machine\System\Network.

The notify set is determined by the highest machine level:

Machine levelLEVEL values, in wire order
absentabsent
linklink
addressedlink, addressed
routedlink, addressed, routed

Each value has its own LEVEL= line in the same datagram. The highest level comes last, so an older manager that retains only the last value continues to see the highest level. Upgrade peinit before or alongside netd to make every member available to dependents.

The set is sent only on a change. The notify channel is lossy by design and unacknowledged (PSPU §4.16), and a level is a statement of a current condition, so a lost one is corrected by the next change.

Each joined interface's own level is written as Status Readiness (§8.1).

8.2.4 What peinit makes of it #

peinit records the set netd last sent against the sending service, and resolves the network role to that service. A dependency on network:<level> waits until the service is active and its published set contains the requested level (peinit TRM §7.5).

A DHCPv4 lease that installs an address and default route in the same pass takes the highest machine level directly from link to routed. The notify datagram contains link, addressed and routed, so both network:addressed and network:routed dependents can start. peinit needs no knowledge of network level ordering; netd publishes every condition that holds. Losing the link replaces this set with absent, preventing new starts on any of the three previous conditions. Dependents already running keep running.

The registry, log, and control status continue to report the highest machine level. net wait <level> polls over the control socket and succeeds when that level is at least the one named (§10.1).

8.3 The Resolver Channel

Peios / Reference / netd / What Netd Publishes

The channel's contract — that a resolver subscribes, and receives whole snapshots, never deltas — is PSPU §6.9. This article is netd's half of it.

8.3.1 Subscribing #

A subscribe request on the control socket (§9.2), which needs the query right, is answered with a snapshot at once, and the connection is kept: switched to non-blocking and added to the subscriber list. It is the one request that does not end its connection.

The first snapshot is the last one published, or, before any has been, one computed on the spot.

8.3.2 When snapshots are sent #

At every publish (§2.2) netd computes the snapshot and compares it with the last one sent. If it differs, it is sent to every subscriber. If it is equal, nothing is sent.

A subscriber that cannot take the whole frame at once — closed, or so far behind that its socket buffer is full — is dropped. A resolver reconnects and receives a fresh snapshot.

8.3.3 The snapshot #

A reply map with ok = true, kind = snapshot, hostname — the name netd last set (§8.4), empty if none — and scopes: one scope per joined interface whose level is above absent, ordered by the interface's metric, then its kernel index.

Each scope:

FieldContent
ifidthe interface id
namethe kernel name
serversDNS servers, as text, in the order to try them (below)
domainssearch domains, likewise
ntpthe lease's NTP servers (option 42)
addressesevery address the kernel holds on the interface, address/prefix, link-local ones included
default_routethe profile's Dns.Default when set; otherwise whether the interface's level is routed
exclusivethe profile's Dns.Exclusive
metricthe interface's metric (§4.2)
levelthe interface's level (§8.2)

8.3.4 Merging DNS facts #

Servers, in this order:

  1. the profile's Dns.Servers, always;
  2. with Dns.Offered: the lease's servers (option 6);
  3. with Dns.Offered: the routers' RDNSS servers, including link-local IPv6;
  4. with Dns.Offered: the DHCPv6 reply's servers, including link-local IPv6.

Domains, in this order:

  1. the profile's Dns.Domains, always;
  2. with Dns.Offered: the lease's domain search list (option 119) if it is not empty, otherwise its domain name (option 15);
  3. with Dns.Offered: the routers' DNSSL domains;
  4. with Dns.Offered: the DHCPv6 reply's domains.

Each list removes duplicates across the entire list, retaining the first occurrence and the source order above. This includes repeated values with other values between them.

The containing scope supplies the interface for link-local IPv6 servers. resolvd uses its index on UDP and TCP upstream sockets; the address text does not need a zone suffix. Deploy this publication change with a resolver that supports interface-scoped upstreams (resolvd TRM §4.7).

NTP servers are reported whatever Dns.Offered says. Whether to believe a lease's time servers is timed's decision, made against its own registry value. A snapshot describes what the network said.

The same merge feeds the dns and search fields of the status reply (§9.2), for every non-loopback interface, joined or not.

8.4 The Hostname

Peios / Reference / netd / What Netd Publishes

netd selects and validates the machine hostname before applying it to the kernel. Registry configuration takes precedence over an accepted lease offer.

8.4.1 Which name #

  1. Machine\System\Network Hostname, when it is set and not empty;
  2. otherwise the hostname option (12) of a lease. netd takes the first joined interface, in kernel index order, whose profile has Hostname.Offered and whose lease carries a hostname;
  3. otherwise none.

The selected name is checked by netd_core::hostname, the same rule used by System Settings and first-boot setup: after trimming outer whitespace, it must be one nonempty label of at most 63 ASCII letters, digits or hyphens, with no leading or trailing hyphen, and must not be localhost (case-insensitive). This applies to registry and lease names alike.

An invalid selected name leaves the kernel's name and netd's last applied name unchanged. It is logged as hostname <quoted name> refused: <quoted reason>, with control characters escaped, once while the same rejected candidate remains selected. A different candidate, a valid name, or no name clears that suppression. A nonempty but invalid registry name still takes precedence: it does not silently fall through to a lease. Likewise, the first selected lease name is checked without searching later leases for a replacement.

A valid name that the kernel nevertheless refuses is logged as sethostname(<name>): <error> and tried again at the next pass.

8.4.2 When #

After every full pass and every reconcile-only iteration (§2.2), netd calls sethostname(2) if the name differs from the last one it set, and logs hostname is <name>. It does not compare against the kernel's current hostname. A change made by anything else is not reverted until netd's own name changes.

When there is no name — the registry value removed and no lease offering one — netd does nothing: the kernel keeps whatever hostname it had.

The status reply and the resolver snapshot report the name netd last set, empty if it has set none.

8.4.3 What is recorded #

Each sethostname(2) that changes the kernel's name writes a netd.hostname.changed event, which is essential: the emission policy cannot switch it off. It carries config.name (always Hostname, whether the name came from the registry or from a lease), config.text (the name now in force) and config.text-previous (the kernel's name, read before the call; the kernel's own (none) on the first change after boot). A call that leaves the kernel's name as it was — netd setting a name the kernel already holds, as after a restart of netd or a change made behind its back — records nothing, and neither does a name the kernel refuses.

The record's subject.token.sid is the principal that acted (PGSS §6.4). When the change is made during the pass a reconcile request (§9.2) asked for, that is the requester's user SID; netd refuses a request whose user it cannot read. A change netd makes on its own authority — after a registry change, a lease, or at startup — names netd's own user, SYSTEM; who wrote the registry value is LCS's to record.

8.4.4 Telling the network #

With Hostname.Announce in an interface's profile, a newly started DHCPv4 client sends the validated, trimmed registry Hostname in option 12 (§5.1). An invalid registry name is omitted. An existing client's announcement configuration is unchanged until it restarts. A name adopted from a lease is never announced.

9.1 The Socket and Its Object

Peios / Reference / netd / The Control Socket

The control socket accepts local requests to inspect or change network state. A separate security object governs access to those operations.

9.1.1 The socket #

netd listens on /run/netd/control.sock, a SOCK_STREAM Unix socket. At startup it:

  1. creates /run/netd if it is missing, sets its mode to 0755, and gives it the descriptor below;
  2. removes a socket file left by a previous run, logging removed a stale /run/netd/control.sock;
  3. binds, sets the socket file's mode to 0666, and gives it the same descriptor.

The descriptor on both: owner and group SYSTEM, and a DACL allowing SYSTEM GENERIC_ALL and Everyone GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE. peinit creates /run SYSTEM-only and inheritable, so without it nobody else could reach the socket. Everyone can connect; the control object decides what each connection can do. A failure to set it is logged as an error and netd carries on.

9.1.2 The control object #

Every request is checked against the control object, a security descriptor netd holds in memory. It is Machine\System\Network ControlSecurity, a self-relative descriptor in a REG_BINARY value, when that is set and valid. When it is not valid, netd logs ControlSecurity is not a valid descriptor (…); using the default.

The compiled default: owner and group SYSTEM, and a DACL of:

TrusteeRights
SYSTEMNETWORK_ALL_ACCESS
AdministratorsNETWORK_ALL_ACCESS
EveryoneNETWORK_QUERY, READ_CONTROL

The object is rebuilt whenever the configuration changes (§2.3), so a written ControlSecurity applies to the next connection.

9.1.3 Rights #

RightValue
NETWORK_QUERY0x00000001
NETWORK_CONTROL0x00000002
NETWORK_ALL_ACCESS0x000F0003: both, plus the standard rights

The generic mapping:

Generic rightMaps to
readNETWORK_QUERY, READ_CONTROL
writeNETWORK_CONTROL, READ_CONTROL
executeNETWORK_QUERY
allNETWORK_ALL_ACCESS

9.1.4 The check #

For each request, netd opens the connecting peer's token through KACS and runs a real access check of the request's right (§9.2) against the control object. It never looks at SO_PEERCRED, so a deny-only group or a filtered token is judged as the kernel would judge it anywhere else. A peer whose token cannot be opened is denied, and so is one whose token's user cannot be read, since a change made for it is recorded under that user (§8.4).

A denied request is answered {ok: false, error: "access denied"}, and nothing else happens.

9.1.5 Nonblocking client I/O #

The control socket is served on netd's one thread (§2.2). Accepted connections are nonblocking and polled alongside network and registry inputs. An idle client, partial request, or client that does not read its reply does not hold the loop in a socket read or write.

At most 64 requests or replies are pending at once. While full, netd stops polling the listener until a slot becomes free; connections still waiting in the kernel backlog have not been accepted. Each iteration accepts at most 16 connections and reads or writes at most 4 096 bytes per ready pending connection. The 65 536-byte message ceiling is checked from the header before reading a request payload (§9.2).

A request must complete within two seconds of acceptance. A normal reply must be written within two seconds of being queued. Partial progress does not extend either deadline. Expiry closes the connection without a timeout reply. These deadlines participate in the same poll timeout as network-client timers. Completed subscriptions leave this pending-client set and use the existing nonblocking snapshot publisher (§8.3).

9.2 Requests

Peios / Reference / netd / The Control Socket

Control requests use the shared framing and reply types described here. Each operation names the right required by the daemon.

9.2.1 Framing #

The control socket is a PSPU observability query channel: one length-prefixed MessagePack map in each direction, one request and one reply per connection, except subscribe.

  • A frame is a 4-byte little-endian payload length, then the payload.
  • A length above 65536 is refused before any of the payload is read, with {ok: false, error: "message of <n> bytes exceeds the ceiling"}.
  • A request is a map with a string query. Unknown keys are ignored, and a key that appears twice refuses the request.
  • A reply is a map with a boolean ok, and either the result's fields or a string error.

An oversized, incomplete-at-EOF, or undecodable request is answered with an error reply and the connection ends:

Problemerror
no querymissing field query
an unknown queryunknown query "<query>"
a duplicate keyduplicate field <key>
renew without interfacemissing field interface
malformed MessagePackmalformed message: …

Expired client deadlines and failed socket I/O close the connection without a reply (§9.1). A normal reply that exceeds the message ceiling is replaced with an error reporting its size.

9.2.2 The requests #

queryRightDoesReply
statusNETWORK_QUERYnothingthe status (below)
subscribeNETWORK_QUERYkeeps the connection as a subscriber (§8.3)a snapshot now, and another on each change
reconcileNETWORK_CONTROLa full pass (§2.2){ok: true}
renew, with interfaceNETWORK_CONTROLthe client renews (§5.4){ok: true}, or an error

renew finds its interface by kernel name or by interface id. It answers no interface <name> when there is none, and <name> is not using DHCP when the interface has no DHCPv4 client.

9.2.3 The status reply #

FieldContent
hostnamethe name netd last set, empty if none (§8.4)
levelthe machine level (§8.2)
refusalwhy the newest generation was refused, or nil (§3.2)
interfacesone map per non-loopback interface netd has seen, joined or not, in kernel index order

Each interface:

FieldContent
ifid, name, indexthe interface id, kernel name, and index
mac, path, driveridentity (§4.1); empty strings when absent
verdictJOIN, IGNORE, or DOWN; nil when the backstop answered or rules tied
rulethe rule that spoke, backstop, or the tied rules <a> vs <b>
profilethe profile path, JOIN only
network, network_name, network_trustthe network identified now (§7)
warningdiscovery unanswered (§5.2), or a tie (§3.3); nil otherwise
up, carrierthe link's flags
levelthe interface's level (§8.2), computed for every interface
addressesevery address the kernel holds, address/prefix, link-local ones included
gateway, gateway6the gateway of the interface's first IPv4 and IPv6 default route, any owner's
dns, searchthe merged DNS facts (§8.3); empty for an interface not joined
leasewhile the client holds a lease: server, expires_in (whole seconds), state (§5.1), duration (the lease's length), and renew_at and rebind_at (T1 and T2), the last three in whole seconds after the lease was bound; nil otherwise. A client reading a netd that predates the last three finds them absent.

10.1 Commands

Peios / Reference / netd / The Net Command

net is netd's operator command. It talks to netd over the control socket, and reads the registry directly for rules and profiles, because those are configuration that netd merely executes. Changing the network is a registry write; net shows state and pokes the daemon. The task-oriented guide is ~peios/networking/the-net-command.

10.1.1 Subcommands #

CommandDoes
net statusprints the status reply (§9.2)
net renew <interface>sends renew
net reconcilesends reconcile
net rulesprints Rules\Interface from the registry: one line per rule, indented by depth, with its priority, (disabled) for Enabled = 0, its conditions, and its actions (NULL when it has none)
net profiles, net profile listprints Profiles\ from the registry: one line per profile, indented by depth, with the values it sets itself ((inherits only) when none) and (disabled)
net wait <link|addressed|routed> [seconds]waits for the machine level
net policyprints the kernel engine's status: enforcing or not, the generation, unwalked changes, a refused last walk, the context count
net policy wait [seconds]waits for the packet policy to be in force
net version, net --versionprints net <version>

rules and profiles fail when their key does not exist. Neither needs netd running.

10.1.2 net status output #

A hostname line ((unset) when empty) and a readiness line, then policy REFUSED: <why> (the last good generation stands) when there is a refusal. Then a block per interface: <name> [<id>], then verdict (<VERDICT>(<profile>) by <rule>, or (none) by <rule>), state, and readiness for a joined interface. Then, where present, hardware, network (<name> [<id>] trust <trust>), each address, gateway, gateway6, dns, search, lease (<state> from <server>, <n>s left) and warning.

10.1.3 net wait #

It asks for status every 500 ms and succeeds as soon as the machine level is at least the one named. An error reaching netd is printed and the wait goes on. The timeout is the second argument, or 60 s when absent or not a number. When it lapses, net prints net: timed out waiting for <level> and fails.

absent is accepted as a level, and is met at once.

10.1.4 net policy wait #

It reads /dev/peios-ntfe's status (ABI 5) once and takes the number of policy changes the engine has noted as its target. It then polls every 5 ms until the engine's count of changes walked reaches the target. If the last walk was refused, it fails, naming the errno and the generation that stands; otherwise it succeeds. The timeout is the argument, or 10 s. The counters are the kernel's (PKM §6.5). A device that answers with another ABI fails at once.

10.1.5 Exit status #

CodeMeaning
0success
1netd unreachable, an error reply, a timeout, a refused policy, or a registry key that cannot be opened
2usage: an unknown subcommand, a wrong argument count, an unknown level, or a non-numeric policy wait timeout

10.1.6 Wait deadlines #

net wait limits each status request and polling pause to the remaining wait deadline. A zero timeout expires without sending a status request. Unrepresentable timeouts return an error instead of panicking. net policy wait also rejects unrepresentable deadlines; its kernel status reads remain synchronous.

11.1 Failure Modes

Peios / Reference / netd / Failure Modes

netd reports configuration, protocol, and kernel failures through status and logs. The cases below distinguish refusal from incomplete discovery or reconciliation.

11.1.1 Where the evidence is #

  • net status: the policy refusal, each interface's verdict and the rule that gave it, its warning, its addresses and gateways, and its lease's state.
  • netd's log. Informational lines go to standard output; warnings and errors go to standard error. peinit forwards both to eventd (evctl 'LOGS FROM netd SINCE 1h ago TAKE 40'). Each line is also mirrored to /dev/kmsg at KERN_INFO, KERN_WARNING or KERN_ERR, so it reaches the kernel log and, at a permissive console log level, the console. If the mirror cannot be opened, netd says so once on standard error and tries again on the next line. Each mirrored line opens and closes its own /dev/kmsg descriptor, so boot and reconciliation bursts do not lose lines to the kernel's per-open rate limit (normally ten lines in five seconds). All three severities are retained. The mirror remains best-effort if opening or writing the device fails; stdout/stderr delivery is independent.
  • The registry: Interfaces\<id>\Status, Networks\<id>\Status, Readiness.

11.1.2 No address on a joined interface #

What net status showsLikely cause
warning asked for an address; nobody answered, a 169.254 address, or noneno DHCPv4 server answered. Either there is none, or NTFE refused the exchange: the shipped baseline's DHCP rules were deleted or overridden. netd cannot see the verdict stream.
no lease line, no warningthe profile does not offer the address (Address.Offered, Address.Families), the interface has no MAC, or the packet socket would not open (logged). Or a server is answering but its ACK does not read as a lease: no server identifier, a lease time under 4 s, or a malformed classless route option (§5.3). The client then cycles through Selecting and Requesting, neither of which is shown (§5.1).
no IPv6 addressno advertisement arrived, or none was accepted: hop limit under 255, a non-link-local source, a prefix that is not an autonomous /64 (§6.1, §6.2). Also check Address.Families.

11.1.3 The wrong interfaces are configured #

What net status showsMeaning
policy REFUSED: …the newest generation was refused (§3.2). Everything shown is still the last good generation. Fix the named rule or profile; the next write is read at once.
verdict (none) by backstopno rule speaks for the interface. It is left as the kernel left it.
verdict (none) by <a> vs <b>, warning rules … tietwo rules tied on priority and named different profiles (§3.3). The interface is ignored until one outranks the other.
an interface that was joined is now IGNOREd, with its old addresses still on itby design: IGNORE touches nothing, removal included (§3.3)

11.1.4 Changes that do not stick #

  • An address added by hand disappears. netd owns every address on a joined interface, and the next pass removes it (§4.3). Add it to Address.Static instead.
  • A route added by hand stays, unless it carries protocol 200.
  • A pinned gateway never appears. Route.Gateway is not checked against the interface's subnets. When the kernel cannot reach it, every reconcile logs reconcile: AddRoute(…) failed, and the interface stays addressed.
  • The hostname does not change back when Hostname is removed. netd never unsets a name (§8.4).

11.1.5 Losing what was working #

  • A cable pull drops everything offered — the lease, autoconfigured addresses, routes, the network identity — and stops the clients (§4.1). When the carrier returns, the DHCPv4 client asks for the old address first, so a cooperative server restores it in one exchange.
  • A lease that cannot be renewed drops its address at the lease's end, unless the profile says Address.OnExpiry = Keep (§5.4). After that, the link-local fallback does not happen again in the same client's life (§5.2).
  • Editing a profile restarts its interfaces' clients (§3.3), so a DHCPv4 lease is released and asked for again.

11.1.6 netd is slow or unresponsive #

  • Control requests time out. netd handles control clients without blocking the event loop. It permits 64 pending clients, accepts at most 16 per pass, and closes requests that exceed their 2-second deadline (§9.1). Check for clients holding connections open or flooding /run/netd/control.sock.
  • net: cannot reach netd at /run/netd/control.sock. netd is not running, or /run/netd lost its descriptor. The service restarts netd always; evctl shows why it stopped.

11.1.7 Configuration not read #

  • A configuration read failed. Check the named read error in the log. netd retains its previous complete configuration after a reload failure. Restore access or valid text, then change the configuration to retry.

  • Network state refresh failed. An interrupted or failed netlink dump is discarded. netd keeps its previous complete snapshot until a refresh succeeds; it does not reconcile against a partial dump.

  • netd ignores every registry change. The watch could not be armed at startup (registry watch unavailable … configuration is read once), or Machine\System\Network did not exist then (§2.1). Restart netd.

11.1.8 Getting back to a known state #

  1. Undo the last registry write. A refused generation names what to undo, and the next good write is taken at once.
  2. net reconcile runs a full pass without waiting for an event.
  3. net renew <interface> renews a lease without releasing it.
  4. Restarting netd re-derives everything from the registry and the kernel, and asks for the remembered IPv4 address with INIT-REBOOT (§2.1). The requested address already installed and applicable netd-owned routes stay while that request is pending. A NAK or unanswered revalidation discards this provisional state and starts fresh discovery; an unchanged ACK keeps IPv4 connectivity in place. Offered DNS and IPv6 information still have to be reacquired.

12.1 The Public Interface

Peios / Reference / netd / Client Library

libnetd.so.1 exposes daemon access and configuration validation through a C application binary interface (ABI). The netd-client Rust crate wraps that same shared library. It does not embed a second implementation.

12.1.1 Daemon operations #

The library reads status, requests lease renewal or reconciliation, and subscribes to resolver snapshots. Each ordinary operation opens its own Unix socket connection. The default path is /run/netd/control.sock; callers can select another filesystem socket.

A positive timeout in milliseconds bounds the entire connection, send, and receive exchange. A full listen queue can return EAGAIN before the deadline. A failed exchange does not prove that a command was not applied. The library does not replay commands or reconnect subscriptions automatically.

The library preserves the daemon's authorization checks. A successful connection alone does not grant permission to query or change network state.

12.1.2 Ownership and errors #

Each operation returns an owned result, including failures. The caller checks peios_netd_result_error before reading a result and frees it exactly once with peios_netd_result_free. Error codes are POSIX values; diagnostics are human-readable text, not stable identifiers. peios_netd_result_error returns the stored code without setting thread-local errno.

Returned strings and arrays are borrowed from the result. Strings contain UTF-8 bytes with explicit lengths and do not include a terminating NUL. A result owns copies of its input, so its views do not depend on caller buffers. Immutable results support concurrent readers; freeing a result must wait for all readers to finish. Input and output pointer requirements are documented in <peios/netd.h> and libnetd(3).

A subscription has independent ownership and must be freed separately. Calls and destruction on one subscription must not overlap. A receive timeout retains partial framing for the next call. Other receive errors close the connection and leave the subscription unusable.

12.1.3 Configuration validation #

Hostname checking returns the normalized hostname or an error. Profile resolution and policy construction accept neutral registry trees and perform no registry writes. Policy judgment accepts interface facts and reports the outcome using the same policy implementation as the daemon.

The public input boundary accepts at most 128 key levels, 65,536 total keys, values, and list items, and 4 MiB of text across both trees. Each fact set has a separate 4 MiB text limit. These limits bound library input handling; the daemon's registry reader and the policy parser impose their own limits.

Profile names compare without ASCII case distinctions. Invalid actions return validation errors, including malformed non-ASCII text. Disabled profiles remain visible in resolved results so configuration editors can inspect them.

12.1.4 Rust access #

Client::system selects the installed socket with an explicit Duration. status, renew, reconcile, and subscribe use the shared library. The wrapper returns owned Rust values and releases C results through Drop.

check_hostname validates a hostname. Policy::build, resolve_profiles, and judge expose configuration checks. Policy and subscription handles remain bound to their owning thread; the wrapper does not declare them Send or Sync.

The installed libnetd-devel package supplies the C development interface. Rust consumers select a matching netd-client source revision and link the installed library. The internal netd-core crate is not a replacement for the public shared-library boundary.

Appendix A Constants

Peios / Reference / netd

These constants bound netd's protocol, timing, and control behavior. The values below describe the implementation rather than configuration defaults.

A.1 Paths #

PathUse
Machine\System\Networkconfiguration root, readiness, DUID (§2.3, §8)
/run/netd/control.sockcontrol socket (§9.1)
/run/netdruntime directory, created by peinit (§2.1)
/var/state/netd/duidthe DUID, when the registry has none (§5.7)
/var/state/netd/secretthe RFC 7217 secret (§6.2)
/usr/sbin/netdthe daemon
/proc/sys/net/ipv6/conf/<name>/accept_raset to 0 (§6.1)

A.2 Numbers #

ConstantValue§
Routing protocol stamped on netd's routes200§4.3
Default route metric100; 600 for wireless§4.2
Minimum MTU applied68§4.3
Converge repetitions per passat most 4§2.2
Registry tree depth read16§2.3
Control message ceiling65536 bytes§9.2
Control read and write timeout2 s§9.1
DHCPv4 first backoff, ceiling4 s, 64 s, ±1 s jitter§5.2
DISCOVER retransmissions before "nobody answered"3§5.2
REQUESTs in Requesting before rediscovery4§5.2
REQUESTs in Rebooting before rediscovery2§5.2
Renewing and rebinding retransmission floor60 s§5.2
Shortest lease accepted4 s§5.3
DHCPv4 maximum message size advertised1500§5.1
DHCPv4 message paddingto 300 bytes§5.1
Domain-search compression jumps per name16§5.3
Link-local range169.254.1.0–169.254.254.255§5.5
Router solicitation interval, ceiling4 s, 3600 s, ±10% jitter§6.1
Solicitations before backoff3§6.1
Prefixes, RDNSS servers, DNSSL domains per advertisement option16§6.1
SLAAC prefix length64§6.2
Two-hour rule7200 s§6.2
Temporary address preferred lifetime86400 s minus 0–599 s§6.2
Temporary address valid lifetime172800 s§6.2
Temporary addresses per prefix4§6.2
Stable address counter attempts8§6.2
DHCPv6 first retransmission, ceiling1 s, 3600 s, ±10% jitter§6.3
DHCPv6 refresh default, floor86400 s, 600 s§6.3
DHCPv6 servers and domains kept16 each§6.3

A.3 Identifiers #

IdentifierValue§
Interface id digest prefixpeios-netd-ifid|§4.1
Network id digest prefixpeios-netd-network|§7.1
Stable address digest prefixpeios-ndp-stable-iid|§6.2
DUID-LL header00 03 00 01§5.7
Status descriptorO:SYG:SYD:P(A;;KA;;;SY)(A;;KR;;;WD)§8.1
NETWORK_QUERY, NETWORK_CONTROL, NETWORK_ALL_ACCESS0x1, 0x2, 0x000F0003§9.1

1.1 Overview

Peios / Reference / resolvd / Introduction

resolvd is the Peios stub resolver. It is the one process on a machine that answers names: a DNS client that answers from what it knows about the machine, from its cache, or by forwarding to an upstream server. It is not a recursive resolver and not an authoritative server.

The contract it implements is the Name Resolution Interface, PSPU §6. This manual describes the maintained resolvd implementation: the order it does things in, the limits it applies, and what it does where the contract leaves a choice.

1.1.1 Three doors, one engine #

A question reaches resolvd by one of three doors (PSPU §6.3):

DoorWhereWho uses it
Native socket/run/resolvd/resolv.sockThe resolv command, the NSS shim, Peios tools
Stub listener127.0.0.53:53 (UDP and TCP)Programs that speak DNS themselves
NSS shimlibnss_peios_net.so.2, loaded into every glibc processgetaddrinfo and the gethostbyname family

The shim is not a separate resolver: it is a client of the native socket. The native socket and the stub listener both hand their questions to the same engine inside the daemon, and the engine is the only thing that decides an answer.

1.1.2 Design boundaries #

It owns no network configuration. The servers, search domains and addresses of each interface arrive from netd over netd's control socket, as a whole snapshot each time anything changes. The registry holds only the fallbacks — servers to use when no interface offers any, extra search domains — and the static names that replace /etc/hosts. resolvd never writes /etc/resolv.conf; the file it ships is a constant that points at the stub listener.

A question goes to one interface. Each interface's contribution is a scope, and every name is routed to exactly one of them. Nothing is ever asked of every interface's servers at once. A single-label name is never sent upstream bare, and the cache is partitioned by scope, so an answer learned through a VPN disappears when the VPN's servers change or the VPN goes away.

One thread, and an engine with no I/O. The daemon is a single poll loop. The engine inside it is a pure state machine: it takes questions, upstream replies and the passage of time, and returns actions — bytes to send, transactions to abandon, answers to deliver. Every socket is the loop's. Reply writes use bounded nonblocking queues, so a client that stops reading does not hold up the event loop (§9.4).

It holds no privilege. resolvd runs under its own virtual service account. Port 53 is reached through a port reservation granted to its service SID, not through a capability.

It does not wait for the network. resolvd reports itself ready as soon as its two listening doors are open. localhost, the machine's own name and the registry's static names are answered with no network and no netd at all.

It does not validate. No DNSSEC validation is performed, and every answer from every door is reported unvalidated.

1.2 What This Manual Covers

Peios / Reference / resolvd / Introduction

This manual covers the resolvd source tree and its shared client library:

ComponentPackageInstalled as
The daemondev.peios.resolvd/usr/sbin/resolvd
The operator commanddev.peios.resolv/usr/bin/resolv
The NSS shimdev.peios.resolvd-nss/usr/lib/x86_64-linux-peios/libnss_peios_net.so.2

The dev.peios.libresolvd package supplies libresolvd.so.1; its -devel package supplies headers, linker metadata, and libresolvd(3).

1.2.1 Other packaged files #

dev.peios.resolvd also ships the constant /usr/etc/resolv.conf, the service definition and port reservation seeds under /usr/share/regim/, the registry reference /usr/share/regman/resolvd.regman, and the resolvd(8) page; dev.peios.resolv ships resolv(1).

Each package has a matching -debuginfo package, and dev.peios.resolvd-debugsource carries the sources for the component.

1.2.2 The source tree #

The source is one Cargo workspace, built with pekit, and the split is visible in what each part of the system can do:

CrateWhat it is
dnsThe DNS wire codec: names, messages, records. No I/O and no policy.
resolvd-coreThe native channel's types, MessagePack codec, and framing. No I/O beyond framing.
resolvdThe engine, the cache, the stub door's DNS rendering, and the daemon around them.
resolvThe operator command.
libresolvdThe public C shared library, with owned results and bounded exchanges.
resolvd-abiC-compatible data layouts.
resolvd-clientSafe Rust wrappers over the shared library.
nssThe shim. Built on resolvd-core and libc, without libpeios (§7.1).

1.2.3 Covered elsewhere #

The contract. What any resolver standing in resolvd's place has to do is PSPU §6: the doors (PSPU §6.3), the native channel's framing and control object (PSPU §6.4), the requests (PSPU §6.5), outcomes and validation (PSPU §6.6), the resolution model (PSPU §6.7), the stub door (PSPU §6.8), the network manager channel (PSPU §6.9), the shim (PSPU §6.10), and the limits (PSPU §6.B). Where a chapter here touches the contract it cites it and adds only what resolvd does.

netd's side of the channel. Which interfaces appear in a snapshot, how their servers and domains are merged from profile and lease, and when a snapshot is sent, are netd's, and are described in the netd TRM. This manual covers what resolvd does with a snapshot once it has one.

Kernel mechanisms. Registry watches, access checks, file descriptors, and port reservations are described in the Peios Kernel TRM. This manual says which of them resolvd uses and how.

1.3 Terminology

Peios / Reference / resolvd / Introduction

The protocol's terms — name, question, record, scope, route, outcome, source, door, synthetic answer, control object, stub door — are used as PSPU §6.2 defines them. The terms below are resolvd's own.

Task. One question the engine is working on: a name and a record type. A resolve or reverse request, and every stub query, is one task. A lookup is one task per address family it asks for.

Candidate. One name a task asks. A multi-label name has exactly one candidate, itself. A single-label name has one candidate per applicable search domain (§4.3), asked in turn.

Transaction. One query sent to one server over one transport, with its own DNS message identifier, its own case pattern, its own socket and its own deadline.

Attempt. A transaction counted against the question's attempt limit. Failures spend the shared question budget. A TCP retry after a truncated UDP reply also spends an attempt (§4.6).

Up scope. A scope at link or better. Up scopes contribute search domains and participate in routing independently of whether they have servers. Exclusive selection additionally requires addressed or better. Only the ordinary lowest-metric choice requires servers (§4.4).

Scope key. The string that identifies a scope in the cache and in routing: the interface's ifid from netd, or fallback for the registry's fallback servers.

Demoted server. A server address whose last failure was less than 30 seconds ago, and which has not given a usable reply since; it is tried after its healthy peers (§4.6).

In-flight ceiling. The bound on outstanding upstream transactions, beyond which a question that needs the network is answered unavailable at once (§4.6).

The loop. resolvd's single thread and its poll (§2.5).

2.1 The Service

Peios / Reference / resolvd / Startup and Configuration

2.1.1 The service definition seed #

resolvd is started by peinit from Machine\System\Services\resolvd. The package ships the definition as a registry seed, /usr/share/regim/resolvd-service.reg, which is inert until an image explicitly applies it.

2.1.2 The service definition values #

ValueTypeDataEffect
ImagePathREG_SZ/usr/sbin/resolvdThe binary. resolvd reads no command-line arguments.
TriggersREG_MULTI_SZbootStarted at boot.
IdentityREG_SZServiceRuns under its own virtual service account.
ReadinessREG_DWORD0Notify: ready when resolvd says so.
RuntimeDirectoriesREG_MULTI_SZresolvdpeinit creates /run/resolvd.
RestartPolicyREG_DWORD2Always restarted.
LimitNOFILEREG_DWORD16384Descriptor headroom for 4 096 upstream transactions, their client waiters, 512 pending clients and daemon descriptors.
ErrorControlREG_DWORD0
DisplayNameREG_SZStub resolver
DescriptionREG_SZ(one sentence)

2.1.3 Identity and privilege #

resolvd holds no privilege and needs none. Its one claim on the machine that an ordinary process could not make — binding UDP and TCP port 53 — is met by a port reservation rather than a capability (PSPU §6.8).

Without the reservation applied, the stub listener cannot bind and resolvd exits at startup (§2.2, §9.3).

2.1.3.1 The port reservation seed #

The reservation is a second seed, /usr/share/regim/resolvd-port.reg, also inert until an image applies it. It writes one value:

KeyValueType
Machine\System\Network\TcpIp\PortReservationstcp,udp:53REG_BINARY

2.1.3.2 Who holds the reservation #

The data is a security descriptor granting the reservation to SYSTEM and to resolvd's service SID, S-1-5-80-3864064249-1823296737-2008945602-1354971773-2894779966, so it follows the service rather than whichever account the service happens to run as.

The selector tcp,udp:53 is more specific than the kernel package's tcp,udp:1-1023 and so decides port 53 alone. The descriptor bytes are generated from the SID by a tool in the source tree, not written by hand.

2.1.4 Readiness #

With Readiness 0 peinit waits for a notification. resolvd:

  • sends the datagram READY=1 to the socket named by the NOTIFY_SOCKET environment variable once the native socket and both stub sockets are open and the registry has been read;
  • does not wait for netd: readiness is sent after the first attempt to reach netd whether that attempt succeeded or not;
  • sends nothing when NOTIFY_SOCKET is unset, and logs a failure to send as readiness notify: <error> and carries on starting. Sending has a one-second deadline.

2.1.5 Restart #

RestartPolicy 2 restarts resolvd whenever it exits. A restarted resolvd removes the socket file its predecessor left, logs removed a stale /run/resolvd/resolv.sock, and binds a fresh one (§2.4). Everything resolvd holds is in memory, so a restarted resolvd has:

  • an empty cache;
  • no demoted servers;
  • every counter at zero (§4.10);
  • no scopes, and the kernel's hostname, until the first snapshot after netd is reached again (§3.3).

2.1.6 Log lines #

2.1.6.1 The log line format #

Every line resolvd logs has the form

resolvd: <level>: <text>

where the level is info, warn or error. Informational lines go to standard output; warnings and errors go to standard error. peinit forwards both streams to eventd, marking only standard error as is_error=true. The lines are read with:

evctl 'LOGS FROM resolvd SINCE 1h ago TAKE 40'

2.1.6.2 The kernel log mirror #

Each line is also offered to /dev/kmsg, at kernel priority 6, 4 or 3 for info, warn and error. The mirror is opened when the first line is logged, after that line has been written to its output stream, and the open is never retried.

/dev/kmsg is writable by SYSTEM only, so for resolvd the open fails, and resolvd writes one line to standard error saying so, directly after the first log line:

resolvd: warn: /dev/kmsg mirror unavailable (<error>): log lines go to stdout/stderr only

The mirror warning follows the first log call. That first line can be on stdout or stderr, so readers must not assume a cross-stream ordering. On a start that fails, the first logged line is the fatal one, such as native socket: <error> (§2.4). On a start that succeeds, it is a warning from earlier in startup when there is one, such as removed a stale /run/resolvd/resolv.sock (§2.4) or a Dns … warning (§2.3), and otherwise the result of the first attempt to reach netd, subscribed to netd or netd not reachable (<error>); retrying, which comes before listening on … (§2.2). The mirror line is written once, and nothing further about the mirror is written. resolvd's lines never reach the console or dmesg.

2.2 Startup Sequence

Peios / Reference / resolvd / Startup and Configuration

2.2.1 The sequence #

  1. The native socket. The runtime directory and the socket are created and given their modes and descriptors (§2.4). A failure to create the directory, set a mode, remove a stale socket file, bind, or make the listener nonblocking is fatal: resolvd logs native socket: <error> at error level and exits with status 1. A failure to write a descriptor is not fatal (§2.4).
  2. The stub listener. A UDP socket and then a TCP listener are bound to 127.0.0.53:53. A failure of either is fatal: resolvd logs stub listener on 127.0.0.53:53: <error> and exits with status 1.
  3. The registry. Machine\System\Network\Dns is read whole (§2.3). A missing key selects defaults. A read failure, including unreadable values or malformed UTF-8, is fatal rather than applying partial policy.
  4. The registry watch. A subtree watch is armed on Machine\System\Network (§2.3). If it cannot be armed, resolvd logs registry watch unavailable (<error>); configuration is read once and runs on the configuration it read in step 3 until it restarts.
  5. Query entropy. The engine is given a kernel-randomness provider. Every upstream transaction obtains fresh bytes through nonblocking getrandom; startup does not seed a userspace generator or read /dev/urandom. There is no clock fallback.
  6. The engine's inputs. The engine is given the kernel's hostname, the fallback servers and search domains, and the static names. A kernel hostname that is empty or (none) counts as no hostname.
  7. The control object is built from ControlSecurity (§5.2).
  8. netd. The first attempt to subscribe is made immediately (§3.1). Its failure is not fatal and is retried with backoff (§3.2).
  9. The listening line. resolvd logs listening on /run/resolvd/resolv.sock and 127.0.0.53:53 at info level.
  10. Readiness. READY=1 is sent (§2.1).
  11. The loop is entered (§2.5).

2.2.2 Answering from the moment of readiness #

Both doors are open before readiness is reported, and neither waits for netd. A question asked the moment resolvd is ready is answered at once: synthetic and static names are answered, and anything that needs a server is answered unavailable until either a snapshot arrives or fallback servers are configured (§3.2).

2.2.3 Exiting #

resolvd has no shutdown path of its own. Apart from the startup failures above, nothing a client or an upstream server sends makes it exit.

2.2.3.1 Ending on a signal #

resolvd installs no signal handlers, so it ends when peinit signals it, with the default disposition, and leaves /run/resolvd/resolv.sock behind. The next start removes the stale socket file before binding (§2.4).

2.2.3.2 A poll failure exits #

When poll fails with anything other than EINTR, resolvd logs poll: <error> at error level and exits with status 1. EINTR is retried.

2.3 Registry Configuration

Peios / Reference / resolvd / Startup and Configuration

The registry holds resolvd's fallbacks and its static names, under Machine\System\Network\Dns; which keys a resolver reads is fixed by PSPU §6.9. Nothing about the live network is read from the registry; that arrives from netd (§3).

2.3.1 The Dns key and its defaults #

The key is opened for query and enumerate-subkey access. When it does not exist, every value below takes its default. Other open, query, or enumeration failures reject the complete read. Startup fails on such an error; the running service retains its previous configuration.

ValueType readDefaultUsed for
FallbackServersREG_MULTI_SZ, or one REG_SZ / REG_EXPAND_SZnoneThe fallback scope's servers (§4.4)
ExtraSearchDomainsREG_MULTI_SZ, or one REG_SZ / REG_EXPAND_SZnoneSearch domains after every interface's (§4.3)
ControlSecurityREG_BINARYthe compiled defaultThe control object (§5.2)
Hosts\a subkeyemptyStatic names (§4.2)

2.3.2 Reading strings #

  • A REG_SZ or REG_EXPAND_SZ is one string: its data up to the first NUL, read as UTF-8. Invalid UTF-8 rejects the complete configuration read.
  • A REG_EXPAND_SZ is read as it is stored; nothing in it is expanded.
  • A REG_MULTI_SZ is split at every NUL. Empty strings are skipped. Invalid UTF-8 rejects the complete read rather than omitting one entry.
  • A value of any other type is treated as absent.

2.3.3 FallbackServers #

  • Each string is trimmed of surrounding whitespace and parsed as an IPv4 or IPv6 address. A string that does not parse is skipped and logged as Dns FallbackServers: ignoring malformed address "<string>", with the string as stored — untrimmed, in double quotes, with quotes, backslashes and control characters escaped. A lone REG_SZ that is empty or only whitespace, a whitespace-only string in a multi-string, and an address with a zone such as fe80::1%eth0 (§4.7) are all logged this way.
  • There is no way to give a port; every server is asked on port 53.

The order of the list is the order servers are tried in (§4.6).

2.3.4 ExtraSearchDomains #

Each string is parsed as a domain name, with or without a trailing dot. It is not trimmed, so a leading or trailing space becomes part of a label. A string that does not parse, or that is the root — a lone empty REG_SZ, or . — is skipped and logged as Dns ExtraSearchDomains: ignoring malformed domain "<string>", quoted as for FallbackServers.

2.3.5 ControlSecurity #

  • A REG_BINARY value with at least one byte is taken as a self-relative security descriptor. An empty value, a value of another type, or an absent value selects the compiled default, with no log line.
  • Bytes that do not form a valid descriptor also select the compiled default, and resolvd logs ControlSecurity is not a valid descriptor (<error>); using the default each time it builds the control object from them: at startup, and at every configuration change (below).

2.3.6 Hosts\ #

  • Every value under Machine\System\Network\Dns\Hosts is one static name. The value's name is the host name and its data is one address (REG_SZ or REG_EXPAND_SZ) or several (REG_MULTI_SZ), read as above.
  • A value name that is not UTF-8 rejects the complete read.
  • A value name that does not parse as a domain name is skipped and logged as Dns Hosts: ignoring malformed name "<name>".
  • A value name that parses to the root — an empty name, or . — is skipped silently.
  • Each address is parsed as for FallbackServers, and a malformed one is skipped and logged as Dns Hosts: ignoring malformed address "<string>".
  • A name left with no valid address, including one whose value has any other type, is not a static name at all.
  • Names match case-insensitively, so Printer and printer are the same static name.

Where the same address is listed under several names, the reverse lookup of that address returns one of them (§4.2). A static name named localhost, or under it, never answers a forward question (§4.2).

2.3.7 Changes at run time #

2.3.7.1 The watch on the network key #

resolvd watches Machine\System\Network, recursively and for every kind of change, rather than the Dns key itself: the Dns key need not exist at boot, and a watch on a missing key cannot see it appear. Watch events are read into a 16 384-byte buffer.

2.3.7.2 What triggers a re-read #

Every non-empty batch of watch events, from anywhere under Machine\System\Network, causes the whole Dns key to be read again, as at startup. netd's own writes under that key cause such re-reads too. Each re-read logs the Dns FallbackServers, Dns ExtraSearchDomains and Dns Hosts warnings above again for every malformed string still present, whether or not anything has changed.

A failed read logs the failure and retains the existing configuration. A later notification triggers another attempt.

2.3.7.3 An unchanged configuration #

The fresh configuration is compared with the one in use. When nothing differs, nothing is applied and nothing more is logged.

2.3.7.4 A changed configuration #

When anything differs, resolvd, in this order:

  1. rebuilds the control object from ControlSecurity;
  2. replaces the fallback servers and search domains, discarding every answer cached through the fallback scope if the server list differs in content or in order;
  3. replaces the static names;
  4. logs configuration changed at info level.

2.3.7.5 When a change takes effect #

  • Every change applies to the questions and requests that arrive after it; nothing needs a restart.
  • Static names are never cached, so a new or removed Hosts\ value is visible to the next question.
  • Answers already cached through an interface scope are not discarded by a registry change.

2.3.7.6 When the watch fails #

  • If reading watch events fails, resolvd logs registry watch: <error>; re-arming and arms a new watch. The key is not read again when the new watch is armed, so a change made in between is applied only with the next event.
  • If arming the new watch also fails, watching stops without a further message, and the configuration in use stays as it is until resolvd restarts.

2.4 Sockets and Descriptors

Peios / Reference / resolvd / Startup and Configuration

2.4.1 The native socket #

The native door is a SOCK_STREAM Unix socket at /run/resolvd/resolv.sock (PSPU §6.4), inside resolvd's runtime directory rather than directly in /run, which resolvd's account cannot write.

At startup resolvd:

  1. creates /run/resolvd if peinit has not, and sets its mode to 0755;
  2. replaces the directory's DACL (below);
  3. removes any existing /run/resolvd/resolv.sock, logging removed a stale /run/resolvd/resolv.sock at warn level when there was one, and a removal that fails is fatal (§2.2);
  4. binds the socket, sets its mode to 0666, and replaces its DACL in the same way;
  5. makes the listener nonblocking.

2.4.1.1 A socket left by a previous run #

resolvd leaves its socket behind when it ends (§2.2), so a start that follows an earlier run finds one unless something else has removed it. The previous run gave its own account full access to the directory and the socket (below), so the new process removes the file in step 3, logs the removed a stale … line, and binds a fresh socket. This holds for every restart of the service: svctl restart, a stop and a start, and a restart by the policy after resolvd exits or is killed.

2.4.1.2 The DACL on the directory and socket #

The DACL written to both the directory and the socket is:

TrusteeAccess
SYSTEMGENERIC_ALL
resolvd's own account (its token's user)GENERIC_ALL
EveryoneGENERIC_READ, GENERIC_WRITE, GENERIC_EXECUTE

resolvd's own entry is what lets the next run start. Everyone's read, write and execute include neither DELETE nor deleting a child, so without it the next start could not remove the stale socket: it would exit with native socket: Permission denied (os error 13), and the restart policy would loop on that until the file was removed by hand. If resolvd cannot read its own identity it logs at warn level

could not read resolvd's own identity (<error>); a restart may not be able to replace <path>

and writes the DACL without that entry.

2.4.1.3 The owner of the directory and socket #

Only the DACL is written, so each object keeps the owner it was created with. peinit creates /run/resolvd before resolvd starts (§2.1), so the directory is owned by SYSTEM; resolvd creates the socket, which is owned by resolvd's account. Reaching the socket grants nothing: every request is checked against the control object (§5.2).

2.4.1.4 A descriptor that cannot be written #

If the descriptor cannot be written, resolvd logs at error level

could not set a descriptor on <path> (<error>); programs other than SYSTEM and administrators will not be able to reach the socket

and carries on. The socket then keeps whatever descriptor it was created with, and for ordinary processes the native door — and with it the NSS shim — is unreachable while the stub listener still works (§9.3).

2.4.2 The stub listener #

  • Two sockets, a UDP socket and a TCP listener, are both bound to 127.0.0.53 port 53 and both nonblocking (PSPU §6.8).
  • Nothing is bound on ::1 or on any other address.

Binding port 53 depends on the port reservation (§2.1).

2.4.3 Other descriptors #

DescriptorCountLifetime
The registry watch on Machine\System\Network0 or 1From startup; replaced on a watch error (§2.3)
The netd channel0 or 1While subscribed (§3.1)
Native connections reading or awaiting resolutionup to 256 totalReading: at most 5 s (§5.1); resolving: until completion or definite departure (§4.1)
Stub TCP connections reading or awaiting resolutionup to 256 totalReading: at most 10 s (§6.1); resolving: until completion or definite departure (§4.1)
Queued native reply writersup to 256Until written, failed, or the one-second write deadline (§2.5)
Queued stub TCP reply writersup to 256Until written, failed, or the one-second write deadline (§2.5)
Upstream socketsone per transaction, at most 4 096 including retriesOne transaction (§4.7)

2.4.3.1 Connections whose request has been read #

A connection whose request has been read keeps occupying a slot in its door's 256-connection allowance until resolution completes or a definite hangup/error abandons it. The engine's attempts and timeouts (§4.6) govern this phase; the request-delivery deadline does not apply. A completed answer that cannot be written immediately moves to the separate bounded reply-writer queue (§2.5).

UDP questions share the one listener socket, but retain at most 256 waiting origins in total and 16 per source address and port (§6.1).

2.5 The Event Loop

Peios / Reference / resolvd / Startup and Configuration

2.5.1 One thread and one poll #

resolvd runs on one thread. Every input is a descriptor in one poll call, and the engine sees time only when the loop hands it the current instant.

2.5.2 What is polled #

Each iteration builds the poll set afresh:

  1. the native listener, except during its accept-error backoff;
  2. the stub UDP socket;
  3. the stub TCP listener, except during its accept-error backoff;
  4. the netd channel, while connected;
  5. the registry watch, while armed;
  6. every native connection still sending its request;
  7. every stub TCP connection still sending its query;
  8. every upstream socket — for reading, or for writing while a TCP connection is still being established or its query is still being sent;
  9. native and stub TCP replies waiting to write, for writability;
  10. native and stub TCP streams awaiting engine answers, for hangup and error indications only. Readability and read-half-close are not requested, preserving supported half-closes without spinning on EOF.

2.5.2.1 The poll timeout #

The poll timeout is the earliest of: the next upstream transaction deadline, the next netd reconnection time while disconnected, the moment the oldest stub TCP connection reaches its 10-second bound, the moment the oldest native connection reaches its 5-second bound, the earliest queued reply write deadline, and the end of either listener's 250 ms accept-error backoff. With none of these pending, the loop sleeps until a descriptor is ready.

The timeout is the time to that moment in whole milliseconds, rounded down. A moment less than a millisecond away gives a timeout of zero, so the loop polls again without sleeping until the moment has passed.

2.5.3 Service order #

After poll returns, ready descriptors are serviced in this order:

  1. waiting native and stub TCP streams with definite hangup/error, canceling their questions and upstream transactions;
  2. upstream sockets — replies that have arrived are answers already owed;
  3. queued native replies, then queued stub TCP replies, whose sockets are writable;
  4. the stub UDP socket, reading at most 64 datagrams;
  5. the stub TCP listener, accepting at most 64 connections;
  6. stub TCP connections still sending queries;
  7. the native listener, accepting at most 64 connections;
  8. native connections still sending requests;
  9. the netd channel;
  10. the registry watch.

The fixed datagram/accept batches yield to the other doors and timers even while one listener remains continuously ready.

2.5.4 Timers after descriptors #

Once the ready descriptors have been serviced, the timers run, in this order: transactions at or past their deadline fail over to their next attempt (§4.6), a due netd reconnection is attempted (§3.2), stub TCP connections 10 seconds old or older are closed, expired reply writes are closed, and native connections 5 seconds old or older are closed.

2.5.5 Answers within an iteration #

A question that can be answered without the network — synthetic, from the cache, or refused — has its answer prepared and its first write attempted within the iteration that read it.

A question that needs the network sends its first transaction within that iteration too, and has its answer prepared in the iteration that sees its deciding reply or its last deadline. Delivery can continue over later writable events for a slow native or TCP reader.

2.5.6 Nonblocking reply writes #

Native and stub TCP replies get one nonblocking write attempt immediately. If the socket cannot accept the whole frame, the unwritten suffix is queued and resumed when that socket is writable. Each ready event makes one write attempt; partial progress is retained without duplicating bytes. The connection closes after the whole frame is written, on a write error, or when its fixed one-second write deadline expires. Progress does not extend that deadline. Other inputs and timers continue to be serviced.

At most 256 unfinished native replies and 256 unfinished stub TCP replies are queued. Each frame is bounded by its protocol ceiling (§5.1, §6.2). Even when a queue is full, a new reply gets its immediate write attempt; if it too needs queue space, that connection closes. Ready readers can therefore still receive replies while stalled readers occupy the queue.

Stub UDP replies and upstream queries are not written this way. The netd subscription request uses a nonblocking socket; failure to send it causes a reconnect attempt (§3.1).

3.1 Subscription

Peios / Reference / resolvd / The Netd Channel

The channel is the subscribe request of PSPU §6.9, on netd's control socket. This chapter describes resolvd's end of it; what netd puts in a snapshot and when it sends one is described in the netd TRM.

3.1.1 Connecting #

3.1.1.1 The subscribe request #

When a connection attempt is due (§3.2), resolvd:

  1. opens a nonblocking connection to /run/netd/control.sock;
  2. writes the subscribe request using a four-byte little-endian length and a MessagePack map;
  3. retains the nonblocking socket for snapshot reads.

A full connection queue or an incomplete subscription write fails the attempt without blocking the event loop.

The request needs netd's NETWORK_QUERY right for resolvd's account; whether that is granted is netd's decision.

3.1.1.2 A failed attempt #

A failure at any of the three steps is a failed attempt, and the next one is scheduled by the backoff of §3.2.

3.1.1.3 A successful attempt #

On success resolvd logs subscribed to netd at info level, discards anything buffered from an earlier connection, and waits for the first snapshot as an ordinary read on the channel. Only a successfully decoded snapshot resets its backoff (§3.2); connection success alone does not.

3.1.1.4 Nothing else is written to netd #

resolvd writes nothing more on the channel after the request.

3.1.2 Reading the stream #

When the channel is readable, resolvd reads in 8192-byte chunks until no bytes are available or the buffer reaches one maximum frame, including its length prefix. It then consumes complete frames in order:

FrameWhat resolvd does
A snapshot replyApplies it (§3.3), once the whole read has been taken. Several in one read are applied one after another, so the last wins.
An error replyLogs netd refused the subscription: <message>, and drops the channel once the whole read has been taken.
Any other well-formed replyIgnores it.
A payload that does not decodeLogs netd sent something unreadable: <error>, and drops the channel once the whole read has been taken.
A length above 65 536 bytesStops taking frames: the rest of the buffer is discarded and the channel dropped.

3.1.2.1 Frames behind an error are still taken #

An error reply or an unreadable payload does not stop the frames behind it. Every complete frame already read is still taken, in order, and any snapshot among them is applied. The same holds when the read ended at end of file or a read error: the frames read before it are all taken. Only a length above 65 536 stops the taking, and the frames before it have been taken by then.

3.1.2.2 The channel is dropped before the read's snapshots are applied #

When a read ends with the channel to be dropped, it is dropped — and lost the netd channel; reconnecting logged — after every frame has been taken and before any snapshot from that read is applied. In the log, the lost … line therefore comes before the netd: … summary lines (§3.3) of the snapshots read with it, and status then shows netd as false together with the scopes of those snapshots, until the channel is reconnected.

3.1.2.3 A partial frame #

A partial frame stays buffered until the rest arrives.

3.1.2.4 End of file or a read error #

End of file, or any read error other than EINTR or EAGAIN, drops the channel. EINTR is retried, and EAGAIN ends the read.

3.1.2.5 Dropping the channel #

Dropping the channel closes the socket, discards the buffer, logs lost the netd channel; reconnecting at warn level — once, however many of the causes above occurred in the read — and schedules a reconnection (§3.2).

3.2 Reconnection and Backoff

Peios / Reference / resolvd / The Netd Channel

Failure and reconnection are covered by PSPU §6.9. resolvd's backoff starts at 0.5 seconds and doubles to a ceiling of 10 seconds.

3.2.1 The backoff sequence #

The first attempt is made during startup, before readiness (§2.2). Each failed attempt schedules the next one the current backoff later, then doubles the backoff up to 10 seconds. Measured from a first attempt that fails, attempts are made at:

AttemptTime after the first
20.5 s
31.5 s
43.5 s
57.5 s
615.5 s
7 and laterevery 10 s

3.2.2 The unreachable warning #

A failed attempt made before any connection has succeeded is logged as netd not reachable (<error>); retrying when it is the first failure, and not logged otherwise. Together with the rule after a loss (below), the warning is written at most once in the life of the process: for the first failure, when that failure comes before the first successful connection. A resolvd whose first attempt succeeds never writes it.

3.2.3 A good snapshot resets the backoff #

A successfully decoded snapshot resets the backoff to 0.5 seconds. Connecting, writing the subscription, or receiving another reply kind does not reset it. A partial snapshot does not reset it until complete.

3.2.4 After a loss #

When an established channel is dropped (§3.1):

  • the next attempt is due after the current backoff, then the delay doubles up to 10 seconds. After a channel that delivered a snapshot, successive gaps are 0.5, 1, 2, 4, 8, then 10 seconds. A connection lost before its first snapshot continues the existing sequence;
  • the netd not reachable warning is not logged for the failures that follow, however many there are; the lost the netd channel; reconnecting line that preceded them is the record.

3.2.4.1 A refused subscription also backs off #

A netd that accepts the connection and then answers the subscription with an error has not delivered a snapshot. Its retries follow the same growing delay, up to ten seconds, as other failures. Each connection still logs subscribed to netd at info level and two warnings (§9.4). An accept-then-close or malformed reply likewise preserves the growing delay until a good snapshot arrives.

3.2.5 Disconnected from netd #

Losing netd changes nothing in the engine. The scopes from the last snapshot, the hostname taken from it, and every cached answer stay in use until the next snapshot replaces them; questions are answered exactly as before, and the servers in those scopes are still asked. status reports netd as false (§5.3).

3.2.6 Before the first snapshot #

When resolvd has never received a snapshot it has no scopes. It answers synthetic and static names, uses the fallback servers if any are configured, and answers everything else unavailable (§4.4).

3.3 Applying a Snapshot

Peios / Reference / resolvd / The Netd Channel

Each snapshot replaces resolvd's scopes whole (PSPU §6.9). Applying one has three parts: the hostname, the scope list, and the cache.

3.3.1 The hostname #

  • The snapshot's hostname is used when it is not empty. When it is empty, resolvd reads the kernel's hostname at that moment, into a 256-byte buffer; a kernel hostname that is empty or (none) counts as none.
  • The result is parsed as a domain name. A name that does not parse, or the root, leaves resolvd with no hostname: no synthetic answer is given for it, and status reports an empty hostname.
  • The kernel's hostname is otherwise read only at startup. A change to it is not seen until the next snapshot with an empty hostname.

3.3.2 The scope list #

Each DnsScope in the snapshot becomes one scope, in snapshot order:

Snapshot fieldBecomes
ifidThe scope key
nameThe interface name reported in answers and in status
serversServer addresses, in order. Malformed addresses are logged and dropped. Link-local IPv6 addresses use the containing interface; an optional %name or %index must match it (§4.7). There is no port; servers are asked on port 53.
domainsSearch domains, in order. A string that does not parse as a name, and the root, are dropped.
addresses(address, prefix length) pairs. A string that is not address/prefix is dropped.
default_route, exclusive, metric, levelCarried as they are
ntpIgnored

The ifid is used as it arrives. netd's interface ids are UUIDs, so none is fallback, the key of the fallback scope (§4.4); a scope that did arrive with that key would share the fallback scope's cache entries, would be asked through the fallback servers, and would lend its interface name to the fallback scope's answers.

3.3.2.1 Every scope is kept #

Dropped entries are dropped silently. Every scope in the snapshot is kept, whatever its level or server count; which of them take part in routing is decided per question (§4.4).

3.3.2.2 The snapshot summary line #

resolvd then logs one line at info level summarizing the snapshot:

netd: eth0: 1 server(s), 1 domain(s), default; wg0: 1 server(s), 0 domain(s)

with , default on each scope that claims the default route, or netd: no scopes for an empty snapshot. The counts are of the servers and domains left after parsing.

3.3.3 The cache #

Comparing the new scope list with the old one, by scope key:

  • a scope whose key is new loses any cached answers under that key;
  • a scope whose server list differs from before — in content or in order — loses its cached answers;
  • a scope missing from the new snapshot loses its cached answers;
  • a change to a scope's domains, addresses, flags, metric or level leaves its cache alone.

Demotion is kept per server address, with a scope distinction for link-local servers, and survives snapshots (§4.6).

3.3.4 Questions already in flight #

  • A candidate is routed when it is first asked (§4.4), and its retries stay with the scope key it was routed to. When that scope's servers change, retries use the new list; when the scope has gone, the next retry finds no servers and the question ends unavailable.
  • A transaction already sent is not canceled by a snapshot, and its reply can complete its original requester, but an invalidated task cannot repopulate the cache.

4.1 How a Question Is Answered

Peios / Reference / resolvd / The Engine

Every door ends here. The native socket's resolve, lookup and reverse, and every stub query, become one or more tasks, and each task takes the same path.

4.1.1 The path #

  1. Parse. The name is parsed from presentation form. A trailing dot makes no difference. Escapes are not interpreted; a label is the bytes between dots. A name with an empty label, a label over 63 bytes, or more than 255 bytes on the wire does not parse, and the task is answered notfound at once.
  2. Synthetic names. The name as asked is checked against the synthetic names (§4.2). A match answers the task.
  3. Candidates. The name becomes its list of candidates (§4.3). An empty list — a single label with no applicable search domain — answers the task notfound.
  4. Routing. Each candidate in turn is routed to one scope (§4.4). When no scope can take it, the task is answered unavailable.
  5. The cache. Unless the request asked to bypass the cache, the cache is consulted under that scope (§4.5).
  6. The network. Otherwise the candidate is sent upstream (§4.6 to §4.8).
  7. The next candidate. A notfound for a candidate — from the cache or from a server — moves to the next candidate when there is one. Any other result answers the task.
  8. The last candidate. When the last candidate is notfound, the task is answered notfound.

4.1.2 The empty name is the root #

An empty name, or . alone, parses as the root. The root is not a single label, so it is not expanded (§4.3): it is its own one candidate, routed and asked like any other name.

4.1.3 Each candidate is routed separately #

Each candidate is routed on its own, so the expansions of one single label can go to different scopes. Candidates share the question's attempt budget (§4.6).

4.1.4 What each way out reports #

Ends atOutcomesourceserverinterfacercode
Name does not parsenotfoundlocalnilnil0
Synthetic nameper §4.2synthetic or hostsnilnil0
No candidatesnotfoundlocalnilnil0
No scope can take the candidateunavailablelocalnilnil0
Cache hitas cachedcachethe server whose reply was cachedthe scope's interfacethe cached reply's response code
A server's replyfound or notfounddnsthe serverthe scope's interfacethe server's response code
Every candidate notfoundnotfoundas the last candidate's cache hit or server's reply, in the two rows aboveas that rowas that rowas that row
Attempts exhaustedunavailablelocalnilthe scope's interface0
No servers left in the scopeunavailablelocalnilnil0
In-flight ceiling reachedunavailablelocalnilnil0

A single label whose every expansion came back NXDOMAIN from a server therefore reports dns, the server that answered the last candidate, that candidate's scope's interface, and response code 3; when the last candidate's NXDOMAIN came from the cache, it reports cache with the cached server and code.

4.1.4.1 Answers from the fallback scope #

interface is nil for every answer from the fallback scope, which has no interface: its cache hits, its servers' replies and its exhausted attempts alike.

4.1.4.2 Validation #

validation is unvalidated in every case: resolvd performs no DNSSEC validation (PSPU §6.6).

4.1.5 What an answer carries #

An answer's records are the answer-section records of the reply that decided it, after the filtering of §4.8, or the synthetic records of §4.2. The engine also carries the candidate the answer was found at; the stub door uses it to add a CNAME (§6.2) and lookup uses it as the start of its CNAME chase (§4.9).

4.1.6 An asker that leaves #

While a native or stub TCP question is waiting for the engine, its stream is polled for hangup and errors. A definite hangup, error, or invalid socket abandons the question before ready upstream replies are processed: all of its transactions are canceled, including both families of an any lookup. Other questions continue normally.

Replies to canceled transactions are ignored; they do not populate the cache. Answers already cached before cancellation remain cached.

An abandoned question is removed from the waiting clients and no answer write is attempted for it. Cancellation does not count as an upstream failure, refusal or answer.

A write-half-close is supported: the client can stop sending while still waiting for its answer. Readable end of file alone therefore does not cancel a question. In particular, a TCP FIN cannot reliably distinguish a complete departure from a write-half-close. Without a definite hangup or error, the request retains its admission slot and runs through the usual engine attempts and deadlines. UDP has no disconnect notification.

4.2 Synthetic Names

Peios / Reference / resolvd / The Engine

PSPU §6.7 lists the names a resolver answers before any network. resolvd checks them in a fixed order, on the name as asked and before any search expansion, and the first match answers the task.

4.2.1 The order #

  1. localhost, or any name under it. 127.0.0.1 for A, ::1 for AAAA, both for ANY. Source synthetic.
  2. A static name. An exact, case-insensitive match against the Hosts\ values (§2.3). The name's addresses of the asked family — IPv4 for A, IPv6 for AAAA, both for ANY. Source hosts.
  3. The machine's hostname. An exact, case-insensitive match against the hostname (§3.3), answered with the machine's own addresses (below). Source synthetic.
  4. .local. The name local or any name under it is notfound, whatever the type asked. Source synthetic. No query is sent.
  5. A reverse-mapping name, for PTR or ANY only. See below.

A name that matches none of these goes on to search expansion and the network.

4.2.1.1 Static names beat the hostname and .local #

Because the order is fixed, a static name beats the hostname and .local: a Hosts\ value named printer.local is answered with its addresses, and one named after the machine overrides the machine's own addresses.

4.2.1.2 localhost beats a static name #

localhost is checked first, so a Hosts\ value named localhost, or a name under it such as printer.localhost, never answers a forward question: the synthetic loopback answer is given instead. Its addresses still answer reverse questions through the static-name row below, except loopback addresses, which the loopback row takes first.

4.2.1.3 Record types #

For the three address-bearing kinds, the answer is found whatever type was asked; a type other than A, AAAA or ANY, or a family the name has no address in, gives found with no records. localhost asked for MX is an empty found, not a notfound, and is not forwarded.

4.2.1.4 The machine's own addresses #

  • They are every address of every scope at addressed or better, whether or not the scope has servers, in snapshot order, link-local addresses included and loopback addresses excluded.
  • Repeated addresses are removed only when they are adjacent in that list, so an address on two interfaces that are not consecutive in the snapshot appears twice.
  • When there are none, the hostname is answered with 127.0.0.1 and ::1.

4.2.2 Reverse names #

4.2.2.1 Reverse-mapping names #

A reverse-mapping name is one under in-addr.arpa with exactly four labels before the suffix, or one under ip6.arpa with exactly 32. The suffix is matched case-insensitively.

  • Each in-addr.arpa label parses as a decimal number from 0 to 255. Leading zeros and a leading + are accepted, so 1.0.0.0127.in-addr.arpa and +1.0.0.127.in-addr.arpa both name 127.0.0.1.
  • Each ip6.arpa label is a single hexadecimal digit, in either case.

A name of either shape whose labels do not parse is not a reverse-mapping name.

4.2.2.2 Synthetic reverse answers #

Asked for PTR or ANY, a reverse-mapping name is answered synthetically when its address is:

AddressAnswerSource
A loopback address — anything in 127.0.0.0/8, or ::1PTR localhostsynthetic
Listed under a static namePTR that namehosts
One of the machine's own addresses, when there is a hostnamePTR the hostnamesynthetic

The rows are tried in that order.

4.2.2.3 An address shared by static names #

When several static names list the same address, resolvd returns one PTR: the name whose ASCII-lowercased presentation form sorts first in byte order. For example, alpha.home wins over beta.home. The answer is independent of registry insertion order, hash-table order, reloads and restarts while the set of matching names stays the same. It changes when that set changes and another name sorts first. The selected name retains its configured spelling in the reply. This rule applies to IPv4 and IPv6, for both PTR and ANY questions.

4.2.2.4 Other reverse questions #

A reverse name asked for any other type, and a reverse name whose address matches none of the rows, goes to the network.

4.2.3 Properties of every synthetic answer #

  • Every synthetic record has TTL 0.
  • Synthetic answers are never cached, and the no_cache flag has no effect on them.
  • Each one adds one to the synthetic counter (§4.10).

4.2.4 Expanded candidates are not checked #

Only the name as asked is checked. An expanded candidate is never compared with the synthetic names, so with a static name printer.lan and the search domain lan, a question for printer is expanded and sent to the network as printer.lan.

4.3 Single-Label Expansion

Peios / Reference / resolvd / The Engine

PSPU §6.7 sets the search expansion rules. This article is how resolvd builds and asks the list of candidates.

4.3.1 What counts as a single label #

  • A name is single-label when it parses to exactly one label. The trailing dot plays no part: printer. is single-label and is expanded exactly as printer is.
  • A top-level domain such as com is a single label too, and cannot be asked for directly: it is asked only as its expansions.
  • Any other name — a multi-label name, or the root — has one candidate, itself.

4.3.2 The applicable domains #

An exclusive scope at addressed or better supplies only its own search domains, whether or not it has servers. Otherwise, all up scopes contribute their domains in metric order, followed by ExtraSearchDomains.

An up scope without servers still contributes domains. Equal metrics keep snapshot order, and each scope retains its domain order.

An exclusive scope excludes other scopes' domains and extra domains. With no domains, a single-label question has no candidates and is notfound without a network query. A candidate selecting a serverless scope is unavailable if upstream work is needed; it does not move to another scope.

4.3.3 Building the candidates #

Each domain in turn is appended to the label.

  • A candidate already in the list, compared case-insensitively, is not added again.
  • A candidate longer than 255 bytes on the wire is left out.

With no candidates left the name is notfound without a query (§4.1).

4.3.4 The case of a candidate #

A candidate keeps the case of the label as asked and of the domain as configured; that is the case its records are reported at (§4.8).

4.3.5 Asking the candidates #

  • Candidates are asked one at a time, in order. Each is routed on its own (§4.4) and shares the question's attempt budget (§4.6).
  • A notfound — from a server or from the cache — moves to the next candidate (§4.1).
  • found, with records or without, is the answer, and later candidates are not asked.
  • unavailable is the answer, and later candidates are not asked.
  • When the last candidate is notfound, the question is notfound (§4.1).

4.4 Scope Routing

Peios / Reference / resolvd / The Engine

PSPU §6.7 gives the routing order. resolvd applies it to each candidate separately, when the candidate is first asked, and the candidate's retries stay with the scope it chose.

4.4.1 Which scopes take part #

A scope at link or better is up. Server availability does not exclude it from explicit routing decisions. Search expansion uses the same up scopes.

4.4.2 The steps #

  1. Exclusive. Choose an exclusive scope at addressed or better, preferring the lowest metric and then snapshot order.
  2. Search domain. Among up scopes, choose the longest matching domain suffix, compared by labels without case distinctions.
  3. Reverse subnet. For a reverse-mapping name, choose an up scope whose subnet contains the address. Lowest metric wins, then snapshot order. A prefix beyond the address width is treated as that width.
  4. Default route. Choose an up default-route scope, preferring the lowest metric and then snapshot order.
  5. Lowest metric. Choose an up scope that has servers, preferring the lowest metric and then snapshot order.
  6. Fallback. Use the fallback scope if configured servers exist.

The first matching step wins. When none selects a scope, the candidate is unavailable without a query.

4.4.2.1 An exclusive scope that does not qualify #

An exclusive scope at link alone does not qualify for step 1. It can participate in later steps as an ordinary up scope.

4.4.2.2 A selected scope without servers #

Steps 1 through 4 can select a scope without servers. If upstream work is needed, the candidate becomes unavailable; it does not fall through to another interface or the fallback set. Synthetic answers and the selected scope's cache keep their existing precedence.

4.4.2.3 Ties between search domains #

Between matching domains with the same number of labels, the one in the scope with the lower metric wins. With equal metrics too, the first match found wins: the earlier scope in snapshot order, and within one scope the earlier domain.

4.4.3 Consequences #

4.4.3.1 Step 1 takes every candidate #

Step 1 is absolute while it applies: with an exclusive scope chosen, every candidate goes to it, whatever its name, and step 2 never runs.

4.4.3.2 Search domains beat the subnet rule #

Step 2 runs before steps 3 and 4, so a scope whose search domain is in-addr.arpa or 10.in-addr.arpa takes reverse names ahead of the subnet rule.

4.4.3.3 Fallback servers are a last resort #

Fallback servers are used only when no earlier step selects a scope. An up scope with servers always wins before fallback, and a serverless match in steps 1 through 4 also prevents fallback. Answers cached through it are then not consulted, and stay in the cache until they are flushed, overwritten or evicted (§4.5).

4.4.3.4 A candidate asks only its own scope's servers #

Every attempt for a candidate, and the TCP retry after a truncated reply, goes to a server of the one scope the candidate was routed to. When those attempts fail, the candidate is unavailable (§4.6); the servers of other scopes, and the fallback servers, are not asked for it.

4.4.3.5 Demotion does not affect routing #

Routing reads only the current scope list. Which servers are demoted has no effect on which scope a candidate goes to: a scope whose every server is demoted still takes the candidates routing gives it.

4.5 The Cache

Peios / Reference / resolvd / The Engine

The cache's key and lifetimes are set by PSPU §6.7. This article is how resolvd computes them and what it does at the edges.

4.5.1 The cache key #

  • An entry is keyed by the candidate in lower case, the record type, and the scope key (§1.3). The class is not part of the key; every question resolvd asks is class IN. The stub rejects other classes before consulting the cache (§6.1), even when a matching IN answer is held.
  • The same name asked through two scopes is two entries, and a single label's expansions are each cached under the expanded name.

4.5.2 What is stored #

Only replies a server sent with response code NOERROR or NXDOMAIN are stored, under the candidate and the scope the candidate was routed to:

ReplyStored asLifetime
NOERROR with relevant answer records of class IN (§4.8)found with those recordsThe least TTL among those records, capped at 86 400 s
NOERROR with no relevant answer records of class INfound with noneNegative lifetime
NXDOMAINnotfoundNegative lifetime

4.5.2.1 The negative lifetime #

  • The negative lifetime comes from the first IN SOA record in the reply's authority section whose owner is the effective name or an enclosing domain. The effective name is the candidate after following its relevant CNAME path (§4.8); suffix matching respects label boundaries. Use the lesser of the SOA's MINIMUM field and its own TTL, capped at 300 s. When an alias leads to NXDOMAIN, also cap the lifetime at the least TTL of that alias path.
  • A reply with no qualifying SOA in its authority section has a negative lifetime of zero.

4.5.2.2 A zero lifetime is not stored #

An entry whose lifetime is zero is not stored. A positive answer with a zero TTL, and a negative answer without an SOA, are therefore never cached.

4.5.2.3 What is never stored #

Never stored: synthetic answers, unavailable, transport failures, a UDP reply with TC set (the reply to its TCP retry is the one considered), and replies with any other response code.

4.5.2.4 The TTLs inside an entry #

The records in an entry are kept with the TTLs the server sent. Only the entry's lifetime is capped.

4.5.3 Hits #

  • An entry is live while its expiry is in the future. A live entry is returned with each record's TTL lowered to the whole number of seconds the entry has left, rounded down, when that is less than the record's own.
  • A notfound hit with further candidates waiting moves to the next candidate, as a notfound from a server would (§4.1).

4.5.4 Bypassing the cache #

  • A resolve request with no_cache set skips the lookup for each of its candidates. The reply it gets is still stored.
  • Stub queries, lookup, and reverse always consult the cache.

4.5.5 Capacity and eviction #

  • The cache holds at most 8 192 entries.
  • Expiry alone does not remove an entry. Looking up an expired key removes it immediately, before any replacement answer arrives. Otherwise it stays until overwritten, flushed, or removed during admission at capacity. The cache_entries count in status includes expired entries that have not yet been removed.

4.5.5.1 Eviction #

Storing an entry under a key the cache does not already hold, when it already holds 8 192 entries, first evicts:

  1. every entry whose expiry is at or before the current time;
  2. then, if the cache still holds 8 192 entries, the one entry with the earliest expiry — any one of them, when several share it.

4.5.5.2 A long-lived answer preserves other live entries #

The sweep compares against the current time, independently of the new answer's lifetime. A day-long answer arriving at a full cache of live, shorter-lived answers replaces only the entry with the earliest expiry; the cache still holds 8 192 entries. If removing expired entries makes room, no live entry is evicted.

Older builds compared against the incoming answer's expiry and could empty a cache of live answers.

4.5.5.3 Overwriting a held key #

Storing under a key the cache already holds replaces that entry, live or expired, and evicts nothing else.

4.5.6 Flushes #

EventDiscards
A snapshot in which a scope is new, has a different server list, or is missing (§3.3)That scope's entries
A registry change to FallbackServers in content or order (§2.3)The fallback scope's entries
A flush request (§5.3)Everything
A restartEverything

Nothing else discards entries. Changes to static names, search domains, the hostname, ControlSecurity, scope flags, and metrics leave the cache as it is.

4.5.6.1 A reply after its scope was flushed #

A flush also invalidates pending tasks' permission to store answers. A global flush affects every pending task. Removing an interface scope or changing its servers affects tasks associated with that scope; changing the fallback list affects tasks associated with the fallback scope.

An invalidated task still completes its original requester normally, but cannot store any further answers. This restriction persists through UDP-to-TCP fallback, timeout retries and later search candidates, even if a later attempt uses a new server list. Removing and re-adding a scope does not restore the task's permission. Fresh requests can cache normally.

Changes only to metrics, search domains, or other scope properties with unchanged server lists do not invalidate admission; unrelated scopes' pending tasks are unaffected. This changes cache admission, not request cancellation or routing. Cache keys, TTLs, and eviction policy are unchanged.

4.6 Servers, Attempts, and Timeouts

Peios / Reference / resolvd / The Engine

Server order, demotion and the attempt limit are set by PSPU §6.7, and the contract's mainline values are in PSPU §6.B. resolvd's values are:

BoundValue
Transaction timeout2 s
Attempts per question (all candidates and transports)3
Demotion period30 s
Upstream transactions in flight4 096

4.6.1 Choosing the server #

  • For each attempt, the scope's servers — or the fallback servers — are put in order: the servers not demoted, in their configured order, followed by the demoted ones, in their configured order.
  • The attempt goes to the first server in that order not yet asked for this candidate. When every server has been asked, it goes to the server at position n mod count in that order, where n is the number of attempts already made for the candidate.
  • With one server, all three attempts go to it.
  • The order is computed afresh for each attempt, so a server demoted by the previous attempt is already behind its peers for the next.
  • Attempts for one candidate are made one at a time; a transaction is sent only after the previous one for the same candidate has ended.

With two healthy servers A and B, the attempts go to A, B, then whichever of them is first in the order at that moment — A if both have since been demoted, since demotion keeps configured order within the demoted group.

4.6.2 What fails an attempt #

Each of the following ends the transaction, adds one to upstream_failed, demotes the server, and moves to the next attempt:

  • no matching reply within 2 seconds of the transaction being sent;
  • an error opening, binding, connecting or sending on the transaction's socket, except the local resource and permission errors below — an unreachable network is known at once, not after the timeout;
  • an error receiving on a UDP socket, such as the refusal that follows an ICMP port-unreachable;
  • for TCP, the connection failing to complete: an error or hang-up while it is being established;
  • for TCP, an error, a hang-up or a failed write before the whole query has been sent;
  • for TCP, the connection closing, or a read error, before a whole matching reply has arrived;
  • a matching reply whose response code is neither NOERROR nor NXDOMAIN — SERVFAIL, REFUSED, FORMERR, NOTIMP, and every other code, including EDNS extended codes.

A synchronous failure to open or send a transaction caused by exhausted local descriptors (EMFILE, ENFILE), memory or buffers (ENOMEM, ENOBUFS), local address allocation (EADDRNOTAVAIL, EADDRINUSE), or permission (EACCES, EPERM) still adds one upstream_failed and advances the bounded retry sequence, but does not demote the server. A different configured address or address family might still be usable. If all attempts fail, the result is unavailable and is not cached.

A reply that does not match the transaction is ignored while the socket remains open for a matching reply until the original deadline (§4.8).

4.6.3 Demotion #

  • Demoting a server marks its address until 30 seconds from now; a further failure moves that mark forward.
  • A matching reply with response code NOERROR or NXDOMAIN that resolvd uses — a UDP reply without TC, or a TCP reply — removes the server's mark at once. A UDP reply with TC set does not remove it, whatever its response code; the reply to the TCP retry decides.
  • For ordinary addresses the mark is shared across scopes. Link-local addresses are distinguished by scope so failures on one link do not demote the same address on another.
  • A demoted server is still asked, after the healthy ones.
  • status lists, for each scope, which of its servers are demoted at that moment (§5.3); demotion of the fallback servers is not reported.

4.6.4 The attempt limit #

  • A question gets three upstream attempts across all search candidates and transports. Failures spend them: a timeout, a failure response code, or a transport failure. When its last attempt fails, the question is unavailable (§4.1).
  • The budget is not reset when the question moves to another candidate, but a candidate's NXDOMAIN that moves it on is an answer, not a failure, and does not spend an attempt. Every search candidate is therefore asked, however many there are. Cached answers spend no attempt.
  • The TCP retry following a truncated UDP reply (§4.7) spends one attempt and gets its own two-second deadline. A truncated reply on the final attempt cannot start TCP: the question is unavailable.

The three attempts allow at most six seconds of upstream timeout waiting in total, including TCP and search-domain expansion. Each NXDOMAIN that moves to another candidate adds one round trip. Loop scheduling and local I/O can add elapsed time; the attempt limit does not give those operations a separate deadline.

4.6.5 The in-flight ceiling #

  • When 4 096 or more transactions are outstanding, a question about to allocate an upstream transaction is answered unavailable at once, and the refused counter goes up by one. A question whose scope has no servers left is answered unavailable before the ceiling is looked at, and is not counted as refused.
  • Every send checks this ceiling, including later attempts and TCP retries. A retry is normally sent after its previous transaction has ended and been removed, so it can reuse that slot even at capacity. Exhausting the three-attempt budget is checked before allocating a transaction, and is not counted as a capacity refusal.
  • Synthetic names and cache hits are answered as usual whatever the count.

4.7 The Upstream Query

Peios / Reference / resolvd / The Engine

PSPU §6.7 sets the upstream behavior. This article is what resolvd puts on the wire to meet it.

4.7.1 Sockets #

4.7.1.1 One socket per transaction #

Every transaction has its own socket, opened when the transaction is sent and closed when it ends.

4.7.1.2 The UDP socket #

  • A new socket is bound to the unspecified address of the server's family, port 0, so the kernel picks the source address and a fresh ephemeral source port.
  • The socket is connected to the server's port 53, so the kernel delivers only datagrams from that address and port.
  • Each datagram is read into a 4 096-byte buffer; a longer datagram is truncated by the read.

The query is sent with one send.

4.7.1.3 The TCP connection #

A new nonblocking socket is connected to the server's port 53. When the connection completes, the query is written with its two-byte length prefix; once it is all written, the socket is read until the two-byte length and that many bytes of reply have arrived. Nonmatching frames are discarded and later frames are checked until a matching answer or the original deadline (§4.8). One query is sent per connection, which closes when the transaction ends.

4.7.1.4 A transaction that cannot be sent #

A failure found while a transaction is being sent — opening or binding its socket, connecting it, or, for UDP, sending the query — fails the attempt at once (§4.6) and is logged at warn level as upstream <server>: <error>. A TCP failure found later, once the connection is under way, is not logged, and neither is a timeout or a UDP receive error.

4.7.2 Link-local servers #

A link-local IPv6 server from netd is reached through the interface named by its DNS scope. Both UDP and TCP upstream sockets carry that interface's index in sin6_scope_id; a truncated UDP answer keeps it on the TCP retry. An address such as fe80::1 can therefore be advertised in RDNSS without a zone suffix. Failures of that address on one scope do not demote the same address on another scope.

A snapshot can also spell it fe80::1%eth0 or use a numeric interface index. An explicit zone must match the containing scope's interface; invalid or mismatched zones are logged and ignored. Global addresses continue to use ordinary unscoped sockets.

FallbackServers has no containing interface scope and continues to accept plain IP addresses only: a %zone value is logged and skipped. Configure link-local DNS on the interface profile instead. A bare link-local fallback cannot be sent; it fails as a local address error, without marking a remote server unhealthy.

4.7.3 The message #

FieldValue
ID16 bits from the kernel CSPRNG, fresh for every transaction
FlagsRD set; CD clear; everything else clear
QuestionThe candidate, case-randomized; the record type asked; class IN
AdditionalOne OPT record: payload size 1 232, DO clear, extended response code 0, version 0, no options

Authority and answer sections are empty.

4.7.3.1 Query entropy #

Every transaction obtains 34 fresh bytes through getrandom with GRND_NONBLOCK: two bytes for the message ID, interpreted little-endian, and 32 bytes of case bits, enough for every letter in a DNS name. This uses the kernel CSPRNG without a predictable userspace generator or a clock fallback.

If entropy is unavailable, including before the kernel CSPRNG is ready, resolvd logs the error, increments refused, and settles the affected question as unavailable without sending it. The event loop does not wait for entropy readiness; later requests can try again. Synthetic and cached answers do not need upstream entropy.

4.7.3.2 Case randomization #

  • Every ASCII letter in the candidate is flipped between upper and lower case when its random bit is 1. Digits, hyphens, and other bytes are unchanged.
  • Case bytes follow the ID bytes. Bits are taken lowest first from each byte in order. A bit is used only for a letter.
  • Each transaction — a retry to the same server, and the TCP retry after truncation, included — gets a new pattern and a new ID.

4.7.4 No fallback without EDNS0 #

Every query carries the OPT record. resolvd does not fall back to a query without EDNS0: a server that answers an EDNS0 query with FORMERR has failed the attempt (§4.6).

4.7.5 The TCP retry #

  • A matching UDP reply with TC set is not used. The same candidate is sent to the same server over TCP as a new transaction, with a new ID, a new case pattern and its own two-second deadline, if an attempt remains in the question budget. The TCP transaction spends one attempt (§4.6); without budget the question is unavailable.
  • A TCP reply with TC set is used as it is.

4.8 Reply Validation

Peios / Reference / resolvd / The Engine

4.8.1 Matching #

A reply is matched against the transaction it arrived for. It matches when all of these hold:

  1. it decodes as a DNS message — bytes after its last section are tolerated;
  2. its ID equals the transaction's;
  3. its QR bit is set;
  4. it has exactly one question;
  5. that question's type and class equal those sent;
  6. that question's name is byte-for-byte identical to the name sent, case pattern included.

4.8.1.1 A non-matching reply is ignored #

A reply that fails any of these is ignored: the transaction is not ended by it, nothing is counted, and the server is not demoted for it.

4.8.1.2 A non-matching datagram on UDP #

A datagram that does not match is discarded while the transaction's socket stays open. A later matching datagram can answer the same transaction. Ignoring a datagram does not extend the original two-second deadline: if no matching reply arrives, the attempt times out and the server is demoted (§4.6).

4.8.1.3 An undecodable or cut-short datagram #

The same holds for a datagram that does not decode. A datagram longer than the 4 096-byte read buffer arrives cut short. If the cut falls inside the DNS message, it cannot decode and is discarded; the socket remains available for another reply until the original deadline.

4.8.1.4 A non-matching TCP reply #

An undecodable or non-matching TCP message is discarded while the connection remains open. Later complete frames on that connection are checked, including frames already buffered and a matching frame followed by EOF. Partial frames remain buffered for the next read. Ignoring a frame does not extend the original deadline. If the peer closes before a matching frame completes, the attempt fails; if it stays open without a matching reply, the attempt times out (§4.6).

4.8.2 A matching reply #

A matching reply adds one to upstream_answered and ends the transaction. Then:

ReplyResult
UDP, TC setTCP retry to the same server (§4.7)
Response code NOERRORfound
Response code NXDOMAINnotfound
Any other response codeThe attempt fails (§4.6)

A NOERROR or NXDOMAIN reply that is used removes the server's demotion; a UDP reply with TC set does not (§4.6).

4.8.2.1 Extended response codes #

The response code is the header's four bits combined with the extended bits of an OPT record in the reply, so an extended code is never mistaken for NOERROR or NXDOMAIN.

4.8.3 What is taken from it #

4.8.3.1 Records #

  • Relevant answer records of class IN, in the order the server sent them.
  • For NXDOMAIN none are taken, even if the server sent some.
  • Start at the candidate. Keep records of the requested type at that owner; otherwise follow the first IN CNAME there, retaining it, and repeat at its target. Stop after sixteen aliases, on a repeated name, or when no matching record remains. Records unrelated to that path or of an unrequested type are discarded before rendering or caching. Their TTLs cannot shorten the cache lifetime.
  • An explicit CNAME question returns CNAME records at the queried owner. ANY accepts all IN types at that owner and does not follow aliases. Owner comparisons are case-insensitive and use DNS label boundaries.
  • The authority and additional sections are not returned.

4.8.3.2 The case of returned records #

A record whose owner name equals the candidate, case-insensitively, is given the candidate's case — the case of the question as asked, not the randomized case sent. Other records keep the case the server used.

4.8.3.3 Lifetime #

The cache lifetime of §4.5, computed from the answer records or from the authority section's SOA.

4.8.3.4 Upstream flags #

The server's AA, AD, RA, and CD bits are not used and are not carried into any answer.

4.8.3.5 An empty NOERROR #

A NOERROR reply with no relevant answer records of class IN — including a referral from a server that does not recurse — is found with no records.

A notfound with further candidates moves to the next one (§4.3); everything else answers the question.

4.9 Lookup and Reverse

Peios / Reference / resolvd / The Engine

4.9.1 lookup #

A lookup (PSPU §6.5) asks for A, AAAA, or both:

familyTasks
anyA and AAAA, started together
inetA
inet6AAAA

4.9.1.1 Each task is an ordinary question #

Each task is an ordinary question (§4.1): it has its own synthetic check, its own expansion, its own routing per candidate, its own cache lookups and its own attempts. The two tasks of an any lookup run at the same time and can be answered from different sources. The reply is built when the last of them is done.

4.9.1.2 The outcome #

Tasks' outcomesoutcome
At least one found, with or without recordsfound
None found, at least one unavailableunavailable
Every one notfoundnotfound

An A answer and an AAAA that is unavailable is found, with IPv4 addresses only.

4.9.1.3 Chasing CNAMEs #

For each found task, resolvd looks for addresses in that task's answer records, starting at the candidate the answer was found at. Names are compared case-insensitively.

  1. If the first record at the current name is a CNAME, and no record of the asked type is at the current name, the chase moves to the CNAME's target.
  2. This repeats at most 16 times; a loop stops there.
  3. The addresses are the A (for the A task) or AAAA (for the AAAA task) records at the name the chase ended at, in answer order, each with its record's TTL.

4.9.1.4 The chase asks nothing further #

Only the records in the task's own answer are used. A chain that leaves them — a CNAME whose target's addresses the server did not include — ends with no addresses, and no further question is asked.

4.9.1.5 The reply fields #

  • addresses lists each finished task's addresses in turn, in the order the tasks finished, so whether IPv4 or IPv6 addresses come first depends on which family was answered first.
  • canonical and source come from the same selected found task. Prefer a task that produced addresses; when both or neither did, prefer A over AAAA. Completion order does not affect this choice. canonical is the name that task's CNAME chase ended at, after search expansion. Without a found task it is the name asked, as parsed, in presentation form without a trailing dot (the root is .).
  • A found with no addresses still reports the expanded or chased name.
  • A name that does not parse is answered at once with outcome notfound, canonical ., no addresses and source local; no task is started.
  • source is the source of the selected task, and local when no task was found. It describes that task; the other family's records can have a different source.
  • validation is unvalidated.
  • A lookup adds one to queries however many tasks it makes.

4.9.2 reverse becomes a PTR question #

A reverse turns its address into the reverse-mapping name — the four octets reversed under in-addr.arpa for IPv4, the 32 nibbles reversed, in lowercase hexadecimal, under ip6.arpa for IPv6 — and resolves that name for PTR exactly as a resolve without no_cache would. The reply is an ordinary answer (§5.3).

4.10 Counters

Peios / Reference / resolvd / The Engine

The engine keeps seven counters, reported by status (§5.3). Each is an unsigned 64-bit count.

4.10.1 What each counter counts #

CounterGoes up by one for
queriesEvery resolve, lookup and reverse request that passes the access check, and every syntactically accepted stub query, including UDP budget refusals and requests whose name does not parse
syntheticEvery task answered by a synthetic name (§4.2), including .local's notfound; an any lookup of localhost adds two
cache_hitsEvery candidate found live in the cache (§4.5), including a notfound hit that moves on to the next candidate
upstream_sentEvery transaction started, UDP or TCP, including TCP retries. It is counted before the socket is opened, so a transaction whose socket cannot be opened, connected or sent on (§4.7) counts here as well as in upstream_failed, though nothing reached the wire
upstream_answeredEvery matching reply (§4.8), whatever its response code, including a truncated one
upstream_failedEvery failed transaction (§4.6): a timeout, a transport failure, or a reply with a response code other than NOERROR and NXDOMAIN
refusedEvery question refused at the in-flight ceiling (§4.6), the UDP pending budgets (§6.1), or because fresh query entropy is unavailable (§4.7)

4.10.2 What is not counted #

status and flush requests are not counted, and nothing on the netd channel is.

An unmatched reply changes neither upstream counter (§4.8). A later matching reply adds one upstream_answered; if the original deadline expires without one, the timeout adds one upstream_failed instead. A reply with SERVFAIL shows up in both. A transaction that could not be sent shows up in upstream_sent and upstream_failed, and never in upstream_answered.

4.10.3 Resetting the counters #

The counters start at zero when resolvd starts, and are reset only by a restart. flush does not reset them.

5.1 Framing and Limits

Peios / Reference / resolvd / The Native Socket

The framing, the one-request-per-connection rule, and the requirement to answer errors with an error reply are PSPU §6.4's. This article is resolvd's reading of them.

5.1.1 Accepting connections #

At most 64 waiting connections are accepted per event-loop iteration. When 256 native connections are either still sending their requests or waiting for engine answers, a newly accepted connection is closed at once, with no reply; so is one that cannot be made nonblocking. Reading a request keeps its slot occupied until resolution completes or the asker is abandoned (§4.1). Reply writers use a separate bounded queue (§2.5).

5.1.2 Reading the request #

Each connection is read without blocking. Partial headers and payloads are retained until more bytes arrive or the delivery bound expires.

  1. Read exactly the four-byte little-endian payload length. A length above 65 536 gets the reply request too large and the connection closes, without reading any payload bytes.
  2. Read only that many payload bytes, in chunks of at most 4 096 bytes. The buffered frame never exceeds 65 540 bytes, including its header.
  3. Decode the complete payload immediately. Bytes after this first frame remain unread and do not count against its size ceiling; they cannot make a legal request too large.

5.1.2.1 The length check precedes the payload #

The declared length is checked before any payload is read, even when the client queues the header and a large payload together. A legal request followed by additional bytes is still answered once. This is one request per connection; extra frames are not processed. When extra bytes remain unread, the client can observe a connection reset after its framed reply instead of a clean end of file.

5.1.3 A connection that ends early #

  • A connection that closes, or fails to read, before its request is complete is dropped without a reply.
  • A client that sends its whole request and then shuts down its writing side is answered as usual, whether the end of file is already waiting behind the request or arrives later. The complete frame is decoded without reading beyond it, and the connection closes after its one reply. A partial frame followed by end of file is dropped immediately, without waiting for the delivery timeout.
  • A connection that has not delivered a complete request five seconds after it was accepted is closed without a reply.

5.1.4 Decoding #

The payload is a MessagePack map. Keys are strings; duplicate top-level keys fail. Duplicate keys within an unknown skipped value are not checked.

Unknown fields are skipped, including floats, fixed and variable-length extensions, and the full unsigned 64-bit range. Skipped strings must still be valid UTF-8 and skipped containers retain the 32-level depth limit. Truncated values fail, and the reserved 0xC1 marker is unsupported.

query is required and must name a supported operation.

Known fields are type-checked even when unused by the selected operation. The type field must fit its documented range. Unknown-field skipping does not widen any known field's accepted range.

Bytes after the top-level map are ignored. The first error encountered in map order is returned; required-field checks follow decoding of the map.

5.1.5 Error replies #

Every error reply is ok: false with an error string and nothing else. The decoder reports these causes:

errorCause
request too largeThe size checks above
malformed message: truncated messageThe payload ends inside a value, or an array or map claims more items than bytes remain, a map's keys and values counted separately
malformed message: unexpected value typeA known field, a key, or the payload itself has the wrong MessagePack type; this includes a type that is negative or above 9 223 372 036 854 775 807
malformed message: unsupported value typeThe reserved MessagePack marker 0xC1
malformed message: string is not UTF-8A string that is not UTF-8
malformed message: nested too deeplyNesting beyond 32 levels inside a skipped value
missing or malformed field <name>A field the request needs is absent; a type, in any request, from 65 536 to 9 223 372 036 854 775 807; or the address of a reverse that is not an IP address
duplicate field <name>A repeated key
unknown query "<name>"A query resolvd does not know
access deniedThe access check (§5.2)
reply too largeThe encoded reply would exceed the 65 536-byte payload ceiling; it is replaced by this error

5.1.5.1 The connection after an error reply #

After an error reply the connection is closed.

5.1.6 Writing the reply #

  • The reply is framed the same way — four-byte little-endian length, then the MessagePack map — and written without blocking. An unfinished write is queued with a fixed one-second deadline and a cap of 256 queued native replies (§2.5). A failed or expired write is logged as control: reply failed: <error>. The connection is then closed.
  • An encoded reply payload can be at most 65 536 bytes, excluding its four-byte length prefix. A larger reply is replaced by the error reply too large; no partial answer is sent. This applies to every native reply kind. Exactly 65 536 bytes is allowed.

5.2 The Access Check

Peios / Reference / resolvd / The Native Socket

The control object and its check are PSPU §6.4's. resolvd makes the check after the request has been decoded and before anything else is done with it.

5.2.1 The check #

  1. The connecting peer's token is opened from the socket. When it cannot be, resolvd logs control: no peer token: <error> and the request is denied.
  2. A KACS access check is made of the request's right against the control object's descriptor, with that token. A check that cannot be completed counts as a denial.
  3. A denied request is answered access denied (§5.1).
RequestRight
resolve, lookup, reverse, statusRESOLVER_QUERY (0x0001)
flushRESOLVER_CONTROL (0x0002)

5.2.1.1 The generic mapping #

The check uses this generic mapping:

Generic rightMaps to
GENERIC_READRESOLVER_QUERY, READ_CONTROL
GENERIC_WRITERESOLVER_CONTROL, READ_CONTROL
GENERIC_EXECUTERESOLVER_QUERY
GENERIC_ALLRESOLVER_ALL_ACCESS (0x000F0003)

5.2.1.2 Decoding comes before the check #

A request is decoded before it is checked, so a malformed request gets its decoding error whoever sent it, and an unknown query gets unknown query rather than access denied.

5.2.1.3 The answer does not depend on the caller #

The peer's identity is used for this check and for nothing else. Every caller allowed to ask gets the same answer to the same question.

5.2.2 The compiled default descriptor #

The descriptor is ControlSecurity when it holds a valid self-relative descriptor, else the compiled default (§2.3):

ComponentValue
OwnerSYSTEM
GroupSYSTEM
DACLSYSTEM: RESOLVER_ALL_ACCESS; Administrators: RESOLVER_ALL_ACCESS; Everyone: RESOLVER_QUERY and READ_CONTROL

5.2.3 A new descriptor applies to later requests #

The descriptor is rebuilt whenever the registry configuration changes (§2.3). A request decoded after the change is checked against the new one; a request already being answered is not checked again.

5.2.4 What the control object does not govern #

The stub listener is not checked against the control object (PSPU §6.8): anything on the machine that can reach 127.0.0.53 can ask. A program denied RESOLVER_QUERY on the native socket still resolves names through the stub listener. The NSS shim uses the native socket, so for such a program getaddrinfo fails (§7.1) while a resolver that speaks DNS directly succeeds.

5.3 Requests

Peios / Reference / resolvd / The Native Socket

The requests, their fields, and their reply shapes are PSPU §6.5. This article covers what resolvd accepts and what it fills in.

5.3.1 Common to every request #

A request that passes the access check (§5.2) is handled at once:

  • status and flush are answered within the same loop iteration;
  • the other three become engine questions (§4.1), and the connection is held until the engine answers; the reply is written then.

5.3.2 resolve #

FieldAccepted
nameAny string: no name is refused at decoding. It is handed to the engine as it is, which parses it (§4.1).
typeAny value from 0 to 65 535, forwarded as it is — ANY (255), OPT (41) and types resolvd has no parser for included.
no_cacheBoolean; absent means false. Skips the cache lookup (§4.5).

The reply's outcome, source, server, interface, and rcode are as §4.1 describes. Each record carries:

KeyContent
nameThe owner name in presentation form, without a trailing dot; the root is .. A dot or backslash inside a label is written \. or \\, and any byte outside ! to ~ as a backslash and three decimal digits.
typeThe record type number
ttlAs sent by the server, lowered on a cache hit (§4.5); 0 for a synthetic record
dataThe record data in uncompressed wire form
textThe record data in presentation form (below)
Typetext
A, AAAAThe address
CNAME, PTR, NSThe target name, written as name is
SOAmname rname serial refresh retry expire minimum
MXpreference exchange
SRVpriority weight port target
TXTEach string in double quotes, separated by spaces; inner quotes are escaped as \", backslashes are not escaped, and bytes that are not UTF-8 become U+FFFD
Anything else\# <length> <hex>, the hex in lower case

5.3.3 The lookup family #

family takes any, inet, or inet6. Absent, or any other string, means any. The reply is built as §4.9 describes.

5.3.4 The reverse address #

address is an IPv4 or IPv6 address in textual form; anything else is the error missing or malformed field address. The question is built as §4.9 describes.

5.3.5 status #

KeyContent
hostnameThe hostname in use (§3.3), or an empty string when there is none
netdWhether the netd channel is connected at this moment
scopesEvery scope in the latest snapshot, in snapshot order — including scopes with no servers and scopes that take no part in routing
fallback_serversFallbackServers as parsed (§2.3)
cache_entriesThe number of entries held, expired ones included (§4.5)
counters§4.10

5.3.5.1 Each scope in status #

Each scope carries interface (the interface name), servers and domains as parsed from the snapshot (§3.3), default_route, exclusive, metric, subnets, and demoted:

  • subnets holds the interface's addresses as address/prefix — the address itself, not the network it is in;
  • demoted holds those of the scope's servers that are demoted at this moment (§4.6);
  • a scope's level is not reported.

5.3.6 flush #

  • Every cache entry, for every scope, is discarded, resolvd logs cache flushed at info level, and the reply is ok: true with no kind.
  • Demotions and counters are left as they are.

6.1 Receiving Queries

Peios / Reference / resolvd / The Stub Listener

The stub listener's address, its loopback-only rule and its rendering are PSPU §6.8. This article covers how resolvd reads queries; the replies are §6.2.

6.1.1 UDP #

When the UDP socket is readable, at most 64 datagrams are read per event-loop iteration, including malformed or dropped datagrams. For each:

  1. A datagram whose source address is not a loopback address — anything outside 127.0.0.0/8 — is dropped without a reply.
  2. It is checked as a query (below). A refused query gets its error reply, or nothing.
  3. A valid query is admitted if fewer than 16 UDP questions from its source address and port, and fewer than 256 UDP questions in total, are waiting for engine answers. Otherwise it gets SERVFAIL, with no upstream transaction, and increments both queries and refused. This admission check precedes synthetic and cache lookup.
  4. An admitted query becomes an engine question (§4.1). Its slot is released when the engine completes it, including timeout completion.

The endpoint is an accounting key, not an authenticated process identity. Changing source ports can consume the aggregate UDP allowance but cannot consume the separate native or TCP admission allowances. These bounds limit retained work; they do not promise fairness between local processes.

6.1.1.1 The UDP read buffer #

Each datagram is read into a 4 096-byte buffer; a longer datagram is truncated by the read to its first 4 096 bytes.

6.1.1.2 A UDP query longer than the buffer #

A query longer than 4 096 bytes therefore arrives cut short. When the cut falls inside the DNS message, the message does not decode and, being at least 12 bytes long, is answered FORMERR (below). Bytes after the end of the message are ignored by decoding, so a query whose message fits in 4 096 bytes and is only padded beyond them is answered as usual.

6.1.1.3 Where UDP replies go #

Replies are sent to the source address and port the query came from.

6.1.2 TCP #

When the TCP listener is readable, at most 64 waiting connections are accepted per event-loop iteration. A connection is closed at once, without a reply:

  • when 256 stub TCP connections are still sending queries or waiting for engine answers;
  • when its source is not a loopback address.

A connection that cannot be made nonblocking is closed the same way.

6.1.2.1 Reading a TCP query #

Each held connection is read as it becomes readable, everything available each time, in 4 096-byte chunks. A message is a two-byte big-endian length and that many bytes.

  • When more than 65 537 bytes are buffered, the connection is closed without a reply.
  • When a whole message has arrived, it is checked as a query, and the connection leaves the set of connections still sending, but continues to occupy its admission slot while the engine works.
  • A connection carries one query. Anything sent after the first message is ignored, and the connection is closed once the answer, or the error reply, has been written.
  • A connection that closes, or fails to read, before its message is whole is closed without a reply.
  • A client that sends a complete query and then shuts down its writing side is still answered. This also applies when the read finds end of file immediately after the buffered query. The connection closes after its one reply. A partial frame followed by end of file is dropped immediately, without waiting for the delivery timeout.
  • A connection that has not delivered a whole message ten seconds after it was accepted is closed without a reply.
  • Once its query has arrived the ten-second bound does not apply; the connection is held until the engine answers or a definite hangup/error abandons its question (§4.1). Reply writers use a separate bounded queue (§2.5).

6.1.3 Checking a query #

The messageResult
Does not decode, and is at least 12 bytes longFORMERR: the query's ID, QR set, every other header bit clear, no sections
Does not decode, and is shorter than 12 bytesDropped without a reply
Has QR setDropped without a reply
Has an opcode other than QUERYNOTIMP
Has no question, or more than oneFORMERR
Has a question class other than INNOTIMP; the question is echoed unchanged and no upstream query is made
OtherwiseAccepted

6.1.3.1 The NOTIMP and question-count FORMERR replies #

These two replies are built from the query:

  • the header copies the query's ID, opcode, RD and CD bits, and sets QR and RA; every other bit is clear;
  • the question section is the query's, whatever it holds;
  • when the query carried an OPT record, the reply carries one whose payload size is the size the query advertised, with DO clear and no options; without one, the reply has none.

6.1.4 What an accepted query contributes #

  • Only IN questions are accepted. Their decoded name and type reach the engine; unsupported classes are rejected at the stub door over both UDP and TCP.
  • RD, CD, the DO bit, and any EDNS options are not looked at.
  • Stub queries always consult the cache (§4.5).

6.1.4.1 Wire names #

The decoded name reaches the engine directly, without conversion to presentation text and reparsing. Label boundaries and bytes, including embedded dots, backslashes, NUL and other binary bytes, are preserved. The usual upstream ASCII case randomization still applies (§4.3).

Names are subject to DNS wire limits, not the length of a displayed escape sequence. A valid 63-byte binary label or a valid name whose display form would exceed 255 bytes can therefore be resolved normally.

Search expansion (§4.1) uses the number of wire labels: a single label containing a literal dot remains a single-label name.

6.1.5 Which stub queries are counted #

Every valid query counts in queries (§4.10), including a UDP query refused by the pending budgets (which also increments refused). Queries rejected by syntax, opcode, question count, or class checks do not count.

6.2 Rendering Replies

Peios / Reference / resolvd / The Stub Listener

The outcome-to-response-code table and the rules for CNAME, RA, AA and AD are PSPU §6.8. This article is how resolvd builds each reply.

6.2.1 The header and question #

  • The reply copies the query's ID, opcode, RD and CD bits and its question section.
  • QR and RA are set. AA, AD and TC are clear, except that TC is set on a truncated UDP reply (below).
  • No bit from an upstream server's reply reaches the stub reply.

6.2.2 By outcome #

6.2.2.1 found replies #

  • The response code is NOERROR, and the answer section holds the engine's records in the order the engine has them (§4.8).
  • When the answer was found at a candidate other than the question's name — compared case-insensitively — the section begins with a CNAME from the question's name, in the query's case, to the candidate. Its TTL is the least TTL among the records when any are present.
  • A found with no records at an expanded name is NOERROR with only that leading CNAME. Its TTL is the negative cache lifetime: the lesser of the enclosing upstream SOA record's TTL and minimum field, capped at 300 seconds and at the TTL of any CNAME path the reply followed (§4.5). A cache hit uses the remaining lifetime, rounded down to whole seconds. With no enclosing SOA, the TTL is zero; no lifetime is invented. The authority section remains empty. An unexpanded empty found has no CNAME.

6.2.2.2 notfound replies #

NXDOMAIN, with empty answer and authority sections. No SOA is supplied, so a client has nothing from which to cache the absence.

6.2.2.3 unavailable replies #

SERVFAIL, with empty sections.

6.2.3 EDNS in stub replies #

When the query carried an OPT record, the reply carries one advertising a payload size of 1 232 bytes, with DO clear and no options. A query without OPT gets a reply without one.

6.2.4 Size and truncation #

  • Over UDP the reply's size limit is the payload size the query's OPT advertised, or 512 bytes when that is smaller or there is no OPT.
  • A reply over the limit is replaced by a truncated one, which keeps the same header with TC set, and the question.
  • The truncated reply keeps the OPT record when the reply has one.
  • The truncated reply carries no records: nothing is partially included.
  • A reply that cannot be encoded at all is not sent.
  • Over TCP the whole reply is sent, whatever its size up to the 65 535 bytes a DNS message can hold.
  • A TCP reply is written with its two-byte length, without blocking. Unfinished writes are queued with a fixed one-second deadline and a cap of 256 queued TCP replies (§2.5); a failed or expired write is not logged.

7.1 The Module

Peios / Reference / resolvd / The Nss Shim

The shim's obligations are PSPU §6.10. This chapter describes the module resolvd's source tree builds.

7.1.1 The object #

  • libnss_peios_net.so.2 is installed by dev.peios.resolvd-nss at /usr/lib/x86_64-linux-peios/libnss_peios_net.so.2.
  • It is built from the nss crate, with the native channel codec compiled in. Its only shared-object dependencies are libc.so.6 and the dynamic loader, ld-linux-x86-64.so.2. The GCC unwinder required by Rust is linked statically, with its symbols private to the module; name lookups do not load libgcc_s.so.1. The identity shim, libnss_peios.so.2, uses the same static-unwinder arrangement. Neither shim links libpeios.

7.1.1.1 The entry points #

The module exports six entry points:

Entry pointAsks
_nss_peios_net_gethostbyname4_rlookup, family any
_nss_peios_net_gethostbyname3_rlookup, family from af
_nss_peios_net_gethostbyname2_ras gethostbyname3_r, with no TTL or canonical name out
_nss_peios_net_gethostbyname_ras gethostbyname3_r, with af AF_INET
_nss_peios_net_gethostbyaddr2_rreverse
_nss_peios_net_gethostbyaddr_ras gethostbyaddr2_r, with no TTL out

7.1.2 One connection per call #

  • Every call that needs resolvd opens a new connection to /run/resolvd/resolv.sock, sends one request, reads one reply, and closes the connection.
  • Nothing is kept between calls: no connection, no cache, no configuration. The module reads no file.

7.1.2.1 The ten-second socket timeouts #

Connection creation is nonblocking. A full local listener queue returns UNAVAIL instead of waiting indefinitely. Once connected, the socket is given ten-second read and write timeouts, which apply to each read and write on the socket. Ten seconds is longer than the six seconds a question's three timed-out attempts take in resolvd, TCP retries included (§4.6), so a slow upstream normally reaches the caller as unavailable from resolvd rather than as a timeout here. A question can still reach the timeout when many search candidates each answer NXDOMAIN slowly, since those answers do not spend the attempt budget; that is reported as the table below shows.

7.1.3 Results #

ResultNSS statuserrnoh_errno
Addresses, or names, foundSUCCESS——
found, but no address of the asked familyNOTFOUNDENOENTNO_DATA
notfoundNOTFOUNDENOENTHOST_NOT_FOUND
unavailableTRYAGAINEAGAINTRY_AGAIN
No reply within ten secondsTRYAGAINEAGAINTRY_AGAIN
resolvd cannot be connected toUNAVAILENOENTNO_RECOVERY
An error reply, including access deniedUNAVAILENOENTNO_RECOVERY
A reply of the wrong kind, a reply that does not decode, or any other I/O errorUNAVAILENOENTNO_RECOVERY
The caller's buffer is too smallTRYAGAINERANGENETDB_INTERNAL (-1), required for retry
gethostbyname3_r or 2_r with an af other than AF_INET or AF_INET6UNAVAILEAFNOSUPPORTNO_DATA
gethostbyaddr2_r or _r with an af and length other than AF_INET/4 or AF_INET6/16UNAVAILEAFNOSUPPORTNO_RECOVERY
A null name, a name that is not UTF-8, or a null addressNOTFOUNDENOENTHOST_NOT_FOUND

A found reply without a usable address of the requested family returns NOTFOUND, ENOENT, and NO_DATA. A found reverse reply without a PTR record has the same result. Explicit notfound remains HOST_NOT_FOUND.

7.1.3.1 AF_UNSPEC #

AF_UNSPEC is accepted only by gethostbyname4_r, which always asks for both families.

7.1.4 The caller's buffer #

Every string, pointer array, and address the module returns is placed in the buffer glibc passes in; the module allocates nothing that outlives the call. When the buffer cannot hold the result, the call returns as in the table, and nothing written to the buffer is valid.

7.2 Forward Lookups

Peios / Reference / resolvd / The Nss Shim

7.2.1 localhost in the shim #

  • A name that, with trailing dots removed, is localhost or ends in .localhost, compared case-insensitively, is answered inside the calling process without contacting resolvd — whether resolvd is running or not.
  • The answer is 127.0.0.1 for IPv4, ::1 for IPv6, or both, IPv4 first, with canonical name localhost and TTL 0.

7.2.2 Other names #

  • Any other name is sent as a lookup (§4.9), with the family the entry point asks for. The addresses in the reply are filtered to that family, and an empty result is NOTFOUND (§7.1).
  • Addresses are returned in the order resolvd's reply lists them.

resolvd does not fix which family comes first (§4.9); glibc's own sorting of getaddrinfo results is what callers normally see.

7.2.3 gethostbyname4_r #

The result is a linked list of gaih_addrtuple, and the pointer glibc passes is overwritten with the head of the list:

FieldContent
nextThe next tuple: one tuple per address, in reply order
nameOne copy of the canonical name, shared by every tuple
familyAF_INET or AF_INET6, per address
addrThe address
scopeid0, so an IPv6 link-local address is returned without the interface it belongs to

7.2.3.1 The gethostbyname4_r TTL #

When ttlp is given it receives the least TTL among the addresses.

7.2.4 The forward hostent #

gethostbyname3_r, 2_r, and _r return a hostent:

FieldContent
h_nameThe reply's canonical name
h_aliasesEmpty
h_addrtypeThe af asked for
h_length4 or 16
h_addr_listEvery address, in reply order

7.2.5 The gethostbyname3_r TTL and canonical name #

When ttlp is given it receives the least TTL among the addresses, and when canonp is given it is pointed at h_name.

7.3 Reverse Lookups

Peios / Reference / resolvd / The Nss Shim

7.3.1 Loopback addresses in the shim #

An address in 127.0.0.0/8, or ::1, is answered inside the calling process without contacting resolvd: h_name is localhost, with no aliases and TTL 0.

7.3.2 Other addresses #

  • Any other address is sent as a reverse (§4.9). A found reply with no records is NOTFOUND (§7.1).
  • A found reply without a PTR record returns NOTFOUND, ENOENT, and NO_DATA. Explicit notfound returns HOST_NOT_FOUND; transient failures retain their separate results (§7.1).

7.3.3 The reverse hostent #

Otherwise the reply's PTR records are taken in order, each record's text with any trailing dots removed:

FieldContent
h_nameThe first PTR record's name
h_aliasesThe remaining PTR records' names
h_addrtypeThe af asked for
h_length4 or 16
h_addr_listThe address asked about, alone

7.3.4 The reverse TTL #

When ttlp is given it receives the least TTL among all the reply's records, PTR or not.

8.1 The resolv Command

Peios / Reference / resolvd / The Resolv Command

resolv (/usr/bin/resolv, package dev.peios.resolv) owns no state.

8.1.1 One request per verb #

Every verb but version is one request on the native socket, on one connection, and its output is a rendering of the reply.

8.1.2 Verbs #

CommandRequest
resolv statusstatus
resolv query <name> [<type>] [--no-cache]resolve
resolv lookup <name>lookup, family any
resolv reverse <address>reverse
resolv flushflush
resolv version, resolv --versionnone: prints resolv <version>

8.1.2.1 The command line #

  • --no-cache is recognized anywhere on the command line and removed before the rest is matched; it affects only query.
  • Any other argument list prints a usage line to standard error and exits 64.

8.1.2.2 Arguments checked before contacting resolvd #

  • The <type> of query is A when omitted. It is one of A, NS, CNAME, SOA, PTR, MX, TXT, AAAA, SRV or ANY, in any case, or TYPE<n> for any type number from 0 to 65 535.
  • Any other <type> prints resolv: unknown record type "<type>" and exits 1 without contacting resolvd.
  • The <address> of reverse is checked in the same way: anything that is not an IPv4 or IPv6 address prints resolv: "<address>" is not an address and exits 1 without contacting resolvd.

8.1.2.3 Bounded exchanges in resolv #

resolv uses libresolvd.so through its Rust wrapper. Each operation has a ten-second total deadline covering connection, request, and response.

8.1.3 Output #

8.1.3.1 query output #

query prints a summary line, then one line per record:

<outcome>  <source>[ via <server>][ on <interface>]  validation <validation>
<name>	<ttl>	<type>	<text>

with via present when the reply names a server and on when it names an interface, and fields on record lines separated by tabs. A line rcode <name> follows the summary when the outcome is found and the response code is not zero. resolvd answers found only with response code zero (§4.8), so against resolvd the line does not appear.

8.1.3.2 lookup output #

lookup prints <outcome> <source> canonical <name>, then <address> <ttl>, tab-separated, for each address.

8.1.3.3 reverse output #

reverse prints <outcome> <source>, then the text of every record in the answer, whatever its type.

8.1.3.4 status output #

status prints three lines:

hostname   <name, or (unset)>
netd       <connected | not connected>
cache      <n> entries

then scopes (none) when there are no scopes, or, for each scope, a blank line and

<interface>  metric <n>[  [default-route, exclusive]]
  server   <address>[  (demoted)]
  domain   <domain>
  subnet   <address/prefix>

with the bracketed flags present as they apply and one line per server, domain and subnet. When fallback servers are configured, a blank line and a fallback <servers> line follow, the servers separated by single spaces. Last come a blank line and the counters, on one line:

queries <n>  synthetic <n>  cache-hits <n>  upstream sent <n> answered <n> failed <n>  refused <n>

8.1.3.5 flush output #

flush prints nothing on success.

8.1.4 Exit status #

StatusMeaning
0found, or status, flush or version succeeded
1resolvd unreachable, a protocol failure, an error reply (including access denied), or a bad type or address argument; an unexpected reply kind is diagnosed
2notfound
3unavailable
64A command line resolv does not recognize

8.1.4.1 The unreachable message #

Errors are printed to standard error prefixed resolv: . resolvd connection or protocol failures carry the library diagnostic. Diagnostic wording is not a stable interface.

9.1 Reading resolvd's State

Peios / Reference / resolvd / Failure Modes

9.1.1 Where to look #

SignalTells you
resolv statusWhether netd is connected, the scopes in use, which servers are demoted, the fallback servers, cache size, counters (§5.3, §8.1)
resolv query <name> --no-cacheWhere a fresh answer comes from: source, server, interface, response code (§4.1)
evctl 'LOGS FROM resolvd SINCE 1h ago'Every log line (§2.1)
The exit status of resolv2 for notfound, 3 for unavailable, 1 when resolvd could not be asked (§8.1)
The door's own errorNXDOMAIN or SERVFAIL at the stub; HOST_NOT_FOUND, TRY_AGAIN, or NO_RECOVERY from getaddrinfo (§6.2, §7.1)

Two readings of the counters are worth knowing. upstream_failed rising with upstream_answered flat means no matching reply is arriving: the servers are not answering, their replies do not match (§4.8), or the transactions cannot be sent at all (§4.7), which the log shows as upstream <server>: <error> lines. Both rising together means servers answer with failure codes. refused counts rejection at the in-flight ceiling or a failure to obtain randomness for a new transaction (§4.6).

9.1.2 Log lines #

Every line resolvd writes, with the level it is written at:

LineLevelMeaning
native socket: <error>errorStartup failed at the native socket; resolvd exits (§2.2)
stub listener on 127.0.0.53:53: <error>errorStartup failed at port 53; resolvd exits (§2.2)
poll: <error>errorThe loop failed; resolvd exits (§2.2)
could not set a descriptor on <path> (<error>); …errorThe native socket is reachable only by SYSTEM and administrators (§2.4)
removed a stale /run/resolvd/resolv.sockwarnA previous instance left its socket behind and this one removed it; expected on every restart of the service (§2.4)
could not build a descriptor: <error>warnAs could not set a descriptor …, but before writing was attempted (§2.4)
registry watch unavailable (<error>); configuration is read oncewarnConfiguration changes will not be seen (§2.3)
registry watch: <error>; re-armingwarnThe watch failed and is being replaced (§2.3)
Dns FallbackServers: ignoring malformed address "<s>"warn§2.3
Dns ExtraSearchDomains: ignoring malformed domain "<s>"warn§2.3
Dns Hosts: ignoring malformed name "<s>"warn§2.3
Dns Hosts: ignoring malformed address "<s>"warn§2.3
ControlSecurity is not a valid descriptor (<error>); using the defaultwarn§2.3
readiness notify: <error>warnpeinit was not told resolvd is ready (§2.1)
netd not reachable (<error>); retryingwarnFirst failure to reach netd (§3.2)
netd refused the subscription: <message>warnnetd answered subscribe with an error (§3.1)
netd sent something unreadable: <error>warn§3.1
lost the netd channel; reconnectingwarn§3.1
upstream <server>: <error>warnA transaction could not be sent (§4.7)
control: no peer token: <error>warnA native request was denied because its token could not be read (§5.2)
control: reply failed: <error>warnA native reply could not be written (§5.1)
stub udp: <error>, stub tcp accept: <error>, native accept: <error>warnA listener read or accept failed. Accept errors pause that listener for 250 ms before retrying; other descriptors continue to be serviced
listening on /run/resolvd/resolv.sock and 127.0.0.53:53infoStartup reached readiness (§2.2)
subscribed to netdinfo§3.1
netd: <summary>infoA snapshot was applied (§3.3)
configuration changedinfoA registry change was applied (§2.3)
cache flushedinfoA flush request was carried out (§5.3)
/dev/kmsg mirror unavailable (<error>): log lines go to stdout/stderr onlywarnThe kernel log mirror could not be opened, which for resolvd is always; written once, directly after the first line logged (§2.1)

9.1.3 What a question logs #

Answering a question writes no log line, however it is answered — synthetic, from the cache, by a server, or unavailable after timeouts — and a timeout or a demotion writes none either. The only lines a single question or request can cause are upstream <server>: <error>, for a transaction that could not be sent (§4.7), and, for a native request, control: no peer token: <error> (§5.2) and control: reply failed: <error> (§5.1).

9.2 Names Do Not Resolve

Peios / Reference / resolvd / Failure Modes

9.2.1 Everything needing the network is unavailable #

Looks like: resolv query example.com exits 3; the stub answers SERVFAIL; getaddrinfo returns EAI_AGAIN. localhost, the hostname, and static names still answer.

Check resolv status:

  • netd not connected and scopes (none). resolvd has never had a snapshot. Without fallback servers nothing can be asked (§4.4). Start netd; resolvd reconnects within ten seconds of netd's socket appearing (§3.2) and the first snapshot brings the scopes.
  • Scopes listed, but none has a server. An explicit routing rule can select a serverless scope and return unavailable (§4.4). Either the profiles and leases supply no servers, or the offered addresses or explicit zones were invalid (§4.7). Correct the selected profile's servers. Fallbacks do not bypass an explicit serverless selection.
  • Servers listed and marked (demoted). Every server's last failure was less than 30 seconds ago (§4.6). upstream_failed rising shows it. Questions are still sent to demoted servers, so service returns as soon as one answers.
  • The servers listed are link-local (fe80::…). Check that the scope names the intended interface and that it still exists. resolvd sends through that interface for UDP and TCP (§4.7). Link-local servers belong in an interface profile, not the unscoped fallback list.

9.2.2 A single label is notfound at once #

Looks like: resolv query printer exits 2 without delay, with source local.

No search domain applies (§4.3). Check the domain lines in status. An up scope's domains count even without servers; while an exclusive scope takes every question (§4.4), only its domains apply and ExtraSearchDomains is ignored. A single label is never sent bare, so with no domain it is answered locally.

9.2.3 Names meant for the VPN go elsewhere #

An exclusive scope takes every question at addressed or better (§4.4), even without servers. Without a server, uncached upstream work is unavailable instead of using another interface. At link alone, the exclusive rule does not apply. Check the interface state as well as its flags.

9.2.4 An answer is wrong or stale #

Cached answers live up to a day (§4.5). They are discarded for a scope when its server list changes, and for everything by resolv flush (§5.3), which needs RESOLVER_CONTROL. A static name in Hosts\ overrides DNS at once, with no flush (§4.2).

To see what the network says now, use resolv query <name> --no-cache. It skips the cache lookup, but the answer it gets is still stored, replacing the cached one (§4.5).

9.2.5 Answers are slow #

Each question shares three attempts across candidates and TCP retries, allowing six seconds of timeout waiting (§4.6). Successful negative answers can add further round trips while advancing through search domains. A dead first server costs two seconds per question until it is demoted; after that it is asked last, for 30 seconds, and the cycle repeats if it is still dead.

A UDP reply that does not match its query — a server that does not echo the question's case exactly, for instance — is ignored (§4.8). A later matching reply can still answer the transaction. Only if none arrives by the original two-second deadline does the attempt time out, demote the server, and add to upstream_failed without adding to upstream_answered.

9.2.6 refused is rising #

The counter includes transactions rejected at the 4,096-transaction ceiling and failures to obtain randomness for a new transaction. Both return unavailable; cached and synthetic answers do not allocate a transaction. Check outstanding work and the host's random-source health before assuming that the service is overloaded. The capacity used by completed transactions is released; a new request can then proceed.

9.2.7 Getting back to a known state #

A new resolvd discards the cache, the demotions and the counters, re-reads the registry, and takes a fresh snapshot from netd; nothing is persisted. svctl restart resolvd is enough: the new process replaces the socket its predecessor left (§2.4).

The exception is the first start after an upgrade from a resolvd whose DACL did not name its own account (§2.4). That older resolvd's directory and socket shut the new one out, and it exits with native socket: Permission denied (os error 13) until they are gone. Reboot to recreate the runtime directory. If a reboot is not possible, stop the service and have an administrator inspect and replace only its stale runtime socket and directory before restarting it.

9.3 resolvd Cannot Be Reached

Peios / Reference / resolvd / Failure Modes

9.3.1 resolvd is not running #

DoorWhat a client sees
NSS shimlocalhost and loopback reverses still answer; everything else is UNAVAIL with NO_RECOVERY (§7.1)
Stub listenerNothing listens on 127.0.0.53; UDP queries go unanswered or are refused by the kernel, TCP connections are refused
resolvExit 1, resolv: resolvd is not reachable at /run/resolvd/resolv.sock: <error>

peinit restarts resolvd whenever it exits (§2.1). The new process removes the socket the old one left and binds a fresh one (§2.4), so an outage after a crash lasts only until the restart completes. If resolvd keeps exiting, the cause is one of the startup failures below.

9.3.2 resolvd will not start #

The startup failures are fatal and logged before the exit (§2.2):

  • stub listener on 127.0.0.53:53: <error>: either the port reservation for tcp,udp:53 is not in the registry — its seed is inert until the image applies it (§2.1) — or something else already holds 127.0.0.53:53. The error text says which.
  • native socket: <error>: /run/resolvd could not be created or given its mode, a stale socket file could not be removed, or the socket could not be bound or set up.

Because the restart policy is Always, a failure that persists is a restart loop: the same line in the log each time.

9.3.3 The native door is closed to ordinary programs #

Looks like: getaddrinfo fails with NO_RECOVERY for every name but localhost, for every user but SYSTEM and administrators, while programs that send DNS to 127.0.0.53 themselves work.

Two causes:

  • The socket's descriptor could not be written at startup (§2.4), and the log has the could not set a descriptor line. Ordinary programs cannot reach the socket at all.
  • ControlSecurity holds a valid descriptor that does not grant RESOLVER_QUERY to them (§5.2). They reach the socket and are denied: resolv query prints resolv: access denied. Deleting the value restores the compiled default without a restart (§2.3).

The stub listener is not governed by either, which is why direct DNS clients are unaffected.

9.4 Stalls and Loops

Peios / Reference / resolvd / Failure Modes

9.4.1 A client that does not read #

Native and stub TCP replies are written without blocking (§2.5). A client that does not read can retain its own queued reply until the fixed one-second write deadline, then its connection closes. It does not stop other lookups. Each door holds at most 256 queued replies; if full, a new reply that cannot be written immediately is closed too. Stub TCP write failures are silent; native failures log control: reply failed.

9.4.2 netd refuses the subscription #

When netd accepts the connection and answers subscribe with an error — resolvd's account lacks NETWORK_QUERY, for instance — resolvd drops the channel and retries with exponential backoff (§3.2): 0.5 seconds, then 1, 2, 4, 8, and ten seconds between attempts until a good snapshot resets the sequence. The log shows subscribed to netd, then netd refused the subscription, then lost the netd channel; reconnecting for each refusal. resolv status shows netd as not connected except in the moment between each reconnection and its refusal, and the scopes are whatever the last accepted snapshot held, or none.

9.4.3 The registry watch is lost #

When the watch cannot be armed at startup, or fails and cannot be re-armed, configuration changes are not seen (§2.3). resolv status still shows the fallback servers in use, so a change to FallbackServers that does not appear there is the sign. A restart reads the key again and re-arms the watch.

9.4.4 Cache capacity pressure #

At 8 192 entries, storing a new key removes expired entries first. If that creates room, it keeps every live entry; otherwise it replaces only the entry with the earliest expiry (§4.5). A long answer lifetime does not cause a sweep of shorter-lived answers that are still valid.

cache_entries can fall sharply when admission removes many expired entries. Expiry alone does not remove them, so reaching 8 192 does not mean 8 192 live answers. Looking up an expired key also removes it, before its replacement arrives.

Older builds compared the sweep against the incoming answer's expiry (§4.5). On those builds a day-long answer could empty a full cache of live answers, causing a burst of upstream requests.

Appendix A Constants and Limits

Peios / Reference / resolvd

The articles cited are authoritative; this appendix collects their values in one place.

A.1 Limits and timers #

BoundValueDescribed in
Native request size ceiling (payload)65 536 bytes§5.1
Maximum buffered native frame65 540 bytes§5.1
Native connection read chunk4 096 bytes§5.1
Native request delivery bound5 s§5.1
Native connections still sending a request256§5.1
Queued native replies256§2.5
Queued stub TCP replies256§2.5
Native reply write deadline1 s total§5.1
Stub TCP connections still sending a query256§6.1
Stub TCP query delivery bound10 s§6.1
Stub TCP message buffer65 537 bytes§6.1
Stub TCP read chunk4 096 bytes§6.1
Stub UDP read buffer4 096 bytes§6.1
Stub TCP reply write deadline1 s total§6.2
Classic UDP reply limit, no OPT512 bytes§6.2
EDNS0 payload size advertised (upstream and stub)1 232 bytes§4.7, §6.2
Transaction timeout2 s§4.6
Attempts per question (all candidates and transports)3§4.6
Demotion period30 s§4.6
Service descriptor limit16 384§2.1
Listener retry delay after accept error250 ms§2.5, §9.1
Upstream transactions in flight4 096§4.6
Upstream UDP read buffer4 096 bytes§4.7
Cache entries8 192§4.5
Positive lifetime cap86 400 s§4.5
Negative lifetime cap300 s§4.5
CNAME chase depth in lookup16§4.9
netd reconnect backoff0.5 s doubling to 10 s§3.2
netd subscription writeNonblocking§3.1
resolv exchange deadline10 s total§8.1
Readiness notification deadline1 s§2.1
netd frame ceiling65 536 bytes§3.1
netd channel read chunk8 192 bytes§3.1
Registry watch event buffer16 384 bytes§2.3
Kernel hostname read buffer256 bytes§3.3
Unknown-value nesting depth, native requests32§5.1
NSS shim read and write timeout10 s§7.1
DNS label63 bytes§4.1
DNS name on the wire255 bytes§4.1

A.2 Rights #

RightValueDescribed in
RESOLVER_QUERY0x00000001§5.2
RESOLVER_CONTROL0x00000002§5.2
RESOLVER_ALL_ACCESS0x000F0003§5.2

A.3 Paths, addresses, and identities #

ItemValueDescribed in
Daemon/usr/sbin/resolvd§2.1
Operator command/usr/bin/resolv§8.1
NSS shim/usr/lib/x86_64-linux-peios/libnss_peios_net.so.2§7.1
Runtime directory/run/resolvd, mode 0755§2.4
Native socket/run/resolvd/resolv.sock, mode 0666§2.4
Stub listener127.0.0.53:53 (UDP and TCP)§2.4
netd control socket/run/netd/control.sock§3.1
Upstream port53§4.7
Constant resolver configuration/usr/etc/resolv.conf§2.1
Service definition seed/usr/share/regim/resolvd-service.reg§2.1
Port reservation seed/usr/share/regim/resolvd-port.reg§2.1
Registry reference/usr/share/regman/resolvd.regman§2.1
Service SIDS-1-5-80-3864064249-1823296737-2008945602-1354971773-2894779966§2.1
Fallback scope keyfallback§4.4

Appendix B Registry Keys

Peios / Reference / resolvd

The articles cited are authoritative; this appendix collects the keys in one place.

B.1 Read by resolvd #

KeyValueTypeDefaultDescribed in
Machine\System\Network\DnsFallbackServersREG_MULTI_SZ (or one REG_SZ or REG_EXPAND_SZ)none§2.3
Machine\System\Network\DnsExtraSearchDomainsREG_MULTI_SZ (or one REG_SZ or REG_EXPAND_SZ)none§2.3
Machine\System\Network\DnsControlSecurityREG_BINARYthe compiled default of §5.2§2.3, §5.2
Machine\System\Network\Dns\Hostsany name: a static nameREG_SZ, REG_EXPAND_SZ, or REG_MULTI_SZnone§2.3, §4.2

resolvd watches Machine\System\Network and everything under it, and re-reads Machine\System\Network\Dns whole on any change (§2.3). It reads no other key.

B.2 Seeded by the package #

Both seeds are installed under /usr/share/regim/ and are inert until an image applies them (§2.1).

SeedKeyValues
resolvd-service.regMachine\System\Services\resolvdImagePath, Triggers, Identity, Readiness, RuntimeDirectories, RestartPolicy, ErrorControl, DisplayName, Description
resolvd-port.regMachine\System\Network\TcpIp\PortReservationstcp,udp:53

1 Architecture

Peios / Reference / RADIUS

The radius repository contains the portable RADIUS authentication core, the native radiusd daemon, the radius administration program, and a host-side qualification fixture. The native integration uses existing Peios services and kernel APIs; packaging and real AP qualification are separate milestones.

1.1 Responsibilities #

The core implements UDP RADIUS authentication, EAP-TTLSv0/PAP and PEAPv0/EAP-MSCHAPv2. Rustls handles TLS; ring supplies its cryptographic primitives. RADIUS uses MD5 and HMAC-MD5 only where required by its wire format, through existing cryptographic libraries.

The caller owns sockets, trusted-client selection, network mapping, configuration, identity verification, and network admission. It supplies the actual packet source and a Binding consisting of client identity, trust generation, and network identity. Asserted NAS attributes do not establish this binding.

The core has no registry, account database, OS token, or impersonation authority. The loopback-only radius-test-server is a fixture with one test identity. It is not a production backend or an installable service.

1.2 Conversation #

flowchart TD
    A[Integrity-checked request] --> B[Bound EAP and TLS conversation]
    B --> C[Inner password or source-bound MSCHAPv2 proof]
    C --> D[Credential exchange with integration]
    D --> E[Verify identity and retain full subject]
    E --> F[Check current network admission]
    F -->|Granted| G[Success and Wi-Fi key delivery]
    F -->|Denied or failed| H[Failure without keys]

An outer identity such as anonymous introduces the EAP exchange. The inner username and credential proof drive verification. The outer name grants no user authority and need not match the inner name.

Engine::receive returns a reply, a one-shot verification event or a drop. Credentials are owned by that event; its password buffer is erased on drop, and debug output is redacted. PEAP also returns a typed MSCHAPv2 response event after the source-issued challenge. The Peios adapter uses authd Authenticate and retains its verified identity, source groups and permitted claims on that same attempt. It then evaluates the network's Connect descriptor using the advisory access-check API. It then selects a complete access profile through PNP's shared tree machinery. Profile selection cannot bypass the Connect check or accounting allowances. See Access Assignment.

Only an explicit Engine::finish admission result can deliver success and keys. It rechecks the deadline, source/client/network binding, and shared secret. A changed trust definition requires a fresh exchange. The current policy generation accompanies completion, keeping the reply cache consistent with the decision actually made. The caller is trusted to evaluate that current policy; a generation number is not proof of a grant.

The core does not perform a later username lookup to reconstruct a subject. Backend failure and insufficient identity context do not grant network access. The protocol core receives the admission outcome and does not depend on authd, registry or KACS types.

1.3 Protocol and TLS scope #

Every request requires a valid Message-Authenticator. Malformed and unauthenticated datagrams are discarded without replies. Reply integrity includes both the Message-Authenticator and Response Authenticator. The original authenticated request determines key wrapping for its reply.

TTLSv0/PAP supports both TLS 1.2 and TLS 1.3, with version-specific key derivation. TLS 1.2 uses the TTLS exporter label without context; TLS 1.3 uses the EAP key-material exporter with the TTLS type as context. Both request 128 bytes before splitting the result.

PEAPv0/EAP-MSCHAPv2 uses TLS 1.2 in this initial compatibility slice, with the client EAP encryption exporter label. The core relays a source-issued challenge and the client's response, without receiving the password or reusable NT hash. It sends the exchange-specific server proof only after authentication and admission succeed. Final success and Wi-Fi key delivery wait for the MSCHAPv2 success acknowledgment and the tunneled Result TLV acknowledgment, followed by another current network-admission check. Cryptographic credential checking belongs to authd's principal source. PEAP cryptobinding extensions and TLS 1.3 for PEAP are not implemented in this slice.

Each network has an ordered allowed-method list. Negotiation can select an allowed, untried alternative before TLS begins; a credential failure does not cause method fallback. Named authentication profiles explicitly choose the allowed methods and their order. EAP-TLS and method-specific admission rules remain future work.

Full authentication is required each time. Session storage, ticket resumption, and early data are disabled. Ordinary TLS server defaults are therefore unsuitable without the core's explicit configuration. No client certificate is required, but the client validates the server's certificate chain and expected identity before disclosing credentials.

Proxy-State, direct outer password methods, additional EAP methods, and application SSO are outside this slice.

The separate accounting crate owns durable session reports and allowances; see Accounting.

1.4 Resource and retransmission bounds #

ResourceDefault or bound
RADIUS declared packet lengthAt most 4096 bytes
Reassembled TLS messageAt most 65536 bytes
Buffered inner AVPsAt most 4096 bytes
Inner username1 to 253 bytes
Inner password before padding removalAt most 1024 bytes
Configured shared secret16 to 1024 bytes
Idle conversation timeout30 seconds
Overall conversation deadlineTwo minutes
Active conversations256 globally; 32 per client
Cached replies1024 for 15 seconds
Outgoing TLS fragment payload1000 bytes

The caller supplies monotonic time and periodically calls expire, including while no packets arrive. Pending backend work shares the same conversation deadlines. update_limits changes future attempts' limits without moving existing deadlines. Lower allocation limits prevent new allocations without evicting current attempts.

Exact retransmissions receive cached bytes. The cache includes the authenticated packet contents, source endpoint, trusted binding and policy generation for terminal decisions. Challenges grant no access and can be replayed across policy edits while their trusted binding matches. An in-progress verification is not restarted by a duplicate packet. A changed packet is not mistaken for a cached request.

These records last through sign-in, not through an hours-long Wi-Fi connection. Already admitted connection lifetime and periodic reauthentication belong to the AP. Successful native admissions request reauthentication with Session-Timeout and Termination-Action, defaulting to one hour. Actual AP/client enforcement still requires qualification.

1.5 References #

  • RADIUS.
  • RADIUS support for EAP.
  • EAP-TTLS.
  • TLS-based EAP methods with TLS 1.3.
  • Microsoft key attributes.

2 Qualification

Peios / Reference / RADIUS

The interoperability gate tests the protocol core against an independent OpenSSL-backed supplicant over loopback. It checks the encrypted exchange and actual exported Wi-Fi key agreement independently of Peios services.

2.1 Running the gate #

From the repository root, build the fixture and test tool:

cargo build --workspace --locked
python3 tools/build-eapol-test.py --out target/test-tools/eapol_test

The tool builder requires a C compiler, Make, OpenSSL development files and network access to the pinned upstream archive. It builds only the test executable and removes its temporary source tree. An existing qualified eapol_test can be supplied instead.

Run the required gate:

python3 tests/interop.py --server target/debug/radius-test-server --eapol-test target/test-tools/eapol_test

The runner fails if required tools are missing. Successful cases check both EAP success and MPPE key agreement. It forces TLS 1.2 and TLS 1.3 separately, uses a large certificate chain and small fragments, checks anonymous and differing outer names, and rejects wrong credentials, denied admission, untrusted issuers and wrong server names. A loopback relay duplicates requests and suppresses a reply. Direct packet checks also verify reply authenticators and discard tampered requests.

The fixture listener rejects non-loopback addresses. Temporary test credentials and certificates are removed on completion; captured supplicant output is not printed because it can contain key material. The fixture uses explicit test credentials and never contacts authd.

2.2 Component checks #

pekit test --strict -j 2 unit integration management policy authorization accounting clippy doctests
pekit build --strict -j 2 test_server radiusd radius_cli radius
pekit test --strict -j 2 native native_management administration native_clippy native_management_clippy administration_clippy

These are raw component targets. They do not package files or build a kernel or image. radius_cli builds terminal administration with native support; radius also includes the GXWI window. The native targets supply matching pinned SDK, authentication and desktop libraries. Cargo and Pekit must select the same source revision for each imported component; do not bypass a reported mismatch. Before dependency commits are published, local qualification needs those exact commits in the build cache.

The host Cargo equivalents are documented in the repository README. Native host tests do not replace guest qualification: tests marked as requiring a disposable Peios guest remain ignored on the host. The Rust checks exercise malformed and truncated packets, duplicate attributes, conversation quotas, idle and overall deadlines, binding changes, one-shot admission and rejection without key delivery.

The authorization target checks typed settings, independent standard and vendor wire vectors, exact unit conversion, protected attributes, reset requirements and complete reply bounds. Native coordinator and loopback CoA checks cover complete assignments, cache integrity, quota gating, real UDP requests and acknowledged baselines. These establish server behavior; actual equipment needs separate shaping, filter, gateway, and management tests.

2.3 Native session controls #

In a fresh, isolated guest, run tests/native/setup.sh, then tests/native/session-controls.sh and tests/native/automatic-controls.sh. Supply the compiled native-session-controls example, the native-policy test binary, and the independent supplicant in /mnt/dev/bin, with the fixture credentials under /mnt/dev/credentials. These scripts require PEIOS_DISPOSABLE_RADIUS_TEST=yes and RADIUS_DEV_RUNTIME=1. They change accounts, policy, service definitions, and the ledger; use no deployed state or LAN interface.

The checks exercise actual caller tokens, separate action and fallback permissions, protected credential metadata, password revision changes, maintenance stability, exact-session CoA and Disconnect, forged replies, durable request IDs, restart, rebuild, and real PEAP/TTLS authentication. Automatic cases use direct Registry VLAN edits, account disablement, password replacement with an explicit Disconnect fallback, and opt-in CoA updates. The generic profile does not claim fresh reauthentication support.

tests/native/richer-profiles.sh checks saved setting types, equipment mapping, Explain, exact 64-bit values, unsupported ranges, invalid direct Registry edits, removal, restart, TLS 1.2/1.3 authentication, key agreement, and actual-caller permission checks. Run it after setup.sh in an isolated guest, or after the session-control scripts to include the accounting ledger. It qualifies server behavior with a loopback supplicant; no fixture emulates traffic shaping or gateway enforcement.

A migration fixture can seed accounts with a previously qualified format-6 lpsd before switching to the new runtime. Set RADIUS_QUALIFY_LEGACY_STORE=1 only for that arrangement. Fresh-store checks do not exercise the old-store upgrade.

2.4 Component load and recovery #

The developer-only qualification program measures bounded synthetic loads, checks overload recovery, and injects storage failures in child processes. See Component Load and Recovery for commands, measurements, and the incomplete instrumented fuzzing gate.

2.5 Limits of the evidence #

Passing this gate establishes host-side protocol behavior for the tested tool and cases. Native qualification is described in Native Integration. Neither gate establishes real AP reauthentication or device onboarding. Those require actual equipment. A passing suite is not a complete security audit.

3 Native Integration

Peios / Reference / RADIUS

radiusd is the native adapter around the portable protocol core. It runs as its own Identity=Service account, verifies passwords through authd, and checks the current network's Connect security descriptor. It creates no user token or local logon session.

3.1 Build and service identity #

Build the raw executable, without packaging or rebuilding the kernel:

pekit build --strict -j 2 radiusd radius_cli radius

radius_cli includes native terminal administration; radius includes the same commands and the optional GXWI window. These raw component targets do not invoke final PPK packaging in pkgs/.

The native Cargo feature links the matching public libauth.so.1 and libpeios.so.0. The Pekit target supplies those libraries and SDK headers from pinned canonical source revisions. A development guest must load these matching libraries rather than older image copies.

The daemon, command-line client and GXWI window use one Peios Rust bindings 0.5 dependency graph, aligned with the distribution's SDK and service pins. Build these clients with their pinned dependencies and matching libraries.

Fresh state-directory provisioning requires a kernel with KACS control handles: native opens that request no data rights. The administrator creates each directory carrying its security descriptor. Older kernels reject this open with EINVAL; provisioning does not fall back to creating an unprotected directory and setting its descriptor afterward. Existing directories keep their descriptors.

The current bindings require authd's PGSS version 6 protocol and libauth ABI 6. The shared-library filename remains libauth.so.1, so successful loader resolution alone does not establish compatibility; the bindings check the ABI when creating a client. Upgrade the daemon, matching library, peinit service-token client, and other authentication clients together. An older GXWI server or SSH bridge cannot authenticate against the new authd merely because radiusd has been rebuilt. RADIUS continues to request only password or MSCHAPv2 verification; this update adds no NTLM method.

The service must be named radiusd and use Identity=Service. It checks its actual token user SID at startup. Trusted authd policy gives this account the peios.auth.authenticate capability. It receives no peios.auth.logon capability and needs no token-creation or impersonation privileges. SeChangeNotifyPrivilege permits ordinary path traversal; SeAuditPrivilege permits operational event emission. The normal UDP port-reservation descriptor grants its service SID PORT_BIND for each configured listening port. Use peinit's Notify readiness mode.

The radius package provides these as Registry seeds, in registry.d: radiusd-service.reg defines the service, radiusd-policy.reg grants its account the capability and the two privileges, and radiusd-port.reg reserves UDP ports 1812 and 1813 for it. The definition has no Triggers, so installing the package starts nothing. radius service boot on adds a boot trigger once the configuration is initialized.

Packet admission is separate from the port reservation. When packet filtering is enabled, allow inbound UDP for each configured RADIUS listener. GXWI's inbound TCP rule does not also admit RADIUS authentication traffic.

The default AuthenticationSecurity descriptor grants this service ReadGroups and ReadClaim across the namespace. Authenticate remains a separate capability grant. Administrators can use ordinary claim object ACEs to restrict sensitive claims. An explicit AuthenticationSecurity value replaces the default and is never silently broadened.

3.2 Configuration and admission #

The component's radiusd.regman describes every value under Machine\Software\Radius. Settings define literal UDP listeners and bounded conversation resources. Clients define source-address prefixes, protected secret-file references, and allowed access-policy GUIDs. Access policies define exact SSIDs, Connect security descriptors, periodic reauthentication, and an authentication-profile reference. Profiles select ordered methods and a named server identity. Server identities reference an ordered DER certificate chain and matching protected DER private key. All records have stable GUID keys and independent display names. Schema version 3 adds access profiles and nested assignment rules. Existing schema 2 deployments require the explicit migration described in Administration.

Most-specific source prefixes select the trusted client. There is no fallback to another secret. The integrity-checked Called-Station-Id must contain a valid MAC prefix and exact SSID; NAS identifiers and MAC addresses do not establish user identity. Continuations retain their original client, source, and network binding. A changed secret, source trust definition, SSID, or listener set invalidates affected work.

Each profile's required AuthenticationMethods is an ordered allowed-method list containing ttls-pap, peap-mschapv2, or both. All methods share the access policy's Connect descriptor. Changing a method list invalidates affected unfinished exchanges and cached replies. Enabling NT storage does not change the configured methods.

An intentionally disabled client, policy, or profile denies affected admissions without falling back to other clients or profiles. Otherwise valid disabled records do not invalidate unrelated policy. These changes do not disconnect established stations immediately. Missing references remain invalid even on disabled records.

One nonblocking authd operation belongs to each credential attempt. PAP uses one typed Password prompt and requires confirmed Password verification. PEAP requests MSCHAPv2, relays one source-issued challenge and typed response, and requires confirmed MSCHAPv2 verification with the protocol's server proof. radiusd receives no reusable NT hash. Unsupported or repeated prompts, unavailable sources, and incomplete verification cannot grant access. A configurable concurrency limit rejects excess verification work without an unbounded queue. NT storage and opportunistic password-side backfilling are documented with the local principal source, not configured by radiusd.

Admission uses the verified SID, source groups, permitted typed claims, and explicit claim coverage. It does not reconstruct identity from a later username lookup or invent local-session group memberships. For example, grant Connect to a source's household group SID. An Everyone ACE matches only when that membership is supplied; the adapter does not add it. Hidden claims remain unknown. Missing context, device, or local execution requirements deny admission. The stateless kernel query conveys no token authority. An older kernel fails admission with kernel-api-unavailable; other query errors use access-check-error, independently of wrong credentials and an ordinary policy denial. There is no userspace evaluator fallback.

Each check supplies the stable Registry network ID and SSID display label in an AuditContext of kind network. Invalid UTF-8 in the label is replaced with U+FFFD; policy binding still uses the original SSID bytes. The fields are defined as asserted values in radiusd's event catalog fragment. Matching SACL audit ACEs produce kacs.audit.subject.checked when radiusd holds enabled SeAuditPrivilege. The event identifies radiusd's real caller identity separately from the supplied, hypothetical user SID. Audit preparation errors fail admission. radiusd's own admission events remain separate and describe the real service decision.

Current policy is checked immediately before success and key delivery. Access-Accept carries signed Session-Timeout and Termination-Action attributes. The default requests reauthentication after one hour. It does not immediately disconnect existing Wi-Fi stations, and AP enforcement must be qualified separately.

3.3 Reload and reporting #

A bounded worker handles blocking Registry and protected-file reads. The packet loop continues processing bounded handshakes and expiry. Observed pending, invalid, unreadable, or unwatched configuration pauses new admissions and cached success replies. Pending verification results can wait only within their original deadlines. Recovery validates the assembled configuration before resuming. Certificate replacement cancels affected unfinished exchanges and cached replies. Cosmetic name changes preserve authentication bindings.

Notify readiness means the local status endpoint is ready. An invalid initial configuration leaves that endpoint available for diagnosis and repair while authentication is paused. It does not imply active listeners. The administration program shows saved and effective configuration separately; it also distinguishes a stopped service from an unreachable or unauthorized status endpoint. See Administration.

The loader copies Registry configuration through one short read-only transaction, including key resolution, enumeration, values, and layer selection. It releases the snapshot before opening credential files. Capture races discard the complete candidate and retry a fresh read within a 250 ms retry budget. That budget limits additional attempts; it does not interrupt a Registry call already in progress. Other read errors return immediately. If capture still fails, the worker retries on its normal reload cycle and keeps admission paused while configuration is invalid. Writes are not retried by this read helper. Watches and fingerprints detect changes but do not establish read consistency. Prepare protected immutable credential files, then transactionally switch references. Keep old files until safely unused; a Registry transaction does not snapshot filesystem contents.

radiusd.evman defines operational exchange and configuration events. The inner supplied username is explicitly unverified input; canonical name and SID appear only after verification. Events contain no passwords, AP secrets, private keys, or full claim values. Exact retransmissions do not repeat outcomes. Invalid datagrams are counted in bounded, rate-limited diagnostics. Event emission failure is reported without changing a valid admission; successful emission does not prove durable collection. These events do not replace kernel SACL auditing.

3.4 Disposable guest qualification #

The scripts under tests/native alter accounts, service definitions, machine authentication policy, and a port table. Run them only in a fresh disposable guest, with PEIOS_DISPOSABLE_RADIUS_TEST=yes. They must never run on a developer's normal system.

Use an existing console image and raw component binaries. Mount a read-only development share as /mnt/dev, using the guest's supported 9p synthetic ephemeral policy. Copy the matching raw peinit2, svctl, authd, lpsd, lps, radiusd, libpeios, and libauth into /lcl. Start the raw peinit2 as PID 1 from an initial shell. Set service library search paths explicitly: peinit constructs service environments rather than inheriting the launching shell's environment.

The share contains native with the qualification shell scripts; bin with the independent eapol_test and matching OpenSSL runtime dependencies; and credentials with generated root.pem, server.der, intermediate.der, key.der, secret, and rotated-secret files. The existing interoperability certificate helper creates suitable development-only certificates. Secrets are development fixtures, never production credentials. For PEAP qualification, enable EAP-PEAP and EAP-MSCHAPV2 in the independent supplicant. The supplied builder enables both. An OpenSSL 3 build can also need its matching legacy provider for the supplicant's MD4 operation; place legacy.so beside the test executable. radiusd does not use that provider.

export PEIOS_DISPOSABLE_RADIUS_TEST=yes
bash /mnt/dev/native/setup.sh
bash /mnt/dev/native/qualify.sh
bash /mnt/dev/native/mschapv2.sh
bash /mnt/dev/native/administration.sh
bash /mnt/dev/native/initialize.sh
bash /mnt/dev/native/assignment.sh
bash /mnt/dev/native/migrate-policy.sh

The independent supplicant runs inside the guest against loopback UDP. The native service identity, Registry, authd/lpsd verification, supplied subject admission, and key export are real. Wi-Fi equipment and its radio link are simulated. The scripts check both TLS versions, matching MPPE keys, account and policy denials, restricted-claim uncertainty, invalid-configuration recovery, secret rotation, and source failure. They capture supplicant output privately because it can contain keys. The MSCHAPv2 sequence also checks method negotiation, both NT controls, opportunistic backfilling, password changes, and password eligibility. Administration qualification additionally requires bin/radius, matching libgxwi.so.1, and the native-authority example in the development share. It checks shared profiles, references, renames, disabled isolation, invalid startup recovery, credential staging, stopped-daemon edits, and real-token status, Registry, and secret-file authorization. Certificate import checks also need the corresponding PEM chain and private key in the fixture share. The initialization script temporarily replaces and restores the disposable fixture's Registry subtree and credential directory. It verifies fresh setup, existing-configuration refusal, and enabled-administrator writes without granting the test token extra privileges. Set RADIUS_DEV_RUNTIME=1 when using the replaceable raw-binary layout at /lcl/radius-dev/current rather than copying binaries into /lcl.

The optional native-events Cargo example reads the two fixture CPU rings as the guest administrator. Start it before qualify.sh, wait for /run/radiusd/events.ready, and create /run/radiusd/qualification.done afterward. Its zero exit status and PASS marker verify typed, cataloged payload fields and absence of unexpected credential or claim fields. It is a qualification tool, not part of the daemon or a required service privilege.

Portable coordinator tests separately cover concurrent verification bounds, exact replay, policy changes, preserved deadlines, binding invalidation, and cancellation. Native SDK tests cover typed claims, known absence, and missing device or audit context.

3.5 Diagnostic reader qualification #

Stage eventd and evctl in the replaceable runtime, plus the native-diagnostics Cargo example in the share's bin directory. In a fresh disposable guest, tests/native/diagnostics.sh provisions the fixture and checks actual attempt history, exact authd operation links, caller identity, delegated event reads, and denial of personal fields. It also checks that authentication continues through an eventd outage and tight emission bounds.

The script defaults to eventd's Service identity. The explicit override RADIUS_DIAGNOSTICS_EVENTD_IDENTITY=SYSTEM isolates query checks when normal service ingestion is unavailable. A pass with that override does not qualify the Service deployment. The fixture must not be applied to a deployed machine.

The CLI and GXWI require a working, separately provisioned eventd deployment for diagnostic history. RADIUS authentication remains independent of it.

Passing these checks is development evidence, not a production release or a complete security audit. Real UniFi/iPhone TTLS/PAP connectivity and a profile-free iPhone join through PEAP have succeeded in development trials. Roaming and AP reauthentication enforcement need their own qualification. The supplied-subject evaluator runs in the kernel; the loader uses the public Registry read-snapshot API before further feature expansion.

4 Persistent Development VM

Peios / Reference / RADIUS

The helper under tools/dev-vm runs a virtual machine (VM) with persistent machine state. Raw component binaries remain separately replaceable. The helper runs no package or kernel builds. Offline boot is the default; optional LAN boot attaches a temporary network interface to an existing host bridge.

4.1 Boot and storage #

vm.py prepare extracts the kernel and initramfs from an existing console ISO. It appends a development hook to the initramfs; the source ISO stays unchanged. The image must provide the version-2 rootfs-ready hook sequence and the ordinary live-root strategy.

The extra hook mounts a read-only development share. Before starting peinit, the bootstrap mounts the required ext4 state disk and binds its directories onto /var/state and /lcl/etc. The registry hives, local account store, random seed, machine ID, certificates, secrets, and local policy therefore survive shutdown. /run remains temporary.

Disk creation and first machine initialization are separate explicit operations. Normal boots never format or seed a disk. Missing, unreadable, uninitialized, or incomplete required state stops startup before the registry starts. Bootstrap failure leaves PID 1 waiting with a diagnostic; it does not start another machine identity.

The host helper serializes runs of one VM and checks the prepared boot assets. Keep the VM directory private: its state image contains credential material. Back up the image only after a clean shutdown.

4.2 Preparing a VM #

The host needs Python 3.11 or later, QEMU, xorriso, mtools, GNU objcopy, zstd, cpio, and ext4 filesystem tools. The console image supplies the guest shell, mount tools, security-descriptor seeder, and registry service. QEMU uses two CPUs and 1536 MiB of memory, with hardware acceleration when available and software emulation otherwise.

From the workspace root, prepare the existing console image:

python3 radius/tools/dev-vm/vm.py --vm local/radius-dev-vm \
    prepare local/isos/console.iso
python3 radius/tools/dev-vm/vm.py --vm local/radius-dev-vm create-state

Disk creation exclusively creates a 512 MiB sparse file and refuses an existing file. Boot preparation also refuses existing boot assets.

Build raw targets directly in their component repositories. Assemble the reported outputs into a directory with these entries:

EntriesRaw targets
bin/peinit2, bin/svctlpeinit: peinit2 svctl
bin/authd, bin/lpsd, bin/lpsauthd: authd lpsd lps
bin/radiusdradius: radiusd
lib/libauth.so.1authd: libauth
lib/libpeios.so.0peios-sdk: libpeios

Administration development adds bin/radius and lib/libgxwi.so.1, built from the RADIUS radius target and GXWI libgxwi target. Stage both together; partial administration sets are rejected before publication. The window also needs a running GXWI desktop; the CLI does not.

For a complete desktop, build gxwi-server as the static musl target specified by GXWI's build.gcsl. Its restricted token cannot open a dynamic loader or arbitrary shared libraries. Build the other desktop programs using their component recipes. Install libgxwi.so.1 in the guest's ordinary library search path as well as supplying it to development services. A user session has no service-specific LD_LIBRARY_PATH; a wrapper around RADIUS alone does not make the taskbar and launcher load successfully.

LAN development adds bin/netd, bin/net, and lib/libnetd.so.1, built with netd's raw netd, net, and libnetd targets. Stage all three together. Partial network sets are rejected before publication. Once a VM has a saved network attachment, every boot requires these files, including offline boots, because its service definition persists.

Use matching SDK and authd revisions. The helper checks complete files, checksums, and guest loader dependencies; those checks do not prove ABI compatibility. Build-cache warnings about mismatched imported source revisions require investigation before selecting the outputs.

For an assembled directory at local/radius-runtime, stage and boot it:

python3 radius/tools/dev-vm/vm.py --vm local/radius-dev-vm \
    stage initial local/radius-runtime
python3 radius/tools/dev-vm/vm.py --vm local/radius-dev-vm \
    run initial --initialize

Use run initial without --initialize on subsequent boots. Successful startup reports that persistent state is mounted, followed by peinit's ordinary boot messages and the console shell.

4.3 Updating development binaries #

Stage every update under a different set name. Staging copies every required files before publishing the set and does not alter the running VM. Existing set names cannot be overwritten.

For a configured development VM, activate a staged set from its console:

bash /mnt/dev/activate.sh update-name

Activation copies and verifies the set before stopping services. It stops radiusd if active, then lpsd and authd, and netd if active. It switches the selected set, restarts netd if needed, starts lpsd and its authd dependency, and restarts radiusd if it was active. A set that omits network binaries cannot replace a running netd. Service definitions must use /lcl/radius-dev/current/bin and explicitly select /lcl/radius-dev/current/lib for library loading. Running PID 1 changes only on the next boot. Select the desired set in the next host run command; runtime activation does not change the host boot selection.

A missing or damaged staged set leaves running services untouched. A failure after services stop remains visible and requires correction or activation of the previous set; activation promises no automatic rollback. Old sets remain available until deliberately removed while the VM is off.

4.4 Qualifying the desktop #

Successful sign-in and a desktop document do not establish that the shell and management window work. With RADIUS open on Overview, run this additional check from the host:

python3 radius/tools/dev-vm/check-desktop.py https://10.10.0.111:7780 \
    --certificate-sha256 "$GXWI_CERT_SHA256" \
    --administrator-file local/radius-administrator.json \
    --unprivileged-file local/radius-user.json

Supply the actual development VM address and its certificate's SHA-256 fingerprint, obtained from its console. Each private JSON file contains username and password fields. Keep these files outside the repository and restrict their permissions. The check pins the server certificate before sending credentials; it never prints passwords, session cookies, or app-origin secrets.

The check signs in as both accounts and uses the desktop's HTTP and WebSocket protocols to verify a shell-owned taskbar panel, launcher overlay and declared RADIUS window. It reads the app's rendered Overview: the administrator must see Running and active saved configuration, while the non-administrator must be denied configuration and status access. Both accounts need permission to sign in through GXWI. This does not change configuration or group membership. It can start or rejoin those users' desktop sessions; close them through the ordinary desktop controls after qualification.

This protocol check does not verify browser layout, input or accessibility. Inspect those separately in a browser. It also does not replace independent supplicant tests or the real AP assignment and reauthentication trial.

Shut down through the matching control tool:

LD_LIBRARY_PATH=/lcl/radius-dev/current/lib \
    /lcl/radius-dev/current/bin/svctl shutdown poweroff

4.5 LAN attachment #

LAN mode requires a separately configured persistent Ethernet bridge on the host, NetworkManager, and permission to control network connections. The launcher never moves the host's physical Ethernet configuration. Preparing or changing the bridge is a separate administrative action; preserve the host's addressing identity and prepare a rollback before activating that change.

Save a stable virtual MAC address and the bridge/TAP names once:

python3 radius/tools/dev-vm/vm.py --vm local/radius-dev-vm \
    configure-lan --bridge br-peios

This command writes network.json beside the state image. It refuses an existing file, so ordinary setup cannot replace the virtual MAC. The configuration belongs to this VM and should accompany its state disk.

Configure the guest's radius-dev-lan netd profile and a matching interface rule through the ordinary network registry settings. Static addressing requires the address/prefix, gateway, and DNS settings; it does not require a DHCP reservation. Do not copy addresses from another network into this profile.

Stage a complete runtime set containing the network programs and library. Boot it offline first to provision the service:

python3 radius/tools/dev-vm/vm.py --vm local/radius-dev-vm run lan-initial

In the guest, apply the prepared profile and rule, then run:

bash /mnt/dev/provision-network.sh

The provisioning helper creates the persistent netd state directory if absent and configures the ordinary SYSTEM netd service using the raw executable. It preserves existing network profiles and rules. An existing netd definition retains its unrelated settings. The service starts at boot and publishes network readiness through its normal control APIs.

For a VM prepared by an earlier helper version, copy the updated activate.sh and provision-network.sh into its host share directory before provisioning. No initramfs or kernel rebuild is required.

After a clean shutdown, boot with the LAN attachment:

python3 radius/tools/dev-vm/vm.py --vm local/radius-dev-vm \
    run lan-initial --lan

The launcher creates a temporary NetworkManager TAP profile owned by the invoking user and connects it to the configured bridge. QEMU uses that TAP and the saved virtual MAC. Existing TAP names are rejected. Shutdown or a failed QEMU launch removes the temporary profile and device while leaving the host bridge in place. The profile is not saved to disk.

Check net status in the guest for the matched profile, saved address, gateway, and routed readiness. Check reachability from another LAN machine. Routed readiness reports configured state; it does not prove that the gateway or a remote service answers. The host must remain connected after the VM shuts down and its TAP disappears.

LAN attachment does not expand radiusd's trusted-client configuration or replace the offline fixture's deny-all network policy. Real AP clients, certificates, and network admission require separate provisioning.

4.6 Offline qualification fixture #

tests/dev-vm/prepare.py prepares inputs from authd's standard policy seeds and the existing protocol-test certificate helper. Run it only for a fresh offline VM. The guest fixture refuses an existing account store or authentication policy and creates a development account, group, registry marker, and loopback-only radiusd configuration. It supplies fixed test credentials and a Connect descriptor that denies all access. It is not real-network provisioning.

python3 radius/tests/dev-vm/prepare.py \
    --vm local/radius-dev-vm --authd authd

In the freshly initialized guest:

PEIOS_OFFLINE_VM_PROOF=yes bash /mnt/dev/proof-setup.sh
PEIOS_OFFLINE_VM_PROOF=yes bash /mnt/dev/proof-check.sh save

After binary activation and again after a clean shutdown and normal boot:

PEIOS_OFFLINE_VM_PROOF=yes bash /mnt/dev/proof-check.sh check

The check requires all three services active and compares the machine ID, account domain and security identifiers, groups, configuration, policy, and hashes of the account store and protected credentials. Its PASS marker establishes offline persistence and activation, not a real Wi-Fi connection. Certificate onboarding, a LAN address, UniFi integration, and production credentials require separate provisioning and qualification.

5 Administration

Peios / Reference / RADIUS

The radius program provides terminal administration and a GXWI window:

radius --window

Both interfaces use the same management library and the caller's actual permissions. Configuration is stored directly in the local Registry, so editing works while radiusd is stopped. The daemon's local status endpoint is read-only. There is no remote management listener. Use an SSH session for a remote CLI; a GXWI desktop can present the window remotely.

5.1 Configuration objects #

The window groups authentication, assignment, and accounting administration into separate sections. Overview reports service and configuration activation state.

Overview's listener field starts with the saved addresses. Background refreshes follow external changes while the field is unchanged, preserving an edit in progress. The saved value shown below the field remains separate from the draft.

ObjectPurpose
ClientSource addresses, shared secret, and allowed policies
Access policyExact SSID, Connect permissions, profile, and reauthentication
Authentication profileOrdered allowed methods and server identity
Server identityNamed certificate chain and matching private key
Access profileComplete assignment settings, including an optional VLAN
Assignment rulePolicy-owned conditions, action, priority, and exceptions
Session control profileReusable device capabilities for Disconnect and CoA

Objects have immutable GUIDs. Names are editable labels and can be duplicated; an ambiguous CLI name requires a GUID. References always use GUIDs. Renaming preserves references. Deleting and recreating an object creates a new GUID. Management refuses deletion while another object refers to the target and shows its dependents. It never cascades deletion.

Use these commands to inspect the current objects:

radius status
radius client list
radius policy list
radius profile list
radius identity list
radius access-profile list
radius rule list
radius dynamic-profile list
radius config check

radius --help lists commands. --json produces structured output, including GUIDs and typed errors. Exit status is 0 for success, 64 for invalid arguments, 3 for denied permission, 4 for a missing object, 5 for invalid configuration, and 1 for other failures. Explicit secret output is raw bytes and does not accept --json.

See Access Assignment for profile selection, rule editing, explicit defaults and hypothetical policy explanations.

The Accounting section exposes exact-session Disconnect, fresh reauthentication, authorization updates, and command history. Each action has an independent Accounting security descriptor right; configuration-write access alone does not grant control of established sessions. See Session Controls for activation, device capabilities, fallback permissions, and outcome interpretation.

5.2 Initial setup #

radius config init initializes an absent configuration with schema version 2, empty object collections, and a UDP listener at 0.0.0.0:1812. It refuses an existing deployment. The empty configuration admits nobody. The radius package defines the radiusd service, grants its identity the authd capability, and reserves UDP ports 1812 and 1813 for it, as described in Native Integration. The service starts at no time until you turn it on with radius service boot on, then radius service start.

Create a server identity first, then a profile, policy, and client. In the window, reference pickers show object names and retain their GUIDs. CLI references use the GUID returned by a create or list command. For example:

radius identity create Main \
    --set CertificateFiles=/path/server.pem,/path/intermediate.pem \
    --set PrivateKeyFile=/path/server.key
radius profile create Passwords \
    --set AuthenticationMethods=peap-mschapv2,ttls-pap \
    --set ServerIdentity=IDENTITY-GUID
radius policy create Household --set SSID=Home \
    --set AuthenticationProfile=PROFILE-GUID \
    --set 'ConnectSecurity=O:SYG:SYD:(A;;0x1;;;HOUSEHOLD-GROUP-SID)'
radius client create AccessPoints --set Addresses=10.10.0.0/16 \
    --set Policies=POLICY-GUID

Replace the placeholder GUIDs and group SID with actual values. Source addresses must be canonical literal addresses or prefixes. The first authentication method is preferred. Credential rejection does not cause fallback to another method. PEAP/MSCHAPv2 requires matching authd credential support; enabling it in a profile does not change authd's password policy.

The client receives a generated 48-character shared secret. Explicitly reveal it and configure the same value on the corresponding RADIUS client:

radius client secret AccessPoints show

The window similarly requires an explicit reveal. Normal lists, records, status, and errors contain no secret contents. Reveal still requires read permission on the protected file. Supply your own secret using an echo-free prompt, standard input, or a file; avoid placing secrets in process arguments:

radius client secret AccessPoints set
radius client secret AccessPoints set --file /protected/shared-secret
radius client secret AccessPoints generate

A generated replacement also needs updating on the corresponding client. The policy's reauthentication interval defaults to 3600 seconds.

5.3 Permissions and credentials #

Connect permissions decide whether an authenticated subject can use a policy. Management permissions are the ordinary Registry key descriptor controlling who can edit it. The window opens the existing security descriptor editor for each, under separate controls. The CLI exposes their descriptors without a separate permission language:

radius policy permissions Household connect
radius policy permissions Household management

Add an SDDL argument to set a descriptor. Configuration-write rights, credential-file read rights, service-control rights, and local-status query rights remain independent. The default status descriptor permits SYSTEM and Administrators. An explicit Settings\StatusSecurity can change that policy; malformed or unreadable explicit values deny queries. The endpoint checks the kernel-attested peer token, including deny-only groups.

Certificate import accepts PEM or DER and verifies that the key matches the leaf certificate. The window shows certificate subject, issuer, DNS names, validity dates, and fingerprint. Import paths refer to files on the Peios machine, including when the window is presented remotely. The program does not issue certificates or replace a CA. Replacing an identity preserves its GUID and dependent profile references:

radius identity inspect Main
radius identity import Main --set CertificateFiles=/path/new-chain.pem \
    --set PrivateKeyFile=/path/new-key.pem

Shared secrets and keys are staged as new protected files before Registry references switch in a transaction. Failed saves remove their new files. Successful replacement retains old files until they can safely be removed; deleting a record does not erase credential files automatically.

5.4 Saving, activation, and recovery #

Saving updates stored configuration. It does not claim the daemon activated it. Overview shows saved and effective fingerprints and activation issues. The daemon independently validates direct Registry edits. A broken reference, bad descriptor, or unreadable credential pauses admissions until repaired; the old policy is not silently kept active. The local status endpoint remains available even when initial configuration is invalid.

The tools preserve malformed records for inspection and repair. Direct Registry editing can bypass deletion safeguards. Related management writes are transactional; there is no stale-form conflict detection.

Disabled clients, policies, and profiles deny affected admissions while unrelated valid policy continues. A disabled shared profile affects every policy using it; the window shows those dependents before confirmation. Established stations are not immediately disconnected by these edits.

Service controls are separate from object state:

radius service stop
radius service start
radius service restart
radius service boot on
radius service boot off

Commands report submission; check status for completion. Boot preference does not start or stop the current process. Stop and restart interrupt ongoing authentication; existing network access can continue until reauthentication. Routine edits reload without a service restart. No command requires a kernel rebuild.

6 Accounting

Peios / Reference / RADIUS

Accounting records what a network access server (NAS) reports about access: session starts, updates, ends, and cumulative traffic counters. The reports contain identities and device metadata. They contain no browsing history or packet payloads. Accounting is independent of credential verification.

6.1 Storage and acknowledgments #

radiusd authenticates the actual sender against the most specific configured client prefix and its shared secret. An asserted NAS name never establishes transport trust. Disabled specific prefixes mask broader enabled clients. The accounting listener uses its own configuration path, independent of authentication certificates and private keys.

One owner writes a private SQLite ledger at /var/state/radius/accounting/ledger.db. WAL mode with FULL synchronization commits observations, retry receipts, session interpretation, and quota evidence together. Accounting-Response follows a successful commit. Failure, queue pressure, and uncertain outcomes produce no success acknowledgment. The sender can retry after a lost reply without adding the usage twice.

Batches wait at most their configured intentional delay from the oldest queued report. Count and byte limits also flush batches. A management or admission operation flushes pending reports first. These bounds do not promise a total response latency during slow storage. The database owner never blocks the authentication packet loop while it performs disk operations.

SQLite limits database pages within a transaction. Free pages remain reusable after retention. Lowering the limit does not shrink an existing file. The reported storage size includes the allocated database and WAL; WAL, shared memory, and filesystem overhead require additional disk space. Automatic checkpoints bound steady-state WAL growth, but one transaction can exceed that checkpoint threshold. Keep filesystem headroom outside the database cap.

Corruption, foreign databases, unsupported schema versions, links, and untrusted file descriptors do not cause automatic replacement with an empty ledger. A separate file lock prevents two owners. Stop radiusd before copying the database, WAL, and shared-memory files as a consistent backup set. Rebuild reinterprets retained evidence; it cannot recover deleted evidence.

Ledger format 4 retains complete issued and requested access settings and their exact equipment encodings. Formats 1–3 upgrade in place. Existing evidence and unknown legacy fields are preserved. Earlier binaries refuse format 4; keep a stopped full-state backup and prior runtime for rollback.

6.2 Session interpretation #

Start, Interim-Update, and Stop form ordinary sessions. Accounting-On and Accounting-Off define whole-NAS boundaries; subsystem equivalents use Called-Station-Id. Reliable event times prevent delayed restart notices from closing newer sessions. Missing or implausible times remain uncertain.

Tunnel and tunnel-link reports retain their own occurrences and identifiers. They do not close or charge the parent session again. Unknown status values remain observations without invented lifecycle effects. IPv6 and opaque attributes remain bounded report data. A versioned declarative accounting profile can normalize vendor attributes; profiles execute no code.

Successful local authentication creates an opaque Class reference for the verified security identifier (SID), membership snapshot, client, policy, and optional station. The reference and any concurrent reservation commit before Access-Accept. Retransmissions reuse the exact signed reply and reference. Class is a correlation receipt, not a bearer credential or logon authority.

Reports without a recognized Class can still form a session. Their asserted username does not become a verified SID. Ambiguous matches remain unresolved. Reauthentication can replace the membership snapshot for subsequent evidence; earlier intervals retain their original attribution. Byte deltas across that boundary remain approximate because the NAS supplies cumulative snapshots.

Counters retain the full unsigned 64-bit range. Regressions do not refund or double-charge usage. Missing high words, late reports, inferred ends, and uncertain boundaries carry warnings. Stale sessions continue to consume concurrency until Stop, a reliable lifecycle boundary, or configured inferred expiration. An inferred end is not a factual Stop.

6.3 Permissions and privacy #

The local accounting socket checks the actual caller token through the kernel. Registry management permissions, accounting query permissions, and network Connect permissions are separate. The default accounting security descriptor (SD) permits SYSTEM and Administrators. A policy can provide its own accounting SD; an absent policy falls back to the global descriptor.

Accounting rights are Read (0x1), Personal (0x2), Usage (0x4), Disconnect (0x8), Correct (0x10), and Raw (0x20). Personal permits identity fields; Usage permits counters. Session filtering and pagination apply caller scope before selecting a page. A principal filter needs Personal authority over its requested scope. Delegated usage queries do not expose global allowances.

Optional self-service compares the real caller SID with verified session identity. It provides the caller's rows, history, and usage, without granting Disconnect, Correct, Raw, or direct database access. A reported username alone cannot satisfy self-service. Linked views require their separate toggle and preserve individual session occurrences.

AccountingRetainNames and AccountingRetainAttributes control future ingest. They do not retroactively erase retained data. Raw packet capture is off by default, has separate age and byte limits, and requires both retention controls. Authentication proofs, passwords, and known key attributes are rejected before recording. Treat unknown vendor attributes as private data.

Observation retention removes detailed reports through checkpoints. Summary retention removes ended personal session views. Quota evidence is separate: byte rollups and principal intervals remain available for lifetime limits. Personal history expiry does not reset allowances or erase all SID evidence. The detail interval samples Interim history views; it does not skip live counter processing or deduplication evidence in the retained journal.

6.4 Allowances and enforcement #

Allowances attach to user or group SIDs, optionally scoped to a policy. Every applicable allowance consumes the same attributable usage independently. Allowances never add together. Duplicate membership does not charge a group twice. A zero maximum denies the corresponding resource.

Dimensions are received bytes, sent bytes, total bytes, total session time, connected time, and concurrent sessions. Time amounts use milliseconds. Total session time sums intervals. Connected time unions overlapping intervals across applicable sessions. Five simultaneous one-hour sessions consume five session-hours and one connected-hour. Both limits can coexist.

Periods use UTC days, Monday-based weeks, months, or lifetime. Concurrent limits use lifetime because slots do not reset on a calendar boundary. Cumulative byte deltas are assigned to the update's event period. A delta crossing a reset boundary cannot be divided precisely without another report. Use the uncertainty flags when interpreting those totals.

Admissions reserve concurrent capacity atomically before Access-Accept. Reauthentication with the same verified account, configured client, policy, and nonempty station identity reuses one existing active slot. Its reservation does not charge principals already represented by that session twice. New group memberships still reserve their own capacity. Without matching station context, admission cannot assume it is an existing connection. Reservations expire if no corresponding session follows. Applicable limits can shorten Session-Timeout and request Disconnect for ongoing sessions. Reports arrive late and devices can reject Disconnect, so enforcement is approximate rather than an exact byte cap.

OnAccountingUnavailable=deny-new refuses required or limited admissions during an outage. allow-new bypasses that guarantee and increments the bypass counter. Unconstrained policies without required accounting can continue ordinary authentication. No mode acknowledges an unrecorded report or fabricates a durable Class reference. Storage failure does not disconnect every existing client.

Disconnect records persist selectors, attempts, and outcomes. Requests target the recorded source address through its configured client and shared secret. Attempts commit before transmission. ACK, NAK, and timeout outcomes remain separate from session state. An ACK does not manufacture Stop. General Change-of-Authorization is outside this implementation.

Repeated requests for an occurrence with a pending, sent, or uncertain Disconnect return the existing command. The current interface has no explicit retry command for an uncertain result; it does not silently reset its attempts.

6.5 Administration and diagnostics #

The accounting status query reads AccountingSecurity before checking the caller's token. A failed Registry read makes the query unavailable; it does not substitute the default descriptor for an unreadable configuration. The default applies only when a successful read finds no explicit setting.

Run radius accounting init as an administrator to provision the private directory. Creation supplies its private descriptor atomically and requires the KACS control-handle support described in Native Integration. Existing directories and ledger files must already have trusted owners and private descriptors. SQLite also needs ReadAttributes on its path prefixes. On a restrictive /var/state, grant the service only mask 0x80 without inheritance; do not grant directory listing or broad data access. Use the normal port reservation descriptor for the accounting UDP port.

Network packet admission is separate from port binding permission. An enforcing Flow policy needs to admit incoming accounting traffic to the configured UDP listener. Disconnect also needs permission for a new outbound UDP flow from that listener to the configured client's Disconnect port, conventionally 3799. Scope that exception to the intended server and AP addresses. Replies to an admitted flow follow its existing Flow judgment. Enable the NAS's dynamic authorization service separately; a listener or firewall rule does not enable it on the NAS.

For an existing schema 2 development deployment, provision the Quotas and AccountingProfiles collection keys under Machine\Software\Radius before creating their first records, preserving the parent's management permissions. Fresh radius config init creates all collections. This is a one-off development upgrade, not an automatic schema migration.

Turn on AccountingEnabled and set AccountingListen under Machine\Software\Radius\Settings. Client records share the existing prefix, secret, and policy references. ServiceKind=accounting-only accepts accounting for services without Wi-Fi authentication configuration. It does not implement another authentication protocol. Consult radiusd.regman for the individual controls, defaults, bounds, and restart requirements.

Use radius accounting status, sessions, session, history, usage, and commands for protected diagnostics. Session pages return a revision and cursor. Supply both --after and --revision for the next page; restart the view if its revision changes. annotate records an actor and note. correct-end requires confirmation and can only narrow a stale or inferred end within the last known evidence bounds. rebuild --confirm preserves stable occurrence IDs, usage evidence, corrections, and command history. It does not send another Disconnect or replay accounting telemetry.

The GXWI Accounting section displays protected session details, cumulative traffic history, allowance bars, and health. Allowances and Accounting Profiles use the same configuration model as CLI editing. Saved settings do not establish successful daemon activation; inspect health after changes.

eventd receives service health and operational counters only. Accounting usernames, user SIDs, device addresses, session identifiers, Class references, and individual traffic measurements remain in the ledger. Metric names have the fixed radiusd.accounting prefix with no personal labels. Provision that namespace with radius accounting telemetry-init after eventd provisioning; the command preserves existing namespace policy. Telemetry submission is best effort and is not the authority for limits or accounting facts.

6.6 Qualification #

Portable checks cover independent integrity fixtures, semantic retries, reordered reports, exact counters, principal reservations, overlapping limits, retention, correction, rebuild, full-storage recovery, and process exit after commit before reply. Native checks use a NIC-less disposable VM and the production kernel, without rebuilding the kernel or packages.

A real UniFi/iPhone trial passed session Start, one-minute Interim reports, Class correlation to the verified account despite an anonymous outer username, Stop, and fresh reconnect occurrences. It also passed authenticated Disconnect followed by Stop and automatic reconnection, principal time-allowance exhaustion with subsequent admission refusal and restoration, and a daemon restart with retained session/history followed by a continuing AP update. Stored reports across three APs retained the same verified identity and closed the old occurrences. Their one-second timestamps do not establish subsecond handoff latency, zero packet loss, or uninterrupted application traffic.

Passing fixtures does not qualify every NAS, tunnel implementation, or vendor profile. Test real equipment for reporting frequency, Class echoing, counter semantics, roaming, and Disconnect enforcement. A process or VM crash test does not establish power-loss behavior of every host storage stack. Full eventd ingestion and production-scale capacity remain separate qualification limits.

7 Access Assignment

Peios / Reference / RADIUS

Each access policy owns a forest of assignment rules. A successful decision selects one complete access profile. Profiles are shared objects with stable GUIDs; renaming a profile preserves its references.

Assignment supplements authentication, Connect permissions, and accounting allowances. All gates must permit access before radiusd sends success or keys. Authd supplies identity and permitted claims; it does not interpret VLANs.

7.1 Profiles and defaults #

An access profile contains Name, Enabled, and optional typed network settings described in Access Profile Settings. These include timers, rates, filters, addressing, tunnels, and equipment extensions. The optional VlanId is a DWORD. VLAN IDs range from 1 through 4094. An absent VlanId produces no VLAN override. Zero is invalid. Disabling a selected profile refuses admission.

Profiles live under Machine\Software\Radius\AccessProfiles\<guid>. Rules live under AccessPolicies\<policy-guid>\Rules\<rule-guid>, relative to the same RADIUS root. Child rule keys are exceptions to their parent rule. Name is a display label. Rule keys use canonical UUIDv4 identities.

No selected profile means refusal. An explicit catch-all rule can select a default profile, including a profile with no VLAN override. Parent rules do not merge settings into the selected profile.

radius access-profile create Staff --set VlanId=20
radius access-profile create Default
radius rule create Default --set Policy=POLICY-GUID \
    --set 'Actions=ASSIGN(DEFAULT-PROFILE-GUID)'
radius rule create Staff --set Policy=POLICY-GUID --set Parent=DEFAULT-RULE-GUID \
    --set Subject.Group.Equal=S-1-5-32-545 \
    --set 'Actions=ASSIGN(STAFF-PROFILE-GUID)'

Replace the GUID placeholders with identities returned by the creation commands. A nested Parent uses slash-separated ancestor GUIDs. Policy and Parent are derived management fields; direct Registry edits do not store them as rule values. A rule's location remains fixed after creation.

Remove a VLAN override with radius access-profile unset PROFILE-GUID VlanId. Use radius rule unset RULE-GUID CONDITION-KEY to remove a condition, or radius rule unset RULE-GUID Priority to restore inherited priority. Deleting an object with references is refused.

GXWI provides Access Profiles, Assignment Rules, and Explain Policy sections. The rule editor exposes actions, profiles, conditions, and parent selection. Shared-profile references appear in the affected-object information.

7.2 Rule evaluation #

The evaluator shares PNP's tree traversal, ancestor fallback and collation. Conditions on a rule are ANDed. Alternatives inside one condition are ORed. Disabled rules hide their subtree. A matching child shadows its parent only within that tree; independent trees still contribute candidates.

Priority is a signed decimal string or a DWORD. It inherits from the parent, or defaults to zero at a root. Actions accepts a string or string list:

  • ASSIGN(profile-guid) selects a complete profile.
  • REJECT refuses admission.
  • NULL abstains. The nearest ancestor with a direct decision speaks for that region, using the ancestor's priority.

The highest-priority candidate wins. At equal priority, REJECT wins over assignment. Equal-priority assignments to the same profile agree. Different profiles tied at the winning priority cause a per-connection refusal, with both rule paths reported in operational diagnostics. Rule order has no effect on permission. A single rule cannot select multiple different profiles.

7.3 Facts and types #

FactMeaning and type
Subject.UserAuthd-verified user SID
Subject.GroupAuthd-disclosed enabled group SIDs; any-member matching
Subject.NameAuthd's canonical username; exact string
Subject.Claim.<name>.<type>Disclosed claim; explicit native type
Client.IdGUID of the configured client that verified the request
Client.AddressActual packet source IP address
Request.SSIDReported SSID bound to the selected access policy
Request.StationAP-reported station MAC; not device authentication

Condition value names append an operator, such as Subject.Group.Equal or Subject.Claim.Department.String.Equal. Claim types are Int64, Uint64, Boolean, String, Sid, and Octet. Claim names use the same per-character Unicode lowercase equivalence as KACS and authd, without normalization or full case folding. String values compare exactly.

Equal uses one scalar or a list. Signed integers and IP addresses use PNP's pattern grammar; unsigned integers preserve the full 64-bit range and support decimal inclusive ranges. Numeric facts support GreaterThan and LessThan with one threshold. Boolean patterns use true or false; octet patterns use even-length hexadecimal strings. MAC patterns use PNP's colon-separated form. Runtime values never convert between strings, numbers, and booleans.

Unknown facts, unsupported operators, and malformed patterns invalidate the configuration. A known fact missing from an authentication does not satisfy an ordinary comparison. A value of an incompatible type does not match.

Present = 1 tests known presence; Present = 0 tests known absence. For claims, filtered disclosure leaves omitted names unknown unless authd explicitly confirms absence. Neither presence test matches an unknown claim. Disabled and deny-only claims are unavailable to assignment comparisons and cannot prove absence. Withheld claims do not become false, zero or empty.

7.4 Configuration and established connections #

Rules and profiles join the same short, consistent Registry snapshot as other RADIUS configuration. Invalid, pending, or unreadable configuration pauses new admissions and cached success replies. The status endpoint remains available for repair; radiusd does not continue granting under an older policy.

The final authentication decision uses current policy. Semantic changes invalidate cached acceptance replies. Existing Wi-Fi connections receive another assignment when they next authenticate, including automatic reauthentication. The AP controls how it applies a changed VLAN. Configurable Session Controls can act after successful activation; VLAN-change Disconnect defaults on when automatic controls and accounting are enabled. The exact issued baseline, current policy, and precise session selectors determine which occurrences are affected.

A VLAN change does not assign the client's IP configuration. A client can retain its previous DHCP lease after reauthentication and lose connectivity until it disconnects and reconnects. Do not assume a live VLAN change is seamless: qualify both the AP's assignment and the client's address renewal. DHCP's network-change guidance describes address verification after disconnection. When testing a change, check the client's address, gateway, and connectivity on both networks.

VLAN assignment uses the three tunnel attributes described in RFC 3580 section 3.31, with a zero tag and a decimal VLAN string. radiusd signs the complete response, including accounting Class and timeout attributes, before caching it.

7.5 Explain saved policy #

Explain Policy uses the same compiler and evaluator as admission. It shows matching conditions, shadowed rules, ancestor fallback, priorities, competing profiles, and the backstop. Explanations contain condition outcomes, not claim values. Normal Registry permissions govern access to rules and profiles.

The CLI accepts typed hypothetical facts from a JSON file:

{
  "values": {
    "Subject.Group": [{"type": "sid", "value": "S-1-5-32-545"}],
    "Subject.Claim.Department": [{"type": "string", "value": "Engineering"}]
  },
  "claim_coverage": "filtered",
  "absent_claims": []
}
radius --json policy explain POLICY-GUID --facts /path/to/facts.json

claim_coverage defaults to filtered. Set complete only when the hypothetical input intentionally asserts a complete claim set. absent_claims supplies known absences separately. GXWI exposes the same knowledge distinction.

The result identifies saved configuration and its fingerprint. It does not claim that the daemon activated that configuration. Simulation does not verify credentials, run Connect checks, reserve allowances, grant access, or contact an AP.

Supplying a single Client.Id fact compiles the selected settings with that client's saved equipment mapping. The returned authorization plan separates encoded settings from missing mappings and missing client context. Successful encoding does not establish that a device supports or enforces the attributes.

7.6 Bounds and development migration #

The Registry loader accepts at most 1024 rules, 32 nested exception levels, 64 conditions per rule, 256 alternatives per condition and 4 MiB of rule values. Profile count is bounded at 256. Hypothetical input has equivalent fact bounds; the CLI file limit is 1 MiB.

Schema 3 requires explicit assignment rules. For a stopped schema 2 development deployment without assignment objects, the migrate-policy-v3 example prepares one default profile and a catch-all rule for each authenticating policy. Running without arguments prints the candidate. --apply creates the defaults and changes the schema in one Registry transaction. It preserves credentials, existing records, and descriptors; created keys inherit normal permissions. Do not edit RADIUS configuration concurrently with this one-off migration. Keep the prior configuration and runtime available for rollback.

8 Authentication Diagnostics

Peios / Reference / RADIUS

radius diagnostics and the GXWI Diagnostics section show recorded progress through authentication. Both read eventd using the caller's identity. radiusd does not expose a privileged alternative history or store another diagnostic database. Authentication does not wait for eventd storage or diagnostic readers.

8.1 Attempts and outcomes #

One attempt represents one authentication conversation. Retransmissions retain its identifier. A fresh conversation, including reauthentication, gets another. The identifier is displayed as 32 hexadecimal digits. It is not a credential.

Milestones cover method selection, TLS, credential verification, network permissions, assignment, and accounting admission. Repeated polling does not create another milestone for the same result under the same configuration. The final radiusd.exchange.attempted event also carries a summary that can be read independently.

An Accept means the local UDP socket accepted the reply for transmission. It does not confirm AP admission, DHCP, or internet access. A send failure, timeout, and credential refusal are separate outcomes. A TLS timeout does not prove that the person rejected a certificate.

An explicit authority denial for failed credentials or a restricted account uses the generic authentication-failed reason. Unknown accounts and incorrect passwords share that reason. Authority outages, other authority denials, and client transport or protocol failures use authority-unavailable; they do not establish that the supplied credentials were wrong. The authority's free-form error message is not copied into this classification.

Stage sequence numbers order one attempt. Elapsed milliseconds use the local monotonic clock. Event timestamps can move after a wall-clock adjustment. Separate services have separate event orders; nearby timestamps do not prove that their events belong to the same attempt.

8.2 Finding evidence #

Use a bounded time window and inspect whether the result was limited:

radius diagnostics list --since 900 --username alice
radius diagnostics follow --since 300 --station aa:bb:cc:dd:ee:ff
radius diagnostics show ATTEMPT-ID --since 86400
radius diagnostics drops --since 300
radius diagnostics status

--network selects an access-policy GUID. --client selects a client configuration GUID. --username matches the supplied inner username exactly; it does not establish identity. Station identifiers are normalized reported MAC addresses. The outer EAP identity is not recorded.

Personal and configuration filters operate on reconstructed, readable attempts in the returned record window. This keeps anonymous TLS stages alongside a later supplied username. A limited record window can omit other matches. Use a narrower time window or adjust the configured bounds when necessary.

Finite --json commands return structured results. The command diagnostics follow --json writes one JSON object per line: kind=status for reader state, or kind=event with an authorized record. Stop following with Ctrl+C.

In GXWI, select Diagnostics, enter filters, and select Follow Live or Refresh History. Details retain the selected attempt during live updates. A selected attempt outside the returned readable window remains selected but unavailable.

8.3 Authority and configuration links #

An authority supporting the optional PGSS operation GUID supplies an exact link to authd.authentication.attempted. show and Read Linked Events query that GUID and the RADIUS service caller SID. eventd independently authorizes the authority records. Empty results do not establish that no authority event exists. An older authority can authenticate without supplying the identifier.

Correlation is not attestation or authorization. Event type names alone do not prove an emitter's identity. Retain readable kernel event headers when reviewing evidence. Principal-source events are not joined by guessing from names or timestamps.

An attempt records the effective authentication fingerprint, relevant configuration identifiers and observed decisions. Labels and diagnostic controls do not alter that authentication fingerprint. The saved configuration fingerprint is separate. Historical decisions are not recomputed against edited policy. The hypothetical Explain Policy operation remains separate.

Recorded labels remain historical. Open Current Object opens today's readable configuration, which can differ or be unavailable after deletion or a permission change. Current configuration never fills a field missing from the timeline.

8.4 Permissions and privacy #

eventd's record and field security descriptors govern both history and live streams. RADIUS management rights do not automatically grant diagnostic read rights. The reader does not elevate or query as radiusd. Configuration-read permission is not required to use independently delegated event access.

Live readers run in the caller's own process. An impersonating host can use finite history queries on its calling thread, but cannot start a live worker that would inherit a different process identity. Reader startup checks this boundary without requiring token-duplication or impersonation rights.

Records can include packet source addresses, AP-reported station identifiers, supplied usernames, and verified identities. Supplied usernames remain unverified even when an attempt succeeds. Verified names and security identifiers come from the authentication result. The normal timeline does not copy the full groups-and-claims snapshot.

Passwords, authentication proofs, shared secrets, private keys, and decrypted authentication payloads are excluded. Unknown diagnostic fields are refused by the emitter's schema guard. This interface provides no packet dump.

A field absent from eventd's response is unavailable. The reader cannot tell whether it was never recorded or withheld. It does not recover missing fields through configuration or a more privileged query.

8.5 Loss, bounds, and retention #

A missing terminal event leaves the outcome unavailable. Late evidence can complete a timeline. Disconnected streams show their state immediately, reconnect with overlapping history, and deduplicate records. Reader renewal, limited backfill, collection loss, and missing stage sequences can leave gaps. Old results retained during a failed reconnect are marked disconnected.

Finite queries publish no result if eventd fails before confirming completion. An empty successful query means no matching readable records were returned. It does not prove that no connection was attempted.

Requests discarded before conversation allocation have separate aggregate reports, with bounded recent samples. Client matching is not proof of request integrity. An integrity failure does not prove a wrong shared secret.

Registry values beginning with Diagnostics under Machine\Software\Radius\Settings control emission and reader bounds. Consult radiusd.regman for defaults and valid ranges. Client bounds limit retained records and payload bytes; decoded frames and collection structures require additional memory. eventd applies its own query resource limits independently.

Emission reserves capacity for final summaries, without guaranteeing delivery under overload. Collection reports expose emission failures, local rate suppression, and records omitted by emission policy. These reports are also best effort. Missing reports leave collection state unconfirmed.

eventd controls persistent retention and field permissions. RADIUS does not maintain an independent retention database or replay deleted evidence.

9 Session Controls

Peios / Reference / RADIUS

RADIUS session controls operate on the accounting ledger's exact connection occurrences. They use RFC 5176 Disconnect or Change of Authorization (CoA) packets. Authentication can run without accounting; automatic session controls require its inventory.

Use the local CLI or the GXWI Accounting section:

radius accounting disconnect SESSION-GUID
radius accounting reauthenticate SESSION-GUID
radius accounting update SESSION-GUID
radius accounting reconciliation SESSION-GUID
radius accounting commands SESSION-GUID

These commands retain the original occurrence, NAS selectors, device source, action, actor and configuration revision before sending. An AP-reported username never establishes identity or selects another connection. Sessions without precise NAS and session selectors cannot be controlled. Missing verified identity also prevents automatic controls; manual Disconnect can still terminate a precisely identified occurrence.

CLI and GXWI generate a request GUID. Automation can supply --request-id ID and reuse it after a lost reply. The actor/request pair retains one command, including terminal results; it cannot select another session or action. A different deliberate action needs a new ID. Inspect command history before repeating an operation whose reply was lost. Request IDs are not capabilities.

9.1 Device capabilities #

A client can reference a reusable DynamicAuthorizationProfile GUID. Its record lives under DynamicAuthorizationProfiles and contains Name, Enabled and a JSON Definition. CLI uses the dynamic-profile object; GXWI calls these Session Control Profiles. A missing reference uses the generic RFC 5176 profile.

The same definition's authorization member supplies admission mappings, qualified live settings and explicit reset attributes for richer profiles. See Access Profile Settings. The WISPr template provides rate encodings without claiming live support.

Profiles declare bounded recipes for disconnect, reauthenticate and update-authorization, optional station targeting, standard attributes and vendor-specific encodings. They cannot run code, insert usernames as selectors, or replace integrity, authorization, retries and replay handling. NAS and Acct-Session-Id selectors remain mandatory. See the source definition in radius-accounting/src/dynamic.rs for the complete validated schema.

nas_selectors chooses which recorded NAS attributes the profile transmits: ip-address, identifier, and ipv6-address. Omitting it retains all recorded NAS attributes. The list must be nonempty and contain no duplicates; at least one selected attribute must exist on the recorded occurrence, or the request is refused. For example, "nas_selectors": ["identifier"] uses only the recorded NAS-Identifier. This changes the wire recipe, not the immutable session target or destination. Acct-Session-Id and integrity remain mandatory.

The generic profile supports Disconnect and standard VLAN/Session-Timeout updates. It does not claim fresh reauthentication. Clearing a VLAN override has no universal CoA encoding; it needs an explicit device reset recipe or an enabled fallback. A profile that advertises reauthentication must declare fresh_proof: true after device qualification. RFC 5176 Authorize-Only is reauthorization and cannot serve as that declaration.

Every request carries Message-Authenticator and Event-Timestamp. Profiles default to "proxy_state_nonce": true, adding an opaque Proxy-State nonce. Set it to false only for a NAS that rejects that attribute; durable request allocation still applies. Responses must match the packet family, identifier, peer, and request authenticator. Requiring a response Message-Authenticator is configurable for NAS compatibility. Do not advertise a device-specific recipe as qualified until it has produced a fresh authentication exchange on that device.

Before a new request can be transmitted, the ledger reserves its timestamp and identifier atomically with the prepared packet. The pair never moves backwards on the machine, even after a daemon restart, accounting rebuild, history expiration or clock rollback. Retransmissions reuse the original committed packet. An old ACK cannot authenticate a later request using a different reserved pair.

identifier_reuse_seconds controls the NAS duplicate-detection window, defaults to 300, and accepts 1–86400 seconds. Match it to the device's window. At most 256 new requests can be sent to one NAS address within that window; retries reuse their original reservation. Exhaustion or clock rollback leaves requests pending, with a waiting reason, until a valid pair is available. Other NAS addresses have independent reuse windows. The global pair allocator permits up to 256 new requests per second across all NAS addresses, preventing reuse when a destination or shared secret changes. No timestamp is moved into the future to work around exhaustion. This follows the identifier and replay constraints in RFC 5176.

The allocator is retained in ledger format 4 and seeded from stored packets when upgrading formats 1 or 2. Take a full offline state backup before the upgrade; earlier daemons cannot open the upgraded ledger. Ordinary evidence rebuild and retention do not erase the allocator.

For a NAS that rejects Proxy-State, a Disconnect-only compatibility profile can retain all recorded NAS selectors and require the recorded station:

{
  "version": 1,
  "name": "Disconnect without Proxy-State",
  "proxy_state_nonce": false,
  "station_selector": true,
  "require_station": true,
  "recipes": [
    {"action": "disconnect", "fresh_proof": false, "attributes": []}
  ]
}

On the development UniFi AP, the generic request received an authenticated NAK with Error-Cause 401. Omitting only Proxy-State produced an authenticated ACK, an accounting Stop and a new session with fresh password proof. This also worked automatically when changing the assignment to VLAN 20 and back to no override. This qualifies Disconnect on that tested device; it does not establish CoA update, other firmware behavior or a DHCP address change.

In the observed iPhone trial, the address eventually changed to the VLAN 20 subnet after Disconnect and fresh authentication. On the return to no override, the phone still displayed its old address after five minutes. Explicitly assigning the main VLAN also failed to produce a new address and connectivity was lost. Manually toggling Wi-Fi restored an address on the main subnet. Automatic DHCP renewal on VLAN changes is therefore not qualified by this test. A successful Disconnect and new password proof do not establish that the client has usable IP configuration. AP forwarding and client DHCP behavior were not captured, so the precise cause remains unverified.

9.2 Automatic behavior #

With accounting enabled, automatic session controls default on. The defaults disconnect a session after its effective VLAN assignment changes or current access is revoked, and request fresh authentication after password replacement. Automatic CoA authorization updates have a separate switch, default off. Disabling VLAN-change Disconnect therefore does not implicitly select CoA.

Each access policy can override the defaults through SessionControl JSON. Omitted members inherit their global values. GXWI exposes the overrides as ordinary selectors under Access Policies:

{
  "vlan_disconnect": true,
  "revoke_access": true,
  "password_reauthenticate": true,
  "update_authorization": false,
  "unavailable_grace_seconds": null,
  "fallback": []
}

null outage grace keeps existing connections and retries. A positive grace can disconnect when current identity evaluation remains unavailable. The timer persists across daemon restart and accounting rebuild. This requires an active, valid control configuration; invalid or pending configuration pauses controls as well as new successful admissions.

Reconciliation uses the original verified SID with current account status, permitted claims, groups, Connect permissions, and assignment rules. It never turns missing or withheld information into a grant or confirmed deletion. Available, authorized lpsd change events are hints; periodic fresh reads cover missed events, other sources, and restarts. Rapid hints coalesce without continually restarting an unfinished inventory scan. Rules and shared-profile effects use the same activation path as direct Registry edits. Renames and unchanged effective decisions do not create session-control requests.

Only successfully activated configuration can authorize a command. A bounded worker rechecks queued intent and retries against fresh identity state, away from the UDP loop. Changed policy can supersede unsent commands. A transmitted command whose relevance is lost remains uncertain: it might already have acted. An old occurrence's command is never redirected to a new roaming occurrence.

9.3 Evidence and outcomes #

The ledger keeps issued authorization, desired current authorization, and device-reported observations separate. A recorded no-VLAN-override is an explicit issued decision. No baseline means unknown, including sessions from older ledger versions. Missing NAS observations do not imply an applied VLAN.

Successful authentication also binds an opaque credential reference and revision. Password, MSCHAPv2, and NTLMv2 share the local password revision. Replacement rotates it; NT-hash backfill and storage maintenance do not. Current lookup can detect change or ineligibility, but only successful fresh authentication can advance the revision proved by a session. RADIUS receives no stored password hash or private key through this metadata.

The command history distinguishes pending, sent, acknowledged, rejected, unsupported, uncertain, and superseded outcomes. Retries retain the exact packet across restart. Only an explicit unsupported capability permits a configured fallback; timeout, permission refusal, missing selectors, and a missing session do not. The default fallback reports failure. Allowed fallback order is update, then fresh reauthentication, then Disconnect; configure only the steps desired.

An ACK records NAS acceptance. It does not establish fresh proof, a Stop report, reconnection, DHCP renewal, or working applications. A phone can retain an old lease after a VLAN change. Qualify reconnection and address renewal separately on each AP/client combination.

9.4 Configuration and permissions #

Global controls are under Machine\Software\Radius\Settings. Individual DWORDs override the corresponding DynamicAuthorizationSettings JSON member. Unknown JSON members and out-of-range values prevent activation. GXWI exposes the same controls; CLI uses radius config set NAME=VALUE.

The radiusd.regman reference owns each value's type, default, and bounds. Controls include the scan interval and batch/work limits, identity-read timeout, retry count and delay, command lifetime, maximum concurrent requests, response-integrity requirements, and each automatic trigger. One identity read can complete after the scan's work budget; its own timeout still bounds that read.

DynamicAuthorizationFallback is REG_MULTI_SZ, empty by default. It accepts reauthenticate, disconnect, or both in that order. For example, an explicit disconnect fallback lets an unsupported fresh-authentication request fall back to terminating that occurrence. It does not bypass permissions.

Accounting SD rights add Reauthenticate (0x40) and Update Authorization (0x80) alongside Disconnect (0x8). Read and Personal remain independent. Manual requests need Read and the action right, plus every configured fallback right, under the actual caller's token. Authorization is captured when the durable request is submitted. Automatic requests identify radiusd as their origin and are limited to enabled policy enforcement. Existing custom descriptors retain their existing grants; review them before delegating new actions. Packet bytes and shared-secret fingerprints are not returned by the management interface.

9.5 Upgrade and rollback #

Ledger schema 2 adds control state while preserving usage, observations, corrections, and command history. Older sessions keep unknown baselines until fresh authentication. Rebuild preserves outage timers and command history and does not resend commands as a side effect. Stable reevaluations do not fsync a heartbeat on every scan. Schema 3 adds the durable wire allocator described above, preserving that control state.

Schema 4 retains complete logical authorization, per-setting encodings, timer caps and command baselines. It accepts schema 1–3 records without inventing missing legacy attributes. An acknowledged update becomes the comparison baseline for subsequent changes, including a return to the originally issued profile. Quota countdowns do not change the configured policy identity.

The matching lpsd uses store format 7 and persists credential bindings before exposing an upgraded store. Preserve offline copies of both stores, their security metadata, the prior configuration, and the prior runtime before a live upgrade. Older binaries cannot read these newer formats. An older development Registry can also need the DynamicAuthorizationProfiles collection provisioned with the existing parent's permissions; fresh radius config init creates it.

Host regression checks do not qualify an AP's fresh-authentication behavior, VLAN reset conventions, DHCP renewal or roaming timing. Keep device-specific qualification evidence separate from protocol and ledger tests.

10 Component Load and Recovery

Peios / Reference / RADIUS

radius-qualify is a developer tool. It uses temporary synthetic identities, an ephemeral certificate, and exclusively created scratch directories. It opens no external sockets, reads no deployed configuration, and contacts no native authentication service. It does not build a package, kernel, or image.

10.1 Build and run #

From the repository root:

pekit build --strict -j 2 qualify
pekit test --strict -j 2 qualification clippy

Use the executable path printed by the build. The Cargo equivalent is cargo build --locked -p radius-qualification; the executable is target/debug/radius-qualify. Use an optimized executable for measurements. Do not compare debug and optimized throughput.

radius-qualify auth --requests 4096 --concurrency 32
radius-qualify accounting --requests 2048 --concurrency 256 --batch 128 --scratch-parent /path/to/scratch
radius-qualify failures --scratch-parent /path/to/scratch

The scratch parent must already exist. Each invocation creates a new private subdirectory and removes it on completion. The failure fixture creates and terminates its own child processes; it never opens an existing ledger. --help lists workload options. Requests, peers, queue depth, batch size, and completion deadlines are bounded. Unexpected rejection fails a normal load; --allow-overload allows intentional rejection while still checking request conservation and recovery.

To collect the nine standard load cases and machine context:

python3 tools/capacity-qualification.py --binary /path/to/optimized/radius-qualify --out /path/to/new-results --scratch-parent /path/to/scratch

The output directory must be new. The runner records the executable hash, CPU, affinity, starting load, filesystem type, commands, exit statuses, and JSON results. Each case has a controller deadline. Keep the report with the source revision and build settings used to produce that executable.

10.2 What the workloads measure #

Authentication runs full TTLS/PAP exchanges through the production coordinator and TLS implementation. Credential verification and authorization use a fixed synthetic backend. The measurement excludes native authd, password hashing cost, UDP transport, APs, and client radio behavior. After the load drains, a fresh conversation must succeed on the same coordinator.

Accounting submits unique session Start records to the real asynchronous owner and SQLite WAL/FULL ledger. Latency runs from submission to receipt collection and includes batching delay. Every accepted receipt must map to a unique retained observation after stopping and reopening the owner. This is not a mixed Start/Interim/Stop benchmark or a measurement of native packet ingestion. Both workloads use a bounded window of outstanding work rather than a fixed external arrival rate.

max_pending counts outstanding synthetic peers for authentication and submitted receipts awaiting collection for accounting. It does not measure internal queue occupancy. Peak RSS is the process high-water mark from Linux, including fixtures and recovery checks. Successful completions determine throughput and latency percentiles; rejections are reported separately.

10.3 Observed measurements #

On 19 November 2026, the optimized hermetic build ran on a Ryzen 5 7600X host with 12 logical CPUs available. The host was shared with other work; starting load averages were approximately 3.7, 7.0, and 4.2. The scratch filesystem reported ext2/ext3. These single-run observations establish neither a production ceiling nor a recommended deployment limit.

WorkloadWindow / batchCompleted per secondp99 latency
Synthetic TTLS/PAP, serial1 / none3,9900.29 ms
Synthetic TTLS/PAP32 / none4,1128.05 ms
Synthetic TTLS/PAP128 / none4,08831.66 ms
Accounting Starts64 / 164,90825.68 ms
Accounting Starts256 / 12813,18021.65 ms
Accounting Starts1,024 / 51217,32359.30 ms

The timer-driven case used a 64-record window below the 512-record batch threshold. Its one-second flush timer produced about 1.02-second p99 latency, as expected. Do not infer poor saturated throughput from that case. Peak process RSS across all nine cases remained below 13 MiB.

The authentication overload case completed 4 and rejected 4,092 requests with a four-attempt limit, then accepted a new conversation after draining. The accounting overload case committed 32 and rejected 4,064 submissions with a four-record queue; all accepted receipts survived reopening. Queue capacity limits queued work, not all work already committed or in progress. These rejection counts depend on the synthetic arrival pattern and timing.

10.4 Failure regressions #

The storage fixture checks 20 cases: eight write-error points, two sync-error points, eight full-storage points, termination during a sync, and termination after commit before acknowledgment. It checks atomic retention, idempotent retry, SQLite integrity, and foreign-key integrity after reopening. Faults are installed only inside dedicated developer child processes. A fault family must reach an injection point for its run to pass.

Other deterministic regressions check bounded authentication tables, accounting queue saturation, recovery when an authority check becomes available, and failed or stalled required services. The production coordinator is exercised with unavailable event delivery: a successful authority and admission result can still succeed, while failed required authentication or accounting cannot produce an acceptance.

These checks passed on the host. The service failures use synthetic backend contracts. They do not establish native service restart behavior, physical power-loss durability, device-specific disconnect behavior, or a long soak. See Qualification for independent supplicant and disposable native gates.

10.5 Instrumented campaign status #

The optional fuzz/ workspace contains five bounded target adapters for packets, engine sequences, coordinator sequences, ledger replay, and control records. Shared entry points also support deterministic stable-Rust replay. tools/fuzz-qualification.py records seeds, commands, source and executable hashes, execution counts, coverage, logs, and artifacts in a new directory.

The first five AddressSanitizer campaign attempts all aborted during startup on an SQLite aiOff global ODR diagnostic. No execution or coverage counts were obtained, and no RADIUS failure artifact was produced. Compilation and deterministic seed checks do not establish an instrumented campaign pass. The instrumentation issue remains unresolved; the campaign gate is incomplete. Do not disable sanitizer diagnostics to count this gate as passing.

The adapters have further limits: successful encrypted exchanges in the coordinator fixture use TTLS/PAP; PEAP coverage here stops at method selection. Control sequences exercise durable records rather than a real AP transport. The existing independent and native protocol gates remain necessary. None of these checks is a complete security audit.

11 Access Profile Settings

Peios / Reference / RADIUS

An access profile describes the network service a successful authentication requests. Assignment rules select one complete profile; the receiving equipment enforces its attributes. The shared radius-authorization library validates logical settings, compiles the reply, and retains the association between each setting and its wire attributes for later session controls.

11.1 Setting families #

Profiles cover connection timers, bandwidth and priority, VLAN memberships, traffic filters and roles, gateway addressing and routes, tunnel parameters, accounting preferences, and device administration. These are authorization settings. Adding a gateway pool name does not add an address allocator; device-administration settings do not add a device authentication method. Authentication profiles and principal allowances remain separate.

The Registry interface is documented under Machine\Software\Radius\AccessProfiles\<guid> in radiusd.regman. Discover the same setting metadata used by CLI and GXWI with:

radius access-profile fields

An absent setting requests no override. An explicit false flag requests the equipment's disabled value; it differs from absence. Unknown settings and wrong Registry types invalidate configuration. Extensions is a JSON object of typed, namespaced Extension.<namespace>.<name> values, with explicit vendor mappings. It cannot override server-owned identity, selectors, keys, EAP state, Class, or integrity fields.

Rates are per connection, in bits per second from the connected device's perspective. Upload travels from the device; download travels to it. Bursts are bytes. The decimal string representation preserves the complete unsigned 64-bit range. Minimum rates cannot exceed configured maximum rates. A minimum rate requests an equipment capability; it does not reserve capacity in Peios or enforce a principal-wide aggregate bandwidth limit.

VlanId is a numeric untagged assignment. VlanName and tagged or untagged memberships use the distinct RFC 4675 attributes; they are not alternate spellings of the numeric tunnel assignment. A numeric VLAN and a second tunnel assignment cannot coexist. Named filters refer to filters installed on the equipment. Explicit filter rules accept the supported NAS-Filter-Rule grammar, with one complete rule per list item. Roles, isolation, QoS, and IPv4 DNS need an explicit equipment mapping.

Addresses, canonical prefixes, routes, MTU, and tunnel parameters apply to gateways that understand them. A route contains a destination, a gateway, and an optional numeric metric. A prefix with host bits is refused. IPv4 netmasks must be contiguous. Pool references do not allocate leases or control a bridged Wi-Fi client's DHCP state. Management settings require an appropriate management Service-Type; they do not grant a local Peios token.

AccountingInterimSeconds requests a NAS update interval of at least 60 seconds. It does not alter the ledger's durability rules. ServiceLabel is retained local authorization metadata unless an explicit mapping also sends it to the equipment. It never replaces the server's accounting correlation.

11.2 Timers and allowances #

RADIUS provides one Session-Timeout and its Termination-Action. Choose a profile reauthentication interval, or a session timeout with a disconnect or reauthenticate action. A session timeout defaults to disconnect. Configuring both interval settings is refused because they cannot be independent wire timers. Idle timeout is separate and concerns inactivity after admission; the daemon's similarly named conversation timeout bounds the authentication exchange itself.

The network's reauthentication cap can shorten the profile timer. Principal allowances can shorten it again. The accounting proof retains the configured cap separately from the shorter reply, so an allowance countdown does not create repeated policy-change commands. Disconnect expiry does not prevent another successful authentication. Use cumulative principal allowances for limits that span multiple successful authentications.

11.3 Configuring a profile #

CLI and GXWI use the same validation and complete-profile selection:

radius access-profile create Guests --set VlanId=20 \
    --set IdleTimeoutSeconds=300 --set DownloadBitsPerSecond=10000000 \
    --set UploadBitsPerSecond=2000000
radius access-profile set PROFILE-GUID \
    --set 'FilterRules=["permit in 6 from any to assigned 80,443"]'
radius access-profile unset PROFILE-GUID DownloadBitsPerSecond

Replace PROFILE-GUID with the created identity. List input accepts a JSON array when an item contains commas; simple lists also accept comma-separated items. GXWI uses one list item per line. Clearing an optional field removes the saved value. Saving still requires a valid complete profile; for example, remove its expiry action when removing its associated session timeout.

The rate example requires an equipment mapping before admission can succeed. A valid logical setting that cannot be encoded for the actual client refuses the connection before quota reservation. It is never silently omitted.

11.4 Equipment mappings #

The client's existing DynamicAuthorizationProfile also supplies its authorization mapping. Its definition contains three maps: settings for admission encodings, live for qualified CoA settings, and clear for explicit removal values. A missing setting uses its defined standard encoding. An empty encoding list explicitly marks a setting unsupported. Vendor-only settings have no guessed default. Encodings are bounded data, not executable plugins.

Generate the WISPr rate template with:

radius dynamic-profile template wispr

GXWI offers the same template while creating a Session Control Profile. It changes the draft only. The template encodes upload and download using vendor 14122 attributes 7 and 8. It declares no qualified live rate support. It is an attribute template, not a claim that a particular AP enforces those rates.

A custom mapping can describe integer, boolean, text, address or prefix encodings. Integer conversion uses an exact divisor: values that would round or overflow are refused. Text and decimal-text encodings can add bounded prefixes and suffixes. For example, a synthetic equipment definition could contain:

{
  "authorization": {
    "settings": {
      "DownloadBitsPerSecond": [
        {
          "target": {"vendor": 12345, "attribute": 1},
          "format": "decimal-text",
          "divisor": 1000,
          "prefix": "rate=",
          "suffix": "k"
        }
      ]
    },
    "live": [],
    "clear": {}
  }
}

This is the authorization portion of a full Session Control Profile definition. It is not a recipe for real equipment. Standard type checks, protected targets, conflicting attribute owners, and the complete reply budget apply to every mapping. A reply accepts at most 96 authorization attributes and 2400 encoded bytes; credentials and protocol fields remain server-owned.

11.5 Explaining and changing established access #

Explain Policy shows the selected logical settings. Supplying a single Client.Id fact also compiles an authorization plan with that client's saved mapping. The plan distinguishes unsupported settings and missing client selection. It does not authenticate, check every admission gate, send a packet or prove enforcement. Operational diagnostics record an assignment fingerprint over the selected VLAN and complete compiled authorization, without adding raw filter or extension values to events.

An automatic or manual CoA compares complete authorization settings. Changed settings need declared live support. A removal needs an explicit reset of the original recorded attribute; omission never means reset. A changed attribute identity requires fresh authentication. Management protocol and transport protection changes cannot be sent in CoA. Equipment that replaces an entire list must be qualified for that replacement behavior.

A recipe that cannot express the new authorization uses the existing configured fallback and its separate permissions. An ACK records what was requested and acknowledged, not proof that every setting was enforced. The issued baseline, desired settings, last acknowledged request, and limited NAS observations remain distinct. See Session Controls.

11.6 Storage and qualification #

Ledger format 4 retains logical settings, exact per-setting encodings, configured timer caps, and previous acknowledged authorization for commands. It upgrades formats 1–3 without inventing missing legacy settings. Back up the complete stopped ledger and prior runtime before upgrading: earlier daemons refuse format 4. Registry schema remains 3; older readers refuse unknown profile fields rather than grant a partial assignment.

Deterministic tests check encoding vectors, reply authenticators, protected fields, unsupported mappings, policy selection, quota gating, retransmission, reset handling, persistence, and frontend representations. These checks cannot establish traffic shaping, ACL enforcement, gateway addressing, or device administration on untested equipment. Qualify each required field on the actual NAS and firmware before relying on its enforcement.

The underlying attribute definitions are in RFC 2865, RFC 3580, RFC 4675, RFC 4849, RFC 6911, and RFC 5607.

Peios Learn — documentation for Peios software.

Built with Trail.