Reference
Formats and constants, and the technical reference manuals that describe how each component works inside.
Single-page view · as markdown
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 #
| Structure | Reference |
|---|---|
| Security identifier (SID), including its binary representation and well-known values | PCDS SIDs |
| Globally unique identifier (GUID) | PCDS GUIDs |
| Locally unique identifier (LUID) | PCDS LUIDs |
| Self-relative security descriptor and its control flags | SD Structure |
| Access control list (ACL) header and entries | ACL Format |
| Access mask and generic-right interpretation | Access Masks |
| Access control entry (ACE) types and bodies | ACE Types |
| Inheritance and propagation flags | Inheritance |
| Claims, resource attributes, and conditional expressions | Security 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 #
| Interface | Reference |
|---|---|
| Token creation, sessions, query classes, group attributes, and impersonation levels | Token and Session ABI |
| Access checks, descriptors, central policies, and security-information flags | Access-Check and Descriptor ABI |
| File rights, create dispositions, and mount templates | File and Mount ABI |
| Process rights, process security blocks, and mitigations | Process and PSB ABI |
| Registry rights and key security | Key and Security ABI |
| Registry watch records | Watch ABI |
| Event-ring records and constants | KMES 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
svctlcommand surface includingsvctl 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 #
| Concern | Component |
|---|---|
| Authentication and token minting | authd |
| The local identity database | lpsd |
| Log storage, indexing, and queries | eventd |
| Registry storage | registryd, over LCS |
| Packaging and installation | peipkg and the role system |
| Device management | eudev |
| Network configuration | a dedicated service |
| File access control enforcement | FACS |
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.
| Object | What it is | Lifetime |
|---|---|---|
| Service | A 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. |
| Job | A 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. |
| Operation | A 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 on | For |
|---|---|
| KACS | Service identity (installing tokens on children), control-interface authentication (peer token + AccessCheck), and per-service access control. See Access decisions. |
| LCS / the registry | Service definitions, boot configuration, and its own parameters. See The registry. |
| registryd | The 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.) |
| authd | Minting tokens for non-platform services. peinit requests; authd mints. |
| eventd | Service logs (forwarded over a socket) and job/operation/audit events (emitted through KMES). |
| KACS, again | Conveying 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 value | Token source |
|---|---|
SYSTEM | Minted by peinit from its own SYSTEM identity. |
| Any other principal name or SID | Requested from authd. |
| Absent or empty | authd, 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).
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.
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/devare mounted and have been moved into the real root;- the environment holds
TERMand 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.
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:
| Service | Why |
|---|---|
| registryd | Starts before authd exists at all. |
| authd | Needs 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.
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 point | Filesystem | Flags | Provided by |
|---|---|---|---|
/proc | proc | nosuid, nodev, noexec | initramfs |
/sys | sysfs | nosuid, nodev, noexec | initramfs |
/dev | devtmpfs | nosuid | initramfs |
/dev/pts | devpts | nosuid, noexec | peinit |
/dev/shm | tmpfs | nosuid, nodev | peinit |
/run | tmpfs | nosuid, nodev | peinit |
/sys/fs/cgroup | cgroup2 | nosuid, nodev, noexec | peinit |
/sys/kernel/security | securityfs | nosuid, nodev, noexec | peinit |
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:
| Node | DACL |
|---|---|
/dev/null, /dev/zero, /dev/full, /dev/random, /dev/urandom, /dev/tty, /dev/ptmx | D:(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.
2.3.6 Step 6: Start registryd #
peinit holds a compiled-in definition for registryd — the only compiled-in service definition there is :
| Field | Value |
|---|---|
| ImagePath | /sbin/registryd |
| Arguments | Machine=/var/state/loregd/Machine.hive, Users=/var/state/loregd/Users.hive |
| Identity | SYSTEM |
| Readiness | Notify |
| ErrorControl | Critical |
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:
- 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). - 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). - Loopback: peinit brings up
loover netlink, because services that bind127.0.0.1need 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 #
| Failure | Response |
|---|---|
| Root writability probe fails | Recovery |
| A mount point cannot be created | Recovery |
| A peinit-owned filesystem fails to mount | Recovery |
| A mounted filesystem cannot be stamped with its descriptor | Recovery |
/proc/self/mountinfo unreadable or unparseable | Recovery |
/proc, /sys or /dev already mounted, or EBUSY | Tolerated as success |
| A device node in the policy list cannot be stamped | Warning; node keeps the inherited default |
| A device node in the policy list does not exist | Noted; boot continues |
| Random seed absent, oversized, empty, or unrestorable | Warning; boot continues |
| Machine ID generation fails (CSPRNG) | Recovery |
| Machine ID unreadable, or unwritable at its path | Warning; boot continues with an identifier for this boot only |
| Machine ID absent, empty, or malformed | Regenerated; boot continues |
| Any RTC or clock failure | Recovery |
| registryd fails to start, or setup times out | Recovery |
| registryd readiness times out | Recovery |
| Base registry provisioning fails | Recovery |
| Schema-version probe returns a wrong type or length | Recovery |
| An autorun script is missing, unspawnable, or exits non-zero | Warning; boot continues |
| A provisioning entry is malformed | Warning; entry skipped |
| An optional provisioned path fails | Warning; boot continues |
| A required provisioned path fails | Recovery |
| Control socket creation or stamping fails | Recovery |
| Jobs socket creation or stamping fails | Recovery |
| Loopback bring-up fails | Warning; 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.
| Value | Type | Required | Default | Meaning |
|---|---|---|---|---|
Kind | string | yes | — | directory or file. |
Path | string | yes | — | Absolute path to create or verify. |
Security | binary | no | built-in | The Peios file Security Descriptor to apply. |
Required | dword | no | 0 | If 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
Requirestarget fails the dependent. - Warnings — a
Readiness=Aliveservice with dependents that require it — are logged and do not prevent boot: a[ WARN ]peinit warning:line on the console and apeinit.graph.validation.warnedevent under phaseboot, 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:
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.
- eudev — device management. SYSTEM, with
RequiredPrivilegesstripped to the minimum it needs. Starts before authd exists. - lpsd — the local identity database. Depends only on registryd.
- authd — the identity authority. Depends on registryd and lpsd. Once it is ready, token minting is available.
- eventd — logging and audit. Services started before it sign in to peinit's pre-eventd buffer.
- Networking — the first service to receive a token from authd.
- Application services, in dependency order.
- Sign-in services, last, so the system is operational before it accepts a session.
2.5.3.2 The bootstrap matrix #
| Service | Phase | Identity | Token from | Readiness | ErrorControl |
|---|---|---|---|---|---|
| registryd | 1 | SYSTEM | minted by peinit | Notify | Critical |
| eudev | 2 | SYSTEM | minted by peinit, privileges stripped | Alive | Normal |
| lpsd | 2 | SYSTEM | minted by peinit | Notify | Critical |
| authd | 2 | SYSTEM | minted by peinit | Notify | Critical |
| eventd | 2 | SYSTEM | minted by peinit | Notify | Critical |
| networking | 2 | service token | authd | Notify | Normal |
| sshd | 2 | service token | authd | Alive | Normal |
| application services | 2 | service token | authd | per-service | Normal |
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:
| Key | Default | Meaning |
|---|---|---|
Machine\System\Boot\SettleTimeout | 5 | Seconds 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.
2.5.5 Boot success #
A boot is successful once every Critical service has held a dependent-satisfying state continuously for a grace period:
| Key | Default | Meaning |
|---|---|---|
Machine\System\Boot\BootSuccessGrace | 30 | Seconds 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 #
| Failure | Response |
|---|---|
| A service definition fails to decode | That service Failed with cause ValidationError; the rest of the boot proceeds |
| A registry read times out | Recovery |
Invalid MaxParallelStarts or SettleTimeout | Recovery |
| A dependency cycle | All services in it Failed; Safe mode if any is Critical (see below) |
| An unresolvable conflict | Both Failed; Safe mode if either is Critical (see below) |
A missing Requires target | The dependent Failed |
| A Critical service fails during boot | Restart budget, then reboot |
| A non-Critical service fails | Failed; its Requires dependents fail; the rest continue |
| authd unavailable when a service needs a token | That 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=1services 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.
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=1on 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:
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 #
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.
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=1on 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:
- Completes Phase 1 steps 1–5 if they have not been reached yet.
- Ensures the base registry structure exists, so the shell sees a normal layout even on a system that has never been provisioned.
- Attempts to start registryd. A failure here is ignored — recovery delivers a shell whatever registryd's state.
- Skips all Phase 2 services.
- Starts a shell on
/dev/consolefrom a compiled-in definition, with no registry dependency:/bin/recshif it is present and executable, otherwise/bin/sh, running as SYSTEM with a fixed environment ofPATH=/sbin:/bin,TERM=linuxandHOME=/. peinit does not care where either binary comes from. - 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.
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.
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=1it stays there; without, it passes through Completed to release dependents and then goes Inactive. - A non-zero exit goes to Failed.
ExecStartPostruns after the successful exit rather than after a readiness signal, and does not run at all if the Oneshot failed.StartTimeoutcovers 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.
| Field | Type | Default | Meaning |
|---|---|---|---|
| ImagePath | string | required | Absolute path to the service binary. |
| Arguments | multi_string | — | Arguments passed to the binary. |
| Type | dword | 0 (Simple) | 0 Simple, 1 Oneshot. §3.1 |
| Triggers | multi_string | — | When the service starts automatically. §3.4 |
| Disabled | dword | 0 | If 1, no trigger activates the service. |
| SafeMode | dword | 0 | If 1, attempt this service in Safe mode. Implied by ErrorControl=Critical. §2.6 |
| Identity | string | LocalService | SYSTEM, shared LocalService/NetworkService, Service for the service's own virtual account, or a designated principal. §4.1 |
| RequiredPrivileges | multi_string | — | Privileges to keep; all others are removed. §4.5 |
| Requires | multi_string | — | Hard dependencies. §7.1 |
| Wants | multi_string | — | Soft dependencies. §7.1 |
| BindsTo | multi_string | — | Runtime coupling. §7.1 |
| Conflicts | multi_string | — | Mutual exclusion. §7.1 |
| Provides | multi_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 |
| OnFailure | string | — | Service to start when this one fails. §6.3 |
| ErrorControl | dword | 0 (Normal) | 0 Normal, 1 Critical. |
| RemainAfterExit | dword | 0 | Oneshot only: stay Completed after a successful exit. |
| SuccessExitCodes | multi_string | — | Non-zero exit codes treated as success. |
| ExecStartPre | multi_string | — | Commands run before the main binary, sequentially. §5.3 |
| ExecStartPost | multi_string | — | Commands run after readiness or successful exit. §5.3 |
| HookIdentity | string | — | Principal for the hook processes. Falls back to Identity. §4.1 |
| ExecReload | string | — | Reload command, or signal:<NAME>. Absent means SIGHUP. §6.5 |
| PreStartCheckTimeout | dword | 5 | Seconds before a filesystem check helper is killed. §3.5 |
| StartTimeout | dword | 30 | Seconds for the entire start sequence. §5.3 |
| StopTimeout | dword | 10 | Seconds after SIGTERM before SIGKILL. |
| WatchdogTimeout | dword | 0 | Seconds between expected WATCHDOG=1 pings; 0 disables. §6.6 |
| HealthCheck | string | — | Command run periodically. Exit 0 is healthy. §5.6 |
| HealthCheckInterval | dword | 30 | Seconds between health checks. |
| HealthCheckTimeout | dword | 5 | Seconds before a health check is killed and counted failed. |
| HealthCheckRetries | dword | 3 | Consecutive failures before the service is unhealthy. |
| RestartPolicy | dword | 1 (OnFailure) | 0 Never, 1 OnFailure, 2 Always. §6.4 |
| RestartMaxRetries | dword | 5 | Consecutive restarts before Failed. §6.4 |
| RestartWindow | dword | 120 | Seconds of sustained health that reset the restart counter. |
| RestartDelay | dword | 1 | Seconds before a restart; doubles each consecutive failure, capped at 60. |
| Readiness | dword | 0 (Notify) | 0 Notify, 1 Alive. Ignored for Oneshot. |
| NotifyAccess | dword | 0 (Main) | Who can send notifications. Main is the only mode. §10.5 |
| FdStoreMax | dword | 0 | Maximum descriptors held for the service; 0 disables the store. §10.6 |
| TimerPersistent | dword | 1 | Catch up a missed timer run after a reboot. §9.3 |
| TimerJitter | dword | 0 | Maximum random delay added to each firing. §9.4 |
| Environment | multi_string | — | KEY=VALUE pairs added to the environment. §5.5 |
| WorkingDirectory | string | / | Working directory for the process. |
| TTYPath | string | — | Terminal to attach as the standard streams and controlling terminal. §5.4 |
| TTYPrecedence | dword | 0 | Who wins that terminal when several services want it at once. Higher wins. Refused without a TTYPath. §11.6 |
| RuntimeDirectories | multi_string | — | Private directories under /run, created before the main process. |
| LimitNOFILE | dword | — | RLIMIT_NOFILE. |
| LimitCORE | dword | — | RLIMIT_CORE, in bytes. |
| Conditions | multi_string | — | Start-time conditions; failure skips the service. §3.5 |
| Asserts | multi_string | — | Start-time assertions; failure fails the service. §3.5 |
| DisplayName | string | — | Human-readable name for status display. |
| Description | string | — | What the service does. |
| ServiceSecurity | binary | inherit | Descriptor controlling runtime operations on the service. §4.6 |
3.2.1 Registry types #
| Schema type | Registry type |
|---|---|
| string | REG_SZ, UTF-8 |
| multi_string | REG_MULTI_SZ, an ordered list |
| dword | REG_DWORD, 32-bit unsigned |
| binary | REG_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 toLocalService.HookIdentity— empty is the same as absent, and falls back to the service'sIdentity.DisplayNameandDescription— 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.
| Trigger | Form | Meaning |
|---|---|---|
| Boot | boot | Start during the Phase 2 boot sequence. |
| Deferred boot | boot:settled | Start once the boot set has settled, or the deadline expires. §2.5 |
| Terminal handover | tty:released | Start when this service's TTYPath is let go of. §11.6 |
| Timer | timer:<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.
| Check | Form | Passes when |
|---|---|---|
| path | path:<path> | The path exists, of any type. |
| file | file:<path> | A regular file exists there. |
| directory | directory:<path> | A directory exists there. |
| registry | registry:<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.
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:
stopis accepted, so an administrator can drain it cleanly, using the cachedStopTimeout;start,restart, andreloadare rejected withUNKNOWN_SERVICE— there is no definition to work from;statusreports the current runtime state withdefinition_removedset, 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:
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.
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.
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.
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:
| Field | Value |
|---|---|
identity | The definition's Identity value, verbatim |
service | The 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 #
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:
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:
- Takes the caller's token, captured when the connection was accepted.
- 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. - 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}}. - 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 akacs.audit.access.checkedrecord withobject.kindservice,object.service.name, the caller's token, and the access requested and granted (§8.4). - 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 #
The generic mapping:
| Generic right | Maps to |
|---|---|
GENERIC_READ | SYSTEM_QUERY_STATUS |
GENERIC_WRITE | SYSTEM_RELOAD_CONFIG |
GENERIC_EXECUTE | SYSTEM_SHUTDOWN |
GENERIC_ALL | all 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.
/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.
- If the service names a
TTYPathand another service is holding that terminal, it goes to Skipped with causeTtyUnavailableand 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. - Conditions are evaluated. Any failure transitions the service to Skipped and abandons the start. Skipped satisfies dependents.
- If every condition passed and the service has asserts, they are
evaluated. Any failure transitions the service to Failed with cause
AssertionErrorand 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):
| Bytes | Content |
|---|---|
| 0–3 | little-endian u32, the child setup step identifier |
| 4–7 | little-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.
| Id | Step |
|---|---|
| 1 | Close the read end of the error pipe |
| 2 | Set the standard streams |
| 3 | Reset the signal environment |
| 4 | Install the service token |
| 5 | Set the resource limits |
| 6 | Set oom_score_adj |
| 7 | Set the working directory |
| 8 | reserved |
| 9 | Confirm NOTIFY_SOCKET |
| 10 | Inject stored descriptors |
| 11 | Exec the binary |
| 12 | Create a session |
| 13 | Acquire 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 #
- Close the write end of the error pipe.
- 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.
- 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 forREADY=1, then Active. - Simple with
Readiness=Alive: Active as soon as exec succeeds. - Oneshot: wait for the exit. Success is Completed; without
RemainAfterExitit 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:
| # | Step | Id |
|---|---|---|
| 1 | Close the read end of the error pipe | 1 |
| 2 | setsid() — only with a TTYPath | 12 |
| 3 | Set the standard streams | 2 |
| 4 | ioctl(TIOCSCTTY) — only with a TTYPath | 13 |
| 5 | Reset the signal environment | 3 |
| 6 | Set RLIMIT_NOFILE and RLIMIT_CORE | 5 |
| 7 | Set oom_score_adj | 6 |
| 8 | Install the KACS token, then close its descriptor | 4 |
| 9 | Change the working directory | 7 |
| 10 | Confirm NOTIFY_SOCKET is present in the environment | 9 |
| 11 | Inject stored descriptors from fd 3 upward | 10 |
| 12 | execve | 11 |
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:
| Variable | Value |
|---|---|
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.
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.
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:
- Marks it leaked, recording the path, the kind, and the time.
- Increments the service's cgroup generation, so the next start builds a fresh tree (§5.1).
- 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.leakedevent on the event stream, carrying the service, the sub-cgroup path (object.cgroup.path) and its kind (object.cgroup.type:service-tree,health,hooks, orhelper). When it was found is the event's own time.
The pull side survives the moment of detection, for anyone who was not watching:
-
A status query includes a
warningsarray, one entry per leak, each an object with the sub-cgroup path, its kind, and the time of detection: -
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.
| State | Process? | Satisfies dependents? | Meaning |
|---|---|---|---|
| Inactive | No | No | Not started, or stopped cleanly and not set to restart. |
| Starting | Maybe | No | Activation in progress: checks, hooks, fork, or the readiness wait. The process can not exist yet. |
| Active | Yes | Yes | Running and ready. |
| Reloading | Yes | Yes | Re-reading configuration. Still satisfies dependents. |
| Stopping | Briefly | No | SIGTERM sent, awaiting exit, or SIGKILL escalation. |
| Completed | No | Yes | Oneshot only. Exited successfully. |
| Backoff | No | No | A restart is pending; waiting out the backoff delay. |
| Failed | No | No | Exited abnormally with the restart policy exhausted or absent. |
| Abandoned | Yes, unkillably | No | SIGKILL sent and processes survived. Supervision has stopped, the cgroup is leaked. |
| Skipped | No | Yes | Conditions 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 #
- 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.
- 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.
- Only peinit transitions a service. The control socket produces operations; nothing outside peinit writes state.
- 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.
- Readiness is per start generation. The generation increments on every
transition into Starting,
and a
READY=1carrying 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.
| From | To | Trigger |
|---|---|---|
| Inactive | Starting | Start command, dependency resolution, or a timer trigger. |
| Inactive | Skipped | A condition check failed. |
| Inactive | Failed | Validation, assertion, cycle, or dependency failure — before any process existed. |
| Starting | Active | Readiness. Simple only: READY=1 received, or the process exists under Readiness=Alive. |
| Starting | Completed | Oneshot exited successfully. Without RemainAfterExit it passes through, releasing dependents, then goes Inactive. |
| Starting | Skipped | A condition failed after the activation had already entered Starting. |
| Starting | Failed | An assert failed after entering Starting; or a timeout, hook failure, setup failure, or an exit before readiness. |
| Starting | Backoff | A startup failure with the restart policy allowing a retry and budget remaining. |
| Starting | Stopping | An explicit stop canceling an in-progress start. A restart on a Starting service is queued rather than canceling. |
| Starting | Failed | The shutdown wave SIGKILLed a starting service. |
| Active | Reloading | ExecReload issued, or SIGHUP delivered. |
| Active | Stopping | Explicit stop, conflict eviction, a bound dependency stopping, or shutdown. |
| Active | Backoff | A crash, a watchdog timeout, or health check failure, with a restart allowed and budget remaining. |
| Active | Failed | The same three, with RestartPolicy=Never or the budget exhausted. |
| Active | Inactive | A Simple service exited successfully and RestartPolicy is not Always. Cause CleanExit. |
| Active | Backoff | A Simple service exited successfully and RestartPolicy=Always. Cause CleanExitRestart. |
| Reloading | Active | Reload resolved: READY=1, the detection window expiring, the extended wait expiring, or the reload command exiting — success or failure. |
| Reloading | Stopping | The same triggers as Active to Stopping. The reload is canceled. |
| Reloading | Backoff | The main process exited during the reload, with a restart allowed. |
| Reloading | Failed | The same, with no restart available. |
| Stopping | Inactive | The process exited after an explicit stop or a shutdown. |
| Stopping | Failed | The process exited after a conflict eviction or a bound dependency stopping. |
| Stopping | Abandoned | SIGKILL sent and main/ still populated after the post-kill deadline. |
| Stopping | Starting | An explicit start queued against a service that is still stopping. Cause ExplicitStart. |
| Backoff | Starting | The backoff delay elapsed. Cause RestartPolicy. |
| Backoff | Inactive | An explicit stop canceled the pending restart. |
| Backoff | Skipped | The 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. |
| Backoff | Failed | The backoff delay elapsed and peinit could not execute the relaunch. Cause InternalError. |
| Starting, Active, Reloading, Stopping | Failed | peinit could not carry out a step on the service and contained the error to it (§8.2). Cause InternalError. |
| Completed | Inactive | RemainAfterExit=0 and dependents released; or an explicit stop; or shutdown clearing it. |
| Completed | Starting | A start command or timer trigger re-running the Oneshot. |
| Failed | Starting | An explicit start, a bound dependency recovering, or a timer trigger. |
| Failed | Inactive | A reset command clearing the state. |
| Failed | Abandoned | A service SIGKILLed by the shutdown wave whose cgroup stayed populated past the post-kill deadline. |
| Abandoned | Inactive | A reset command. |
| Skipped | Inactive | A 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 #
| Cause | Leads to | Meaning |
|---|---|---|
ExplicitStart | Starting | An administrator, an OnFailure handler, or a boot plan started it. |
ExplicitStart | Inactive | An explicit start on a Skipped service, clearing it so the conditions are re-evaluated. |
DependencyStart | Starting | Started to satisfy another service's dependency. |
RestartPolicy | Starting | An automatic restart after a backoff delay. |
BindsToRecovery | Starting | A bound dependency returned to Active. |
Timer | Starting | A timer trigger fired. |
ExplicitStop | Stopping | An administrator requested a stop. |
ExplicitReload | Reloading, Active | A reload was issued and resolved. |
ExplicitReset | Inactive | An administrator cleared Failed, Abandoned, or Skipped. |
ConflictEviction | Stopping | A conflicting service started; this one lost. |
BindsToPropagation | Stopping | A bound dependency stopped. |
ShutdownWave | Stopping, Failed | The system is shutting down. Active and Reloading services go to Stopping; Starting services go straight to Failed. |
ProcessCrash | Failed, Backoff | The main process exited unexpectedly. |
CleanExit | Inactive | A Simple process exited successfully with a policy other than Always. |
CleanExitRestart | Backoff | A Simple process exited successfully under RestartPolicy=Always. |
ReadinessTimeout | Failed, Backoff | StartTimeout expired before readiness. |
WatchdogTimeout | Failed, Backoff | A keepalive did not arrive in time. |
HealthCheckFailure | Failed, Backoff | HealthCheckRetries consecutive failures. |
PreHookFailure | Failed, Backoff | An ExecStartPre hook exited non-zero, or its token failed, or the start timed out during hooks. |
ParentSetupFailure | Failed, Backoff | A parent-side failure before the fork. No child was created. |
PreExecFailure | Failed, Backoff | Post-fork setup failed before exec, reported through the error pipe. |
DependencyFailure | Failed | A Requires dependency entered Failed. |
RestartBudgetExhausted | Failed | RestartMaxRetries reached. |
CycleDetected | Failed | The service is part of a dependency cycle. |
ValidationError | Failed | The definition failed graph validation. |
AssertionError | Failed | A start-time assert failed. |
ConditionSkipped | Skipped | A start-time condition failed. |
TtyUnavailable | Skipped | Another service was holding the terminal this one names in TTYPath. §11.6 |
ProcessUnkillable | Abandoned | Processes survived SIGKILL. |
InternalError | Failed | peinit 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.
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.
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 #
| Policy | Value | Behavior |
|---|---|---|
| Never | 0 | Never restart. The service stays Failed. |
| OnFailure | 1 | Restart on a non-zero exit or a runtime failure. An exit matching SuccessExitCodes is not restarted. |
| Always | 2 | Restart 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.
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:
| Phase | Base | Ceiling |
|---|---|---|
| Starting | StartTimeout | StartTimeout × 4 |
| Stopping | StopTimeout | StopTimeout × 4 |
| Reloading | StartTimeout | StartTimeout × 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.
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 causeDependencyFailurewithout 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
BindsToPropagationfrom 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.
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 #
| Relationship | A missing target means |
|---|---|
Requires | The dependent is failed with DependencyFailure. |
BindsTo | The same — treated as a missing Requires. |
Wants | Silently dropped. |
Conflicts | Silently 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=Alivethat something else depends on hard.Alivereadiness 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 whoseIdentityis notSYSTEM. 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:
CycleDetectedValidationErrorDependencyFailure
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:
- Everything that
RequiresorBindsToit transitions to Failed with causeDependencyFailure. - Everything that
Wantsit is unaffected and starts normally. - 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:
- Collect the transitive
RequiresandBindsToclosure. - Collect the transitive
Wantsclosure, best-effort. - Validate the sub-graph — cycles, missing targets.
- Resolve conflicts, stopping whatever has to stop.
- Start the sub-graph with the same parallel algorithm. Dependencies
started this way carry cause
DependencyStartand operation sourceDependencyPropagation.
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.
| Boot | On-demand | |
|---|---|---|
| Members | Every boot-triggered root plus its closure | One requested service plus its closure |
| A missing hard-dependency target | Blocks the dependent | Blocks the dependent |
| A disabled hard-dependency target | Blocks the dependent | Blocks the dependent |
| A validation finding | The service is failed, others continue | The start fails |
| Multiple findings on one service | Only the highest-precedence one is reported | — |
| Conflicts | Two boot-triggered conflicting services fail both | The conflicting service is evicted |
| Context | One boot context | One context per explicit start |
| Failure of the whole build | Recovery mode | An 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 withValidationErrorand 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 #
| Publisher | Levels |
|---|---|
netd, as the role network | link → addressed → routed, defined by Peios Network Policy |
| timed | unsynchronised, 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
RequiresorBindsTo, 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.BindsTorequires 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
| State | Meaning |
|---|---|
| Created | The 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. |
| Running | Exec succeeded and the process is alive. |
| Completed | The process exited successfully — code 0, or one in SuccessExitCodes. |
| Failed | The process failed, or peinit classified the job failed before the fork because parent setup failed. |
| Abandoned | The 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:
idis assigned before the fork, so a job that never forks still has an identity.pidandpidfdland 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
SIGCHLDis 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=1before 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_nsrecords the classification time,failure_causerecords what went wrong, andpid,pidfd,started_at_ns,exit_codeandexit_signalall stay null. There was no process to have a PID or an exit status. exit_codeandexit_signalare populated only when peinit observed an exit — never both, since a process either exits or is killed.- For an Abandoned job,
ended_at_nsrecords 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 #
| Concern | Owner |
|---|---|
Restart policy, dependencies, health check schedule, ErrorControl | Service |
| Current state — Active, Failed, … | Service |
| PID, pidfd, exit code, exit signal | Job |
| Execution timestamps | Job |
| Identity and token | Job |
| cgroup assignment | Job |
| Log correlation | Job |
| Submitter, job descriptor, progress, retention | Submitted 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
| State | Meaning |
|---|---|
| Pending | Validated and queued, waiting on a precondition. |
| Running | Executing. |
| Completed | The goal was reached. Start: Active for Simple, Completed, or Inactive for Oneshot. Stop: the service is stopped. Reload: the reload resolved. |
| Failed | The 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). |
| Merged | Merged into an existing identical operation, whose identifier is recorded. |
| Canceled | Terminated while Pending. It never executed. |
| Aborted | Terminated 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:
| Source | Meaning |
|---|---|
Admin | A control client asked for it. |
Boot | The Phase 2 boot plan. |
Shutdown | The shutdown lifecycle. |
DependencyPropagation | A start operation created one for an unsatisfied dependency. |
RestartPolicy | A restart policy generated a start. |
Timer | A timer trigger fired. |
BindsToRecovery | A bound target returned to Active. |
BindsToPropagation | A bound target stopped. |
ConflictResolution | A conflict evicted the running service. |
OnFailure | A failed service's fallback handler. |
TtyRelease | A 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.
| Existing | New | Resolution |
|---|---|---|
| Start | Start | Merge |
| Stop | Stop | Merge |
| Reload | Reload | Merge |
| Restart | Start | Merge — 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 #
| Existing | New | Resolution |
|---|---|---|
| Start (Pending) | Stop | Cancel the start, create the stop |
| Start (Running) | Stop | Abort the start, create the stop |
| Start (Pending) | Restart | Cancel the start, queue the restart |
| Start (Running) | Restart | Queue the restart |
| Stop (either) | Start | Queue the start |
| Stop (either) | Restart | Queue the restart |
| Restart (Pending) | Stop | Cancel the restart, create the stop |
| Restart (Running) | Stop | Abort the restart, create the stop |
| Restart (either) | Restart | Queue |
| Reload (Pending) | Stop | Cancel the reload, create the stop |
| Reload (Running) | Stop | Abort the reload, create the stop |
| Reload (Pending) | Restart | Cancel the reload, create the restart |
| Reload (Running) | Restart | Abort the reload, create the restart |
| Anything (either) | Reset | Reject |
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 #
- Stop wins over start. An explicit stop always takes priority. The administrator said stop, so stop; a queued start can follow.
- Later supersedes earlier. Start then immediately stop means the stop wins and the start is canceled, recorded as superseded.
- 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— sourceDependencyPropagation. If one fails, the parent operation fails withDependencyFailure.Wants— sourceDependencyPropagation. If one fails, the parent continues.BindsTorecovery — sourceBindsToRecovery, created when a bound target returns to Active, for dependents sitting in Failed with causeBindsToPropagation.
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:
| Type | State | Action |
|---|---|---|
| Oneshot | Inactive, Completed, Failed | Create a start, source Timer. |
| Oneshot | Active, Starting | Set the pending flag. One catch-up run, no operation. |
| Simple | Inactive, Failed | Create a start, source Timer. |
| Simple | Active, Starting | No-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.
| Event | Adds |
|---|---|
peinit.operation.requested | — |
peinit.operation.started | — |
peinit.operation.ended | outcome.success, outcome.detail, object.operation.duration |
peinit.operation.merged | object.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.suppressedwhen the fallback chain guard trips;peinit.graph.validation.failedandpeinit.graph.validation.warnedfor validation findings, one per finding, andpeinit.boot.downgradedfor each finding that forced Safe mode;peinit.config.reload.appliedfor an explicitreload-configand for the reload that ends the boot window, andpeinit.config.reload.deferredfor a reload during it (§3.7);peinit.notify.rejectedfor a refused notification datagram, andpeinit.fd-store.rejectedfor a refused descriptor;peinit.notify.status.reported,.errno.reported,.exit-status.reported,.stopping.reportedand.progress.reportedfor the event-emitting notification fields, the last at most once a second for each activation (§10.5);peinit.cgroup.leakedthe first time a sub-cgroup is found still populated after its post-kill deadline (§5.7);peinit.graph.operation.endedfor a graph member's terminal outcome;peinit.recovery.enteredfor the reason peinit dropped to a recovery shell (§2.8);peinit.critical-service.failedandpeinit.service.abandonedfrom the shutdown path (§12);peinit.service.reload.timed-outfor 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:
| Checked | Context | The 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 binary | object.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_PEERPIDFDat accept; the token comes frompeios_token_open_processon that pidfd withQUERY | 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
submitmessage throughKACS_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, atQUERY | 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:
- Parse and validate the definition against the attachment count
(below). A malformed definition is
INVALID_ARGUMENTSbefore any identity work is done. - Refuse during shutdown with
INVALID_STATE. The other four commands keep working while the system goes down. - Establish the job identity, as above.
- 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 isQUOTA_EXCEEDED. A job stops counting the moment it is terminal, not when its retained record is dropped. - Build the job's descriptor: the one the submission supplied in SDDL, used as given, or the default (below).
- Create the record, the entry and the launch queue entry, in one
SupervisorWorktransaction.
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 #
| Field | Default | Validation |
|---|---|---|
image_path | required | Absolute, 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 | "" | |
timeout | 0, no limit | Non-negative integer, seconds. |
stop_timeout | 10 | Positive integer, seconds. |
readiness | none | none or notify. |
readiness_timeout | 30 | Non-negative integer, seconds. |
success_exit_codes | [] | Integers 0–255. |
descriptors | [] | One name per injected descriptor; non-empty, no :. |
output | false | Requires at least one attached descriptor. |
security_descriptor | the default | SDDL 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.
| Right | Bit |
|---|---|
JOB_QUERY | 0x0001 |
JOB_STOP | 0x0002 |
JOB_SIGNAL | 0x0004 |
JOB_ALL_ACCESS | 0x0007 |
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:
| Field | Effect |
|---|---|
READY=1 | For 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=1 | Recorded, so a later stop sends no termination signal. |
| Everything else | Ignored: 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:
| Deadline | Due | Action |
|---|---|---|
Timeout | started_at + timeout | Begin a stop with cause timeout. |
ReadinessTimeout | started_at + readiness_timeout, for a notify job not yet ready | Begin a stop with cause readiness_timeout. |
StopKill | stop requested + stop_timeout | SIGKILL the job's cgroup. |
PostKill | kill + PostKillTimeout | Abandon (below), or re-arm if the cgroup is empty but the exit not yet reaped. |
CgroupCleanup | terminal + PostKillTimeout | Retry 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
backupdruns 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:
| Form | Meaning | Shown as |
|---|---|---|
PROGRESS=N | Counting, 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/T | N 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.
| Field | Form | Default if omitted |
|---|---|---|
| DayOfWeek | weekday names | any day |
| Date | Year-Month-Day | *-*-* |
| Time | Hour:Minute:Second | 00:00:00 |
| Second | the :Second of Time | :00 |
| Timezone | an IANA name | system-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/stepmatches the value and every multiple of the step above it, so0/15in the minute field is 0, 15, 30 and 45.start..end/stepwalks 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 #
| Shortcut | Equivalent |
|---|---|
minutely | *-*-* *:*:00 |
hourly | *-*-* *:00:00 |
daily | *-*-* 00:00:00 |
weekly | Mon *-*-* 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/Londonskips 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 #
| Expression | Meaning |
|---|---|
*-*-* 02:00:00 | Every day at 2am, system-local. |
Mon *-*-* 00:00:00 | Every Monday at midnight. |
*-*-1,15 12:00:00 | The 1st and 15th, at noon. |
*-*~01 00:00:00 | The last day of each month, at midnight. |
Mon..Fri *-*-* 09:00:00 | Weekdays at 9am. |
*-*-* *:00/15:00 | Every fifteen minutes. |
*-*-* 02:00:00 Europe/London | Every day at 2am London time. |
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:
- Read the last-run timestamp.
- Compute the next scheduled firing after it.
- If that time has already passed, at least one run was missed: fire once, immediately.
- 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.
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.
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:
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.
- The shutdown gate. If peinit is shutting down, everything except
status,list,operation-status,boot,job-status,job-listandjob-stopis rejected.bootstays 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. - Resolve the target. A command naming no definition, and no
addressable definition-removed entry, returns
UNKNOWN_SERVICE; one naming no submitted job peinit holds returnsUNKNOWN_JOB. peinit does not synthesise a descriptor for something that does not exist. - 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).
- On denial, return
ACCESS_DENIED. The decision is recorded by KACS, askacs.audit.access.checkednaming 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). - On grant, classify the command against the service's state (§10.3) and act.
10.2.1 Rights #
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.
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.
startcreates 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
stopcancels 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.restartreplaces the automatic restart with the administrator's. A Restart operation with sourceadminis queued Pending and honors the remaining delay exactly as a deferredstartdoes; 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 deferredstartalready pending is canceled with reasonsuperseded_by_restart, and a secondrestartmerges 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.reloadandresetare 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
startimmediately. - 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:
- 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=Mainthe 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:
- If
FdStoreMaxis 0, peinit logs the rejection and closes the descriptor. - If the store already holds
FdStoreMaxentries, peinit logs the rejection and closes the descriptor. The existing store is not modified — a full store does not evict. FDNAME=<name>names it; an absent or empty name meansstored.FDPOLL=0marks 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
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):
- 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. LISTEN_FDSis set to the count.LISTEN_FDNAMESis set to a colon-separated list of names in the same order as the descriptor numbers.- 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.
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 :
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:
| Wait | Set by | Answered when |
|---|---|---|
| Submit | submit | The job leaves created: exec confirmed, or the launch failed. |
| Wait | wait | The condition holds — terminal, or ready-or-terminal. |
| Stop | stop with wait | The 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 | When |
|---|---|
normal | A Full boot. |
requested | A Safe boot asked for with peios.safemode=1. |
safe_mode_downgrade | A 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.
confirmed | waiting_on | confirms_at | confirm_error | Meaning |
|---|---|---|---|---|
| false | the Critical services not holding | null | null | The boot is waiting for them. |
| false | empty | a time | null | Every Critical service holds; if they keep holding, the boot counts then. |
| true | empty | null | null | The boot has counted, and the counter is 0. |
| false | empty | null | why | The 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:
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/resetreturns anoperation_id— a GUID you can poll. Conflict resolution between concurrent commands happens at the operation layer, which is why two simultaneousstarts merge instead of colliding.
10.9.2 Reading status #
status returns the full picture for one service:
display_nameanddescriptionare the definition's, ornull.stateandcauseare the lifecycle pair — read them together.status_textis the latestSTATUS=string the service sent through sd_notify (nullif never sent; cleared on each restart).progressis how far the service last said it had got, fromPROGRESS=andPROGRESS_UNIT=:{"current": 3, "total": 10, "bounded": true, "unit": "items"}, withtotalandunitnullwhen it didn't say them.nullif it never sent one; cleared on each restart.current_jobandcurrent_operationare the job and operation GUIDs, ornull.healthishealthy,unhealthy,unknown, ornull(no health check).definition_removedistruewhen the definition was deleted but an instance is still draining.warningslists leaked sub-cgroups and other operator-relevant notices.timershas one entry for each timer trigger, described below.grantedis what you can do to this service, as peinit checks it: the rights the service's permissions give you, out ofquery_status,start,stopandinterrogate(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:
scheduled_atis the schedule's next occurrence.fires_atis when the timer will actually fire. It is later thanscheduled_atby the random delayTimerJitterdrew for this firing.last_fired_atis when it last fired, ornullif it has not fired since peinit started and has no recorded run.not_armedis set only for a schedule peinit refused, such as one that never comes round. It gives the reason, and the times are thennull.
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:
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":
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_REALTIMEtimestamp, - 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.
| Key | Default | Minimum | Meaning |
|---|---|---|---|
Machine\System\Init\PreEventdBuffer | 1048576 | 4096 | Bytes 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.
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.
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.
- Start sending to eventd's log datagram socket, at the path from
Machine\System\eventd\LogSocketPath. - 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.
- Switch to real-time forwarding — new output sent as it arrives.
- 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 :
| Key | Type | Content |
|---|---|---|
origin | string | The service name, or the hook identifier. |
is_error | bool | True for stderr. |
message | string | The line. |
timestamp | uint | Nanoseconds, wall clock. |
job_id | bin | The 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.
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.
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/consoleand/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.
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:
| Holding | Released |
|---|---|
| Starting, Active, Reloading, Stopping, Backoff | Inactive, 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\) | Default | Limits |
|---|---|---|
MaxLogLineLength | 8192 | Bytes per line; longer lines are truncated with a [truncated] marker. |
MaxLogBufferPerService | 65536 | Bytes buffered per service pipe before back-pressure. |
Two mechanisms back these up:
- A per-readable-event budget.
LogReadBytesPerEventbounds 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.
11.7.4 The eventd handoff #
When eventd reaches Active, peinit switches from buffering to forwarding:
- It begins sending to eventd's log datagram socket (path from
Machine\System\eventd\LogSocketPath). - 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.
- It switches to real-time forwarding — new output goes out as it arrives.
- 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):
| Type | Effect |
|---|---|
poweroff | Stop everything, unmount, power off. |
reboot | Stop everything, unmount, reboot. |
halt | Stop everything, unmount, halt — the CPU stops, the system stays powered. |
12.1.2 Signals #
| Signal | Meaning |
|---|---|
| SIGINT | Reboot. The kernel sends it on Ctrl+Alt+Del. |
| SIGTERM | Poweroff. PID 1 cannot be killed by it but can choose to act on it. |
| SIGPWR | Poweroff. 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
ShutdownWavewhile post-kill verification is pending. A cgroup still populated after the post-kill timeout takes the service to Abandoned with causeProcessUnkillableand 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:
- Each eligible service receives SIGTERM. Already-stopping ones do not.
- Each has
StopTimeoutto exit. - On expiry, SIGKILL to the service's entire cgroup.
- 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, orBindsToPropagation.
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 #
| Key | Default | Meaning |
|---|---|---|
Machine\System\Boot\ShutdownTimeout | 90 | Seconds for the whole sequence. |
Machine\System\Boot\PostKillTimeout | 5 | Seconds 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 #
- Snapshot the mount table first, from
/proc/self/mountinfo. - 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.
- Process in descending path depth, so children go before parents.
- A mount point already gone is a successful no-op.
- On failure, attempt a read-only remount. If that fails too, record it and continue.
- 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.
sync(). Called on all three paths — graceful, forced, and Critical reboot.reboot(2)withRB_POWER_OFF,RB_AUTOBOOT, orRB_HALT_SYSTEM.- 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 #
| Signal | Behavior |
|---|---|
| SIGCHLD | Reap children with waitpid. Match them to tracked jobs; also reap orphans belonging to nothing. |
| SIGINT | Reboot. Three within five seconds forces one. |
| SIGTERM | Poweroff. |
| SIGPWR | Poweroff. |
| SIGHUP | Ignored. PID 1 has no controlling terminal. |
| SIGPIPE | Ignored. 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.
| Path | Stop waves | Seed save | Unmount | Sync | Final action |
|---|---|---|---|---|---|
| Graceful | Yes | Yes | Yes | Yes | Yes |
| Forced — three SIGINTs | No, SIGKILL everything | No | No | Yes | Yes |
| Critical service failure | No | No | No | Yes | Yes |
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 capability | Used for |
|---|---|
SeCreateTokenPrivilege | Minting SYSTEM tokens for platform services during bootstrap, before authd exists (§4.2). |
SeTcbPrivilege | Requesting 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. |
SeAuditPrivilege | Writing 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 duplication | Turning 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 creation | Fork and exec, inherent to PID 1. |
| cgroup management | Creating and destroying trees under /sys/fs/cgroup/peinit/. |
| Signal delivery | SIGTERM and SIGKILL to managed processes. |
| Mount operations | The 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.
13.3 The Attack Surface
Peios / Reference / peinit / Security
| Surface | Reachable by | Controls | Protected by |
|---|---|---|---|
| Control socket | Every authenticated principal, by default | Service lifecycle, shutdown, observing, and stopping jobs | The peer token and AccessCheck against the target's descriptor for every command; a per-user connection limit |
| Jobs socket | Every authenticated principal, by default | Running a program under supervision as an identity the submitter holds; managing the jobs it submitted | The 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 socket | Anything that can connect | Service readiness, watchdog, stored descriptors | The socket inode's descriptor, then PID matching verified through a pidfd, plus the start generation |
| Registry keys | Anything with registry access | Definitions, triggers, configuration | Registry key descriptors, enforced by LCS |
Machine\System\Init\EnvVars\ | Anything with registry access | The environment of every service | That key's descriptor, and nothing else — variable names are not filtered |
| Service cgroups | peinit | Process tracking and clean kill | Ownership of the hierarchy |
| Phase 1 mounts | peinit | Virtual filesystem availability | Hardcoded, no external input |
/lcl/policy/autorun.d | Whatever can write it | Arbitrary code as SYSTEM in early boot | The directory's descriptor |
| Boot attempt counter | Whatever can write /.peinit/ | Recovery mode entry | That 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:
| Cgroup | Consequence |
|---|---|
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:
| What | Where | How |
|---|---|---|
| Boot attempt counter | /.peinit/boot-attempts | A plain integer, rewritten each boot. |
| Local machine ID | /lcl/etc/machine-id | Temporary file, flush, rename. |
| Random seed | /var/state/peinit/random-seed | Temporary 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 #
| Key | Purpose | Defined in |
|---|---|---|
Machine\System\Services\ | Parent key. Each child key is one service. | §3.2 |
Machine\System\Services\SchemaVersion | Schema version guard. REG_DWORD, 1. Created by peinit if absent. | §2.3, §3.2 |
Machine\System\Services\ServiceSecurity | The descriptor inherited by definitions that carry none. REG_BINARY. | §4.6 |
Machine\System\Services\<name> | One service definition. | §3.2 |
Machine\System\Services\<name>\Provides | Roles 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>\LastTimerRun | Last-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 #
| Key | Type | Default | Purpose | Defined in |
|---|---|---|---|---|
Machine\System\Boot\MaxParallelStarts | dword, > 0 | 10 | Services starting concurrently during boot. Zero, a type mismatch, or a malformed payload is invalid and enters recovery. | §2.5 |
Machine\System\Boot\BootSuccessGrace | dword | 30 | Seconds every Critical service has to hold a dependent-satisfying state before the boot counts as successful. | §2.5 |
Machine\System\Boot\SettleTimeout | dword | 5 | Seconds to wait for the boot set to settle before starting boot:settled services regardless. Zero is legal. | §2.5 |
Machine\System\Boot\ShutdownTimeout | dword | 90 | Seconds for the entire graceful shutdown. | §12.2 |
Machine\System\Boot\PostKillTimeout | dword | 5 | Seconds 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 #
| Key | Type | Default | Purpose | Defined in |
|---|---|---|---|---|
Machine\System\Init\ControlSecurity | binary | SYSTEM and Administrators, every right; Authenticated Users, SYSTEM_QUERY_STATUS | The descriptor for system-level control operations and the boot query. | §4.7 |
Machine\System\Init\MaxControlConnectionsPerUser | dword | 16 | Concurrent control socket connections one caller's user SID can hold. SYSTEM is exempt. | §10.1 |
Machine\System\Init\MaxControlConnections | dword | 256 | Concurrent control socket connections in all. | §10.1 |
Machine\System\Init\MaxRequestSize | dword | 65536 | Maximum control request size, in bytes. | §10.1 |
Machine\System\Init\ConnectionTimeout | dword | 30 | Seconds before an idle control connection is closed. | §10.1 |
Machine\System\Init\MaxJobsConnections | dword | 64 | Concurrent jobs socket connections. | §10.7 |
Machine\System\Init\MaxJobMessageSize | dword | 32768 | Maximum jobs socket message content, in bytes. | §10.7 |
Machine\System\Init\JobsConnectionTimeout | dword | 30 | Seconds before an idle jobs connection is closed. | §10.7 |
Machine\System\Init\MaxJobsPerSubmitter | dword | 64 | Live submitted jobs one submitter SID can hold. SYSTEM is exempt. | §8.5 |
Machine\System\Init\MaxLogLineLength | dword | 8192 | Bytes per output line before truncation. Minimum 256; below that the default is used and a warning logged. | §11.3 |
Machine\System\Init\MaxLogBufferPerService | dword | 65536 | Pipe capacity per service, applied with F_SETPIPE_SZ. Minimum 4096 (one page, the kernel's own floor). | §11.3 |
Machine\System\Init\LogReadBytesPerEvent | dword | 16384 | Bytes drained from one output pipe per readable event. Minimum 512. | §11.3 |
Machine\System\Init\PreEventdBuffer | dword | 1048576 | Bytes of output retained before eventd is available. Applied at boot and on reload. Minimum 4096. | §11.2 |
Machine\System\Init\EnvVars\ | parent key | empty | Variables 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 key | empty | Boot-time path provisioning entries. | §2.4 |
Machine\System\Init\ProvisionedPaths\<name>\Kind | string | — | directory or file. Required. | §2.4 |
Machine\System\Init\ProvisionedPaths\<name>\Path | string | — | The absolute path. Required. | §2.4 |
Machine\System\Init\ProvisionedPaths\<name>\Security | binary | built-in | The descriptor to apply. | §2.4 |
Machine\System\Init\ProvisionedPaths\<name>\Required | dword | 0 | If 1, a failure enters recovery before Phase 2. | §2.4 |
A.4 Other subsystems #
| Key | Type | Purpose | Defined in |
|---|---|---|---|
Machine\System\eventd\LogSocketPath | string | Where 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 #
| Path | Purpose |
|---|---|
/usr/bin/peinit2 | Where peinit is installed in package storage. |
/bin/peinit2 | The runtime path the kernel init= names. |
/sbin/registryd | The compiled-in registryd image path. |
/var/state/loregd/Machine.hive | The machine hive, passed to registryd. |
/var/state/loregd/Users.hive | The users hive, passed to registryd. |
/.peinit/ | peinit's own state directory on the root filesystem. |
/.peinit/boot-attempts | The boot attempt counter. |
/lcl/etc/machine-id | The local machine identifier. |
/var/state/peinit/random-seed | The persisted entropy seed. |
/lcl/policy/autorun.d | Phase 1 autorun scripts. |
/run/services/peinit/control.sock | The control socket. |
/run/services/peinit/notify.sock | The notification socket, by default. |
/run/services/peinit/jobs.sock | The 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/rtc0 | The hardware clock, in that order of preference. |
/dev/console | Where peinit writes its own messages. |
/bin/recsh, /bin/sh | The recovery shell, in that order of preference. |
B.2 Timeouts and limits #
| Constant | Value | Meaning |
|---|---|---|
| registryd setup timeout | 30 s | Process setup, driven synchronously in Phase 1. |
| registryd readiness timeout | 30 s | Waiting for READY=1 in Phase 1. |
| Reload detection window | 2 s | Waiting for RELOADING=1 after a reload signal. Bounded above by the operation deadline. |
| Restart delay cap | 60 s | The ceiling on exponential backoff. |
| Timeout extension cap | ×4 | The multiple of a phase's base timeout an extension can reach. |
| Operation retention | 60 s | How long a terminal operation is kept before being dropped. |
| Submitted job retention | 60 s | How long a terminal submitted job's entry answers status before being dropped. |
peinit.job.status.reported interval | 1 s | The least spacing between two peinit.job.status.reported events for one job. |
Submitted job stop_timeout | 10 s | The default, per submission. |
Submitted job readiness_timeout | 30 s | The default, per submission. |
| Submitted job argv and environment | 2 MiB | The bound on a definition's arguments and environment together. |
| Boot attempt threshold | 3 | The default, overridden by peios.bootattempts=. |
OnFailure chain depth | 16 | The maximum handler chain from one originating failure. |
| Pre-eventd buffer | 1 MiB | The compiled-in buffer capacity. |
| Notification datagram | 64 KiB | The receive buffer size. |
| Descriptors per datagram | 64 | The control message buffer capacity. |
| Random seed | 512 bytes | Written at shutdown. Restoring accepts 1–4096 bytes. |
| Control listen backlog | 32 | |
| Jobs listen backlog | 32 | |
| Descriptors per jobs message | 64 | Including an output sink. |
| Tokens per jobs message | 1 | |
| First injected descriptor | 3 | Where stored descriptors are placed. |
| Final action retry | 1 s | The minimum interval between reboot(2) retries. |
B.3 Environment #
| Variable | Value |
|---|---|
PATH | /sbin:/bin — the compiled-in base for every service. |
The recovery shell additionally receives TERM=linux and HOME=/.
B.4 Kernel command line #
| Parameter | Effect |
|---|---|
peios.safemode=1 | Force Safe mode. |
peios.recovery=1 | Force recovery mode. |
peios.bootattempts=N | The recovery threshold; 0 disables the check. |
peios.quiet=N | Console verbosity: 0, 1, or 2. |
peios.notifysocket=PATH | Override the notification socket path. |
B.5 Descriptors peinit applies #
| Where | SDDL |
|---|---|
/dev/shm, /run, /sys/fs/cgroup after mounting | O: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 Security | O:SYG:SYD:(A;;GA;;;SY)(A;;GA;;;BA)(A;;FR;;;BU) |
A service's /run/<name> runtime directory | O:SYG:SYD:(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;<service SID>) |
| The random seed file | O:SYG:SYD:(A;;GA;;;SY) |
| The default ServiceSecurity | O:SYG:BAD:(A;;0x000F;;;SY)(A;;0x000F;;;BA)(A;;0x0001;;;AU) |
| The default ControlSecurity | O:SYG:BAD:(A;;0x0007;;;SY)(A;;0x0007;;;BA)(A;;0x0004;;;AU) |
| The control socket inode | O:SYG:SYD:(A;;GA;;;SY)(A;;GA;;;BA)(A;;FW;;;AU) |
| The jobs socket inode | O:SYG:SYD:(A;;GA;;;SY)(A;;GA;;;BA)(A;;FW;;;AU) |
A submitted job with no security_descriptor | Owner and group the submitter; (A;;0x0007;;;<submitter>)(A;;0x0007;;;SY)(A;;0x0007;;;BA) |
B.6 Access rights #
| Right | Bit |
|---|---|
SERVICE_QUERY_STATUS | 0x0001 |
SERVICE_START | 0x0002 |
SERVICE_STOP | 0x0004 |
SERVICE_INTERROGATE | 0x0008 |
SERVICE_ALL_ACCESS | 0x000F |
SYSTEM_SHUTDOWN | 0x0001 |
SYSTEM_RELOAD_CONFIG | 0x0002 |
SYSTEM_QUERY_STATUS | 0x0004 |
JOB_QUERY | 0x0001 |
JOB_STOP | 0x0002 |
JOB_SIGNAL | 0x0004 |
JOB_ALL_ACCESS | 0x0007 |
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:
| Condition | Reason |
|---|---|
| No hive arguments at all | At least one hive is required. |
An argument with no = | Not a hive declaration. |
| An empty hive name or empty path | Neither is meaningful. |
| A relative database path | Paths are required to be absolute. |
A hive name containing \, /, or NUL | These are path separators and terminators in the registry namespace. |
The hive name CurrentUser, in any case | Reserved by the kernel as a per-token alias; no source can claim it. |
| Two declarations of the same hive name | Duplicates 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 reportwal, 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_registryreturns 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.
SIGTERMandSIGINTare 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 :
(
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:
| State | behavior |
|---|---|
No schema_version table | The database is new. loregd creates the persistent tables, the volatile tables, and inserts version 1, all in one transaction. |
| Version equals 1 | Normal startup. |
| Version greater than 1 | Startup 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 1 | Startup 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 #
(
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
);
| Column | Meaning |
|---|---|
guid | The 16-byte primary key. The kernel supplies it in creation requests; loregd generates the first-boot root GUID. |
name | The key's own name component, with case preserved as written. |
name_folded | The folded form of name (§3.4), used for case-insensitive lookup. |
parent_guid | The parent key's GUID; null for the hive root, which is how the root is identified. |
sd | The security descriptor, in binary self-relative form. Opaque to loregd. |
volatile | 1 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). |
symlink | 1 if the key is a symbolic link. |
last_write_time | Unix nanoseconds. |
3.2.2 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)
);
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.
| Column | Meaning |
|---|---|
parent_guid | The parent key's GUID. |
child_name | The child name with case preserved. |
child_name_folded | The folded form, which is what the primary key uses; so a name collides case-insensitively within a layer. |
layer | The layer name. Compared as binary, so layer names are case-sensitive, unlike key names. |
target_type | 0 for a GUID entry (the key exists in this layer), 1 for HIDDEN (a tombstone masking lower layers). |
target_guid | The target key's GUID when target_type is 0; null for HIDDEN. |
sequence | The 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 #
[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)
);
| Column | Meaning |
|---|---|
key_guid | The key this value belongs to. |
name | The value name, case preserved. The empty string is the key's default value. |
name_folded | The folded form; also the empty string for the default value. |
layer | The layer this value entry belongs to. |
type | The registry value type; REG_SZ is 1, REG_DWORD is 4, and so on. REG_TOMBSTONE (0xFFFF) marks a per-value tombstone. |
data | The value payload; null for a tombstone. |
sequence | The 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 #
(
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.
| Connection | Count | Used for |
|---|---|---|
| Write | One per hive | Every mutating operation, and every read inside a bound read-write transaction. |
| Read pool | min(NumCPU, 16), at least 1 | Reads outside a transaction. Selected round-robin. |
| Snapshot | One per active read-only transaction | Reads 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=walon 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_KEYstores 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_KEYevicts immediately outside a transaction, or through a commit hook inside one.
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:
| Response | Sorted by |
|---|---|
RSI_LOOKUP path entries | layer, then sequence |
RSI_ENUM_CHILDREN children | folded child name |
RSI_ENUM_CHILDREN per-child entries | layer, then sequence |
RSI_QUERY_VALUES value entries | folded value name, then layer, then sequence |
RSI_QUERY_VALUES blanket tombstones | folded layer name, then sequence |
RSI_DELETE_LAYER orphan GUIDs | ascending GUID, compared bytewise |
| Key-metadata blocks, in any response | ascending 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_VALUESresponse comes from its ownUNION ALL, separate from the value entries it travels beside, and takes the same order they do. - The orphan-GUID array in an
RSI_DELETE_LAYERresponse 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:
| Bit | Value | Field |
|---|---|---|
| 0 | 0x01 | sd |
| 1 | 0x02 | last_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:
| Status | Value | Returned when |
|---|---|---|
RSI_OK | 0 | The operation succeeded. Also returned by the idempotent deletions when their target was already absent. |
RSI_NOT_FOUND | 1 | A named key GUID exists in neither store, or resolves to no registered hive. Also an update matching no row. |
RSI_ALREADY_EXISTS | 2 | A 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_ERROR | 3 | A 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_BUSY | 6 | BEGIN 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_INVALID | 7 | An 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_FAILED | 8 | A 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:
| Crate | Responsibility |
|---|---|
eventd-core | Bounded queues, routing, receipts, and SQLite stores |
eventd | Kernel attachment, ingestion, policy, lifecycle, and queries |
eventd-client | Query wire format, client state, and shared access constants |
evctl | Command-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:
| Concern | Owner |
|---|---|
| Event emission and ring-buffer transport | Kernel mediated event subsystem (KMES) |
| Event type names and payload meanings | The emitting component |
| Token and access-check primitives | Kernel access control subsystem (KACS) |
| Registry storage and access | Layered configuration subsystem (LCS) and loregd |
| Service lifecycle and output forwarding | peinit |
| Persistent stores and query execution | eventd |
| Shared userspace wire interfaces | Peios 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.
- Drain. One thread per CPU reads events from that CPU's ring buffer, following the lock-free read protocol PSPK specifies (§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).
- 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).
- 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_posstarts attail_poson first attachment, so eventd begins at the oldest surviving event rather than at the newest.- The drain loop loads
write_poswith acquire ordering, checkstail_posfor lapping, validates the event's structural integrity, and advancesread_posbyevent_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_wakeand 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:
- Records the sequence number of the last event it has successfully handed off.
- Finishes draining the old buffer to its now-frozen
write_pos, updating that sequence number as it goes. - Calls
kmes_attachagain 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:
| Relation | Result |
|---|---|
| shards == CPUs | one shard per CPU, the 1:1 case |
| shards < CPUs | several CPUs share a shard |
| shards > CPUs | a 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.
- 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
MaxBatchSizeevents MaxBatchLatencyMshas 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>
- Otherwise it keeps reading and inserting.
- 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 #
| Condition | Type |
|---|---|
| Lost events detected on a CPU | eventd.events.lost (§2.5) |
| eventd started and attached to KMES | eventd.daemon.started |
| Graceful shutdown, once everything read is committed | eventd.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 runtime | eventd.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.
| Column | Type | Contents |
|---|---|---|
id | INTEGER PRIMARY KEY | SQLite rowid, monotonic within the shard. |
boot_id | BLOB NOT NULL | 16-byte boot ID GUID in PCDS binary layout. |
timestamp | INTEGER NOT NULL | Nanoseconds 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_id | INTEGER | From the KMES header. Null for daemon-wide synthetic events; populated for gap records (§2.5). |
sequence | INTEGER | Per-CPU, per-boot sequence from the KMES header. Null for every synthetic event. |
origin_class | INTEGER | 0 userspace, 1 KMES, 2 KACS, 3 LCS, 4 NTFE. From the header, as written. Null for synthetic events. |
event_type | TEXT NOT NULL | From the header; or one of the five types eventd writes itself (§2.6). |
effective_token_guid | BLOB | 16-byte GUID for the effective token at emission. Null for synthetic events; the null GUID when identity was unavailable at emission. |
true_token_guid | BLOB | 16-byte GUID for the process's primary token. Null for synthetic events. |
process_guid | BLOB | 16-byte GUID for the emitting process. Null for synthetic events. |
payload | BLOB | MessagePack. 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:
| Field | Column |
|---|---|
event.time | timestamp |
event.sequence | sequence |
event.cpu | cpu_id |
event.type | event_type |
event.boot.guid | boot_id |
emitter.class | origin_class |
emitter.token.guid | effective_token_guid |
emitter.true-token.guid | true_token_guid |
emitter.process.guid | process_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:
| Column | Type | Contents |
|---|---|---|
event_type | TEXT PRIMARY KEY | A 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:
| Column | Type | Contents |
|---|---|---|
boot_id | BLOB NOT NULL | 16-byte kernel boot ID. |
cpu_id | INTEGER NOT NULL | Logical KMES CPU identifier. |
first_sequence | INTEGER NOT NULL | First accounted sequence, inclusive. |
last_sequence | INTEGER NOT NULL | Last 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:
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:
| Column | Type | Contents |
|---|---|---|
key | TEXT PRIMARY KEY | Metadata key. |
value | TEXT NOT NULL | Metadata value. |
with two required entries: schema_version, and created_at as a UTC
timestamp formatted YYYY-MM-DDTHH:MM:SSZ.
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 #
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 #
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 #
| Field | Type | Contents |
|---|---|---|
buffer.cpu | unsigned integer | The CPU whose ring the gap was found on. |
loss.sequence | unsigned integer | First missing sequence number. |
loss.sequence-last | unsigned integer | Last missing sequence number. |
loss.count | unsigned integer | How many are missing. |
loss.preceding-time | timestamp | The 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 #
| Field | Type | Contents |
|---|---|---|
config.key.path | string | Always Machine\System\eventd. |
config.name | string | The value's name under config.key.path. |
config.type-previous | unsigned integer | The 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-previous | unsigned integer | The value before. Present exactly when config.type-previous is. |
config.type | unsigned integer | The registry type the value has now, numbered the same way. Absent when the change removed the value. |
config.value | unsigned integer | The 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 #
| Field | Type | Contents |
|---|---|---|
store.kind | string | event, log, or metric. |
store.shard | unsigned integer | The shard, for the event store. Absent for the log and metric stores, which are not sharded. |
outcome.detail | string | Human-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:
- WAL mode,
PRAGMA journal_mode=WAL PRAGMA synchronous=FULL- the
events,event_types,receipt_ranges, andmetadatatables (§3.1) - the
idx_events_timestampindex - the
schema_versionandcreated_atentries
3.3.4 Opening an active shard #
- Open in WAL mode.
- Set synchronous to FULL.
- Read and verify
schema_version. Missing or unrecognized is a startup failure. No migration is attempted. - Verify structural integrity — the required tables and write-time indexes exist. Failing this, with SQLite reporting no corruption, is a startup failure.
- 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).
desired_indexes — the computed desired index set.
| Column | Type | Contents |
|---|---|---|
field_path | TEXT PRIMARY KEY | Header field or payload path, read back like a counter's. |
priority | INTEGER NOT NULL | Rank; lower is higher priority. |
is_expression | INTEGER NOT NULL | 1 for a payload expression index, 0 for a column index. |
sequence_checkpoints — diagnostic only.
| Column | Type | Contents |
|---|---|---|
boot_id | BLOB NOT NULL | The boot the checkpoint applies to. |
cpu_id | INTEGER NOT NULL | CPU identifier. |
sequence | INTEGER NOT NULL | Last committed sequence for that pair when written. |
updated_at | INTEGER NOT NULL | When 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.
| Column | Type | Contents |
|---|---|---|
key | TEXT PRIMARY KEY | Metadata key. |
value | BLOB NOT NULL | Strings 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 #
- Open
eventd-meta.db, creating it if absent. - Verify the schema version and required
metaentries; recreate from defaults on failure. - Load
index_countersinto memory. - Load
desired_indexesinto memory. - Load
sequence_checkpoints, for diagnostics only. - 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:
- 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 #
| Store | Column |
|---|---|
| Event | events.boot_id, every row |
| Log | logs.boot_id, every row |
| Metric | samples.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.
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
LogMaxBatchSizerecords LogMaxBatchLatencyMshas 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.
| Column | Type | Contents |
|---|---|---|
id | INTEGER PRIMARY KEY | SQLite rowid, monotonic. |
boot_id | BLOB NOT NULL | 16-byte boot ID GUID in PCDS binary layout. |
timestamp | INTEGER NOT NULL | Nanoseconds since the Unix epoch — the producer's value if it supplied one, otherwise eventd's clock at receipt. |
origin | TEXT NOT NULL | The producer peinit associated with the output pipe — a service, or a hook, health check, reload command or job within one. |
is_error | INTEGER NOT NULL | 1 for standard error or an explicitly marked error, 0 otherwise. |
message | TEXT NOT NULL | The log text. |
job_id | BLOB | 16-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_timestamponlogs(timestamp)— time-range filtering, as everywhere.idx_logs_originonlogs(origin)— "show me logs from X", which is the dominant log query.idx_logs_job_idonlogs(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:
- WAL mode,
PRAGMA journal_mode=WAL PRAGMA synchronous=NORMAL- the
logs,log_origins, andmetadatatables (§4.2) - the
idx_logs_timestamp,idx_logs_origin, andidx_logs_job_idindexes - the
schema_versionandcreated_atentries
4.3.3 Opening #
- Open in WAL mode.
- Set synchronous to NORMAL.
- 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:
- Authorize the name. The datagram's KACS token must hold
EVENTD_PUBLISHon 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
MetricMaxBatchSizesamples MetricMaxBatchLatencyMshas 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 #
| Column | Type | Contents |
|---|---|---|
id | INTEGER PRIMARY KEY | Series identifier; the foreign key samples uses. |
name | TEXT NOT NULL | The metric name. |
labels | TEXT NOT NULL | Canonical label representation. Empty string for no labels. |
type | INTEGER NOT NULL | 0 counter, 1 gauge, 2 histogram. |
label_hash | INTEGER NOT NULL | Hash of the canonical label string. |
boundaries_hash | INTEGER | Hash of the canonical boundary blob. Null for counters and gauges. |
boundaries | BLOB | Canonical 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:
boundary_count,u32little-endian- that many IEEE-754
f64values, 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 #
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_timestamponsamples(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_nameonseries(name)— name lookups.idx_series_label_hashonseries(label_hash)— series resolution on the ingestion path.idx_series_boundaries_hashonseries(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 #
- 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). - Hash it.
- 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.
- Look up
seriesbyname,label_hash, and for histogramsboundaries_hash. - On a match, verify the full
labelsstring, 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 existingseries_id. - On no match, insert a new
seriesrow 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:
- WAL mode.
PRAGMA synchronous=NORMAL— the log store's reasoning, for the same reason: metric loss on power failure is acceptable (§4.1).- The
series,samples,rollups, andmetadatatables (§5.2, §5.6). - Every write-time index.
- The
schema_versionandcreated_atentries.
5.4.3 Opening #
- Open in WAL mode with synchronous NORMAL.
- 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.
- 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 #
- Delete rows from
samplesolder thanMetricRetentionDays(§A) until none remain. - If
MetricRetentionMaxBytesis 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
SINCEand an explicitAVG_OVER,MIN_OVER,MAX_OVERorSUM_OVERfunction; - the selected output is per series — the selector is bracketed, or it resolves to exactly one series;
- it has no
WHEREpredicate or cross-type filter; and AdaptiveRollupMaxRowsis 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:
(
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 #
| Name | Type | Labels | What it is |
|---|---|---|---|
eventd.events.stored | counter | shard | Events committed to each active shard. |
eventd.events.lost | counter | cpu | Sequences 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.percent | gauge | cpu | How full each CPU's KMES ring buffer is, as its drain last saw it. |
eventd.events.index.sheds | counter | reason | Event indexes dropped under write pressure: pressure one at a time, emergency all at once (§3.4). |
eventd.logs.stored | counter | None | Log records committed. |
eventd.metrics.stored | counter | None | Metric samples committed, these included. |
eventd.metrics.series.cached | gauge | None | Entries in the series cache (§5.3). |
eventd.store.bytes | gauge | store | Bytes each store occupies on disk, its write-ahead logs included: events (every active and historical shard), logs, metrics and metadata. |
eventd.store.write.errors | counter | store | Failed writes to each store, the ones the diagnostic dump names the latest of (§8.5). |
eventd.retention.deleted | counter | store | Rows retention removed from each store (§3.6, §4.4, §5.5). |
eventd.queries.active | gauge | None | Queries running, streaming or not. |
eventd.queries.streaming | gauge | None | Streaming queries running. |
eventd.queries.refused | counter | reason | Queries turned away by MaxConcurrentQueries (machine), MaxStreamingQueries (streaming) or MaxQueriesPerUser (user) (§6.5). |
eventd.queries.failed | counter | reason | Queries 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:
- Identifies the mode from the first token —
EVENTS,LOGS, orMETRIC. - Extracts the primary selector: a type pattern, a
FROMlist, or a metric name with an optional label selector. - Collects every clause, in whatever order they appear.
- Validates that the clauses suit the mode —
CONTAININGonly in log mode,RATEonly in metric mode,SELECTonly 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:
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:
| Query | Each group keeps |
|---|---|
COUNT BY, TOP N BY, GROUP … COUNT | a count; at the end the groups are sorted by count descending and TAKE applies |
GROUP … SUM | the exact integer sum while every value is an integer and it fits, and the binary64 sum |
GROUP … AVG | the binary64 sum and count, divided once at the end |
GROUP … MIN / MAX | the extreme so far |
DISTINCT | the 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.
| Store | Approximate floor | From |
|---|---|---|
| Events | MaxBatchLatencyMs, default 100 ms | §2.4 |
| Logs | LogMaxBatchLatencyMs, 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 #
| Right | Bit | Value | Meaning |
|---|---|---|---|
EVENTD_READ | 0 | 0x0001 | Read records matching the pattern. |
EVENTD_CLEAR | 1 | 0x0002 | Delete records matching the pattern. |
EVENTD_ADMINISTER | 2 | 0x0004 | Change eventd's own policy — the INDEX command (§7.2). |
EVENTD_PUBLISH | 3 | 0x0008 | Publish 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).
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:
| Namespace | Patterns match |
|---|---|
| Events | event type |
| Logs | log origin |
| Metrics | metric 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:
- Look for an exact match on the full identifier,
kacs.audit.access.checked. - Remove the last dot-separated component and look again,
kacs.audit.access. - Repeat:
kacs.audit, thenkacs. - 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:
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:
| Data | field_name |
|---|---|
| Event header field | its field path (PSPU §3.22) — event.time, event.type, event.cpu — never its column's name |
| Event payload field | the flattened dot path — access.granted, subject.token.sid, source.name |
| Log field | the column name — origin, message, is_error |
| Fixed metric field | timestamp, boot_id, name, type, value |
| Metric label | the 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 order | subject.token.sid | subject.process.pid |
|---|---|---|
deny subject, allow subject.token.sid | denied | denied |
deny subject.token.sid, allow subject | denied | read |
allow subject.token.sid, deny subject | read | denied |
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.
- Obtain the caller's token from the connection (§7.1). Failure denies the query.
- Parse the query to establish its data sources and filters (§6.1).
- 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.*,LOGSwithoutFROM, andMETRIC cpu.*are each resolved identifier by identifier. - 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). - 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.
- 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.
- 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.
- Execute, with root filtering already part of the logical row set.
- 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_listwith 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
WHEREpredicates - metric label filters in a primary selector
GROUP,COUNT BY,TOP N BY,SORT, andDISTINCTfields
- event and log aggregation arguments —
SUM,AVG,MIN,MAX - metric transforms and terminal aggregations, all of which read the
fixed
valuefield: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 readstype
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.
| Check | Audit 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.
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.
| Subsystem | For |
|---|---|
| KMES | Event ingestion. Provided by the Peios kernel. |
| LCS and loregd | Configuration. eventd reads every setting from the registry. |
| KACS | Access control — the AccessCheck API for query authorization, and the peer-token socket option (KACS_SO_PEER_TOKEN) for caller identification. |
| peinit | Lifecycle 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 #
- Read every configuration key under
Machine\System\eventd\. The six required keys areEventStorePath,LogStorePath,MetricStorePath,QuerySocketPath,LogSocketPathandMetricSocketPath; 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 #
- Query the KMES logical slot count with
kmes_attach(KMES_ATTACH_QUERY_SLOTS, …), walk every slot, skipEINVALholes, 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 #
- 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>
- 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 #
- 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. - Read and merge every committed
receipt_rangesrow 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>
- 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>
- 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 #
- 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>
- 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>
- Create the metric socket at
MetricSocketPath, then replace its inherited descriptor with the protected one that lets every authenticated caller send (§7.6). - 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 #
- One writer thread per active shard.
- One drain thread per attached logical CPU, each beginning to reconcile and read its ring buffer.
- The log ingestion thread.
- The metric ingestion thread.
- The retention coordinator thread.
- The adaptive indexing policy thread.
8.2.7 Phase 7 — ready #
- Write and commit an
eventd.daemon.startedevent 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>
- 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 #
| Change | Why |
|---|---|
| Socket paths | The sockets are bound and clients are connected to them. |
| Store paths | The databases are open, and moving a store is a data migration, not a setting. |
StorageShards | Shard-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 #
- 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 #
| Signal | Behavior |
|---|---|
SIGTERM | Begin graceful shutdown (§8.4). |
SIGINT | Begin graceful shutdown. |
SIGQUIT | Write a diagnostic dump to standard error, then begin graceful shutdown. |
SIGHUP | Re-read configuration from the registry (§8.3). |
SIGPIPE | Ignored, 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.lostrecord 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:
| Mechanism | Effect |
|---|---|
| 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 capacity | The 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.
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_checkandkacs_access_check_listfail, 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_PUBLISHcheck (§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:
| Consumer | Proportional to | Bounded by |
|---|---|---|
| Series cache | distinct metric series held in memory | MetricSeriesCacheSize (§5.3) |
| Event-type and log-origin intern sets | distinct committed identifiers not yet cleaned from active catalogs | catalog cardinality; no independent memory setting (§3.1, §4.2) |
| Adaptive index counters | distinct event fields queried | the event query surface |
| SQLite page caches | connections and active indexes | per-connection configuration (§C) |
| Event handoff channels | occupied slots and copied event bytes | startup-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.
| Store | Setting | What survives |
|---|---|---|
| Event | synchronous=FULL | Every committed transaction. |
| Log | synchronous=NORMAL | Transactions up to the last checkpoint. |
| Metric | synchronous=NORMAL | Transactions 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.
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:
|
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.
| Format | Selection | Use |
|---|---|---|
| Pretty | --format pretty (default) | One self-describing record per line, with terminal emphasis on field names. |
| JSON Lines | --format jsonl | One JSON object per record for text pipelines. Binary, extension, and non-finite floating-point values use tagged objects rather than being discarded. |
| MessagePack | --format msgpack | A 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 onceendhas arrived, or the error and no records.Tail::start(socket, text, capacity)follows aSTREAMquery. It reports the initial result once, complete, whenwatcharrives; then each live batch; then why the tail ended. If the query fails beforewatch, 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).
stringwrites a quoted string: the quote and backslash escaped, and every control character as\n,\r,\tor\uXXXX.binarywritesx"…";durationwrites90s,2hand 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_guidderives a field's GUID (§7.3). eventd-core computes the same derivation for itself, and a test holds the two equal.resolvefinds the descriptor eventd would check an identifier against: the identifier, each shorter dotted prefix, then*, with an origin's producer left off (§7.2).accesschecks 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 withEVENTD_READon the root or on any field, as eventd shows them (§7.4).field_treebuilds that list for a set of field names, andfield_readsmakes the check over it, answering per field; eventd uses both, so the tree a client asks about is the one eventd builds.field_grantslists 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.readablesays 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).
A.2 SQLite storage #
| Key | Type | Default | Range | Description |
|---|---|---|---|---|
WalCheckpointPages | REG_DWORD | 1000 | 100–100000 | WAL page threshold triggering a passive checkpoint, on shard, log, metric and metadata databases alike. |
A.3 Event ingestion #
| Key | Type | Default | Range | Description |
|---|---|---|---|---|
StorageShards | REG_DWORD | 0 | 0–256 | Number 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). |
MaxBatchSize | REG_DWORD | 10000 | 100–100000 | Maximum events per writer transaction. |
MaxBatchLatencyMs | REG_DWORD | 100 | 10–5000 | Maximum ms before an event batch commits. |
A.4 Log ingestion #
| Key | Type | Default | Range | Description |
|---|---|---|---|---|
LogMaxBatchSize | REG_DWORD | 5000 | 100–100000 | Maximum log records per transaction. |
LogMaxBatchLatencyMs | REG_DWORD | 500 | 10–5000 | Maximum ms before a log batch commits. |
MaxLogDatagramBytes | REG_DWORD | 262144 | 262144–1048576 | Maximum accepted log datagram size; the PSPU portable floor cannot be lowered. |
A.5 Metric ingestion #
| Key | Type | Default | Range | Description |
|---|---|---|---|---|
MetricMaxBatchSize | REG_DWORD | 5000 | 100–100000 | Maximum metric samples per transaction. |
MetricMaxBatchLatencyMs | REG_DWORD | 1000 | 10–5000 | Maximum ms before a metric batch commits. |
MaxMetricDatagramBytes | REG_DWORD | 262144 | 262144–1048576 | Maximum accepted metric datagram size; the PSPU portable floor cannot be lowered. |
MetricSeriesCacheSize | REG_DWORD | 50000 | 1000–1000000 | Entries in the LRU series resolution cache. |
MetricAuthorizationCacheSize | REG_DWORD | 16384 | 256–1000000 | Cached KACS publication verdicts, invalidated by security-policy generation. |
HealthMetricIntervalSeconds | REG_DWORD | 15 | 0–3600 | How often eventd records its own health as eventd.* metrics; 0 turns them off (§5.7). |
A.6 Adaptive indexing #
| Key | Type | Default | Range | Description |
|---|---|---|---|---|
AdaptiveIndexWindowHours | REG_DWORD | 24 | 1–168 | Rolling window over which query frequency is measured. |
AdaptiveIndexPolicyIntervalMinutes | REG_DWORD | 60 | 60–1440 | How often the desired index set is recomputed. The minimum of 60 prevents index churn. |
AdaptiveIndexCreateThreshold | REG_DWORD | 100 | 10–10000 | Queries on a field within the window needed to add it. |
AdaptiveIndexDropThreshold | REG_DWORD | 10 | 1–1000 | Queries below which it is removed. Less than the create threshold, which is what supplies the hysteresis. |
A.7 Index shedding #
| Key | Type | Default | Range | Description |
|---|---|---|---|---|
SheddingWindowSeconds | REG_DWORD | 30 | 10–300 | Sliding window for graduated shedding. |
SheddingBatchPercent | REG_DWORD | 75 | 50–100 | Percentage of batches in the window exceeding 75% of MaxBatchSize that triggers graduated shedding. |
EmergencySheddingBufferPercent | REG_DWORD | 75 | 50–95 | Ring buffer fill percentage triggering emergency shedding. |
A.8 Retention #
| Key | Type | Default | Range | Description |
|---|---|---|---|---|
EventRetentionDays | REG_DWORD | 30 | 1–3650 | Maximum age of events. |
EventRetentionMaxBytes | REG_QWORD | 0 | 0–2^64−1 | Maximum total logical live size of the event shards. 0 means no limit. |
LogRetentionDays | REG_DWORD | 14 | 1–3650 | Maximum age of log entries. |
LogRetentionMaxBytes | REG_QWORD | 0 | 0–2^64−1 | Maximum logical live size of the log store. 0 means no limit. |
MetricRetentionDays | REG_DWORD | 90 | 1–3650 | Maximum age of metric samples. |
MetricRetentionMaxBytes | REG_QWORD | 1073741824 (1 GiB) | 0–2^64−1 | Maximum logical live size of the metric store. 0 explicitly disables the limit. |
RetentionCheckIntervalMinutes | REG_DWORD | 60 | 1–1440 | How often the retention coordinator runs. |
RetentionDeleteBatchRows | REG_DWORD | 10000 | 100–100000 | Maximum rows deleted in one retention transaction. |
A.9 Querying #
| Key | Type | Default | Range | Description |
|---|---|---|---|---|
QueryTimeoutMs | REG_DWORD | 30000 | 1000–300000 | Maximum query execution time. |
MaxConcurrentQueries | REG_DWORD | 128 | 1–4096 | Concurrent finite and streaming queries globally. |
MaxStreamingQueries | REG_DWORD | 64 | 1–1024 | Concurrent streaming queries globally. |
MaxQueriesPerUser | REG_DWORD | 16 | 1–4096 | Concurrent queries, streaming or not, held by one caller's user SID; SYSTEM's are not counted (§6.5). |
MaxDistinctStreamValues | REG_DWORD | 100000 | 1000–10000000 | Values tracked by one DISTINCT streaming query. |
MaxQueryRequestBytes | REG_DWORD | 65536 | 1024–16777216 | Hard maximum query request payload. |
QueryResponseTargetBytes | REG_DWORD | 65536 | 1024–16777216 | Soft response batching target; one complete record can exceed it (§6). |
MaxQueryHeldBytes | REG_DWORD | 268435456 (256 MiB) | 16777216–4294967295 | What 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 #
| Key | Type | Default | Range | Description |
|---|---|---|---|---|
AdaptiveRollupMinSamples | REG_DWORD | 1000 | 100–1000000 | Minimum raw inputs an eligible window query must scan before it can seed rollups. |
AdaptiveRollupBatchRows | REG_DWORD | 512 | 16–4096 | Maximum missing windows submitted in one bounded writer command. |
AdaptiveRollupMaxRows | REG_DWORD | 100000 | 0–10000000 | Global rollup-cache row cap. 0 disables cache reads and writes without changing results. |
A.11 Cross-type filtering #
| Key | Type | Default | Range | Description |
|---|---|---|---|---|
CrossTypeWindowMs | REG_DWORD | 15000 | 1000–300000 | Centered window for cross-type event and log existence checks. |
CrossTypeMaxLookbackSeconds | REG_DWORD | 604800 | 3600–2592000 | Maximum 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 #
| Change | Effect |
|---|---|
| Every tuning parameter above | Applied immediately. |
| Socket paths | Restart. |
| Store paths | Restart. |
StorageShards | Restart. |
| Security descriptors | Next 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 #
| Right | Bit | Value | Meaning |
|---|---|---|---|
EVENTD_READ | 0 | 0x0001 | Read records matching the pattern. |
EVENTD_CLEAR | 1 | 0x0002 | Delete records matching the pattern. Reserved; nothing uses it yet (§7.1). |
EVENTD_ADMINISTER | 2 | 0x0004 | Change eventd's own policy — the INDEX command. |
EVENTD_PUBLISH | 3 | 0x0008 | Publish 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 right | Value | Composed of |
|---|---|---|
GENERIC_READ | 0x00020001 | EVENTD_READ | READ_CONTROL |
GENERIC_WRITE | 0x0002000E | EVENTD_CLEAR | EVENTD_ADMINISTER | EVENTD_PUBLISH | READ_CONTROL |
GENERIC_EXECUTE | 0x00020001 | EVENTD_READ | READ_CONTROL |
GENERIC_ALL | 0x000F000F | EVENTD_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 type | GUID |
|---|---|
| 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 #
| Value | Origin |
|---|---|
| 0 | userspace |
| 1 | KMES |
| 2 | KACS |
| 3 | LCS |
| 4 | NTFE |
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 #
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 #
| Value | Type |
|---|---|
| 0 | counter |
| 1 | gauge |
| 2 | histogram |
Stored in series.type.
The query language exposes the names, not the numbers (PSPU §3.22).
B.9 Log severity #
| Value | Meaning |
|---|---|
| 0 | Normal — standard output. |
| 1 | Error — 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.
| Parameter | Value |
|---|---|
| Offset basis | 0xCBF29CE484222325 |
| Prime | 0x100000001B3 |
| Stored as | hash & 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 #
| Store | Version |
|---|---|
| Event shard | 1 |
| Log store | 1 |
| Metric store | 3 |
eventd-meta.db | 1 |
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 #
| Subject | Where |
|---|---|
| The interface layer's vocabulary — facts, verdicts, the collation laws — and every profile value, as an operator writes them | The network policy reference (~peios/networking/network-policy-reference) |
| The rule engine itself: ingestion, conditions, collation, refusal | Kernel 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 layers | PKM §6.5 |
| The netd → resolver channel's contract | PSPU §6.9 |
| What a resolver does with the snapshots | PSPU book 6 and the resolvd manual |
| The query-channel framing the control socket uses | PSPU book 3 |
| How peinit holds a service until a readiness level is published | The peinit manual |
| Every registry value netd reads or writes, one entry each | regman '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.
| Term | Meaning |
|---|---|
| interface | A kernel network link netd has seen, keyed by its kernel index while it exists and named in the registry by its interface id. |
| interface id | A UUID-shaped digest of an interface's bus path and MAC (§4.1). Stable across boots and kernel renames. |
| verdict | What 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. |
| profile | A resolved key under Profiles\, inheritance applied: how a joined interface stands on its network. |
| generation | One 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. |
| pass | One run of netd's converge sequence (§2.2): identify networks, judge links, start or stop clients, reconcile, publish. |
| desired state | What one interface should look like: up or down, its MTU, its addresses and its routes (§4.2). |
| reconcile | Diffing desired state against the kernel's and applying the difference (§4.3). |
| network | What is on the other side of a joined interface's carrier, identified from what it has offered (§7.1) and recorded under Networks\<id>. |
| offer | Everything a network has said: a DHCPv4 lease, router advertisements, a stateless DHCPv6 reply. |
| level | How far an interface has got toward being usable: absent, link, addressed, or routed (§8.2). |
| scope | What 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:
| Value | Setting | Why |
|---|---|---|
ImagePath | /usr/sbin/netd | |
Triggers | boot | |
Identity | SYSTEM | rtnetlink changes, the packet socket, and a bind to udp/68 each need a privilege only SYSTEM holds |
Provides | network | the role a dependent names: Requires = ["network:routed"] |
Readiness | 0 (Notify) | readiness is READY=1 on the notify socket |
RuntimeDirectories | netd | peinit creates /run/netd for the control socket |
RestartPolicy | 2 (Always) | a stopped network manager is a machine whose leases silently expire |
ErrorControl | 0 |
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:
- 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.
- Opens the control socket at
/run/netd/control.sock, removing a stale one first (§9.1). Failure is fatal. - 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.
- Switches the kernel's RA processing off on every interface that
exists, and in
allanddefault(§6.1). This happens before any link is brought up. - 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.
- Arms the registry watch on
Machine\System\Network. Failure is a warning, and the configuration is then read once, never again. - Dumps the kernel's state (links, addresses and routes, both families). Failure is fatal.
- Runs the first pass (§2.2): every interface is judged, every static address applied, every client that is due started.
- **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 #
| Input | Descriptor | What it leads to |
|---|---|---|
| Kernel events | the rtnetlink multicast socket | a fresh dump, then a full pass |
| Registry changes | the watch on Machine\System\Network | a reload (§2.3), then a full pass |
| udp/68 absorber | the absorber socket | drained and discarded |
| DHCPv4 replies | one packet socket per running client | the client's actions; a reconcile if the network changed |
| Router advertisements | one ICMPv6 socket per interface doing router discovery | the engine's actions; a full pass if anything changed |
| DHCPv6 replies | one UDP socket per running DHCPv6 client | the client's actions; a reconcile if the DNS facts changed |
| Control requests | the listener and accepted client sockets | the request (§9.2); reconcile runs a full pass |
| Time | the earliest deadline of any client | every 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:
- identify networks on joined interfaces with carrier (§7.1);
- 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;
- start DHCPv4 clients where due (§5.1);
- start or stop router discovery and DHCPv6 (§6.1, §6.3);
- 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 key | Used 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 it | the interface layer (§3.2) |
Profiles\ and everything under it | the 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 type | Lowered to |
|---|---|
REG_DWORD (4 bytes) | an integer |
REG_QWORD (8 bytes) | an integer |
REG_SZ, REG_EXPAND_SZ | a string, cut at the first NUL; invalid UTF-8 rejects the read |
REG_MULTI_SZ | a list of strings with empty items removed; invalid UTF-8 rejects the read |
| anything else, or a DWORD or QWORD of the wrong length | other |
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):
| Shape | Accepted |
|---|---|
| boolean | an integer (non-zero is true), or a string on, yes, true, 1, off, no, false, 0 in any case |
| number | a non-negative integer that fits 32 bits, or a string of one, surrounding space trimmed |
| list | a multi-string (empty items dropped), or a single string as a one-item list; an empty string is the empty list |
| string | a 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 #
| Value | Shape | What netd does with it |
|---|---|---|
Address.Offered | boolean | runs a DHCPv4 client while IPv4 is in the families, and router discovery while IPv6 is |
Address.Families | list | items 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.Static | list | each item address/prefix, either family, prefix at most 32 or 128. An item that does not parse refuses the generation. |
Address.LinkLocal | boolean | link-local fallback (§5.5) |
Address.Temporary | boolean | temporary IPv6 addresses (§6.2) |
Address.OnExpiry | string | Drop or Keep, in any case. Anything else refuses the generation. |
Route.Offered | boolean | takes the lease's gateway and classless routes and the routers' default route (§4.2) |
Route.Gateway | list | each 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.Metric | number | the metric of every route netd adds for the interface, and its place in DNS scope order |
Mtu.Offered | boolean | takes the lease's MTU, else the routers' |
Mtu.Value | number | the MTU to set. Below 68 refuses the generation. |
Hostname.Announce | boolean | sends the machine's Hostname in DHCP option 12 |
Hostname.Offered | boolean | adopts a lease's hostname when Hostname is unset (§8.4) |
Dns.Offered | boolean | adds the network's DNS servers and search domains after the profile's own (§8.3) |
Dns.Servers | list | each item an address of either family. An item that does not parse refuses the generation. |
Dns.Domains | list | taken as written; nothing validates a domain |
Dns.Default | boolean | present sets the scope's default-route flag; absent follows the interface's level (§8.3) |
Dns.Exclusive | boolean | sets 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 #
- Profiles are resolved (§3.1). Any error refuses the generation.
- If
Rules\Interfacedoes not exist, the generation has no forest. Every interface meets the backstop,IGNORE, and the profiles are kept for nothing to name. - Each subkey of
Rules\Interfaceis a root rule. Its tree is lowered topnp-core's input and built as theInterfacelayer withbuild_forest— the same ingestion, condition parsing, and lints the kernel applies to the packet layers (PKM §6.5). Every build error refuses the generation. - Every profile a
JOINnames is looked up. AJOINnaming no profile refuses the generation withJOIN(<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:
| Cause | Message |
|---|---|
| An unknown fact in a condition | rule <path>: unknown fact <key> |
| A malformed operator | rule <path>: bad operator in <key> |
| A malformed pattern | rule <path>: bad pattern in <key> |
Actions not a list | rule <path>: Actions is not a list |
| A malformed action | rule <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 layer | rule <path>: <key> does not exist at the interface layer |
Present on a fact never present at this layer | rule <path>: <key> on a fact that never exists at this layer |
Priority not an integer | rule <path>: Priority is not an integer |
Enabled not 0 or 1 | rule <path>: Enabled is not 0 or 1 |
| A malformed rule name | rule <path>: bad name |
A JOIN naming no profile | JOIN(<path>) names no profile |
| A malformed profile | the 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:
| Fact | Value |
|---|---|
Interface | the kernel's name for the link |
Interface.Kind | wired, wireless, loopback, or other (§4.1) |
Interface.Id | the interface id (§4.1) |
Interface.Mac | the hardware address, when the link has a 6-byte one |
Interface.Path | the bus path; absent when sysfs gives none |
Interface.Driver | the driver; absent when sysfs gives none |
Network.Id | the id of the network identified on the link (§7.1); absent until one is |
Network.Name | the record's Name; absent when unset or empty |
Network.Trust | the record's Trust; absent when unset or empty |
Network.Kind | the 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'sithJOINnames, 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 #
| Verdict | Clients | Desired state (§4.2) |
|---|---|---|
JOIN(profile) | started as the profile asks | up, with the profile's addresses and routes |
DOWN | none | down, carrying no addresses, and no netd routes |
IGNORE | none | none: 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:
| Link | Interface.Kind |
|---|---|
| the loopback flag set | loopback |
link type Ethernet, with /sys/class/net/<name>/wireless or /sys/class/net/<name>/phy80211 present | wireless |
| link type Ethernet otherwise | wired |
| any other link type | other |
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 Networkis cleared and theNetwork.*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
IGNOREd 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, withRoute.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 classless0.0.0.0/0route. 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 #
- every IPv6 entry of
Address.Static, at its prefix, preferred, with a prefix route; - 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:
- Link up, if it is desired up and is down.
- MTU, if one is desired, differs from the link's, and is at least 68.
- Address deletions: every address netd owns whose address and prefix length together match no desired address.
- Address additions: every desired address the kernel does not hold with the same flags, in ascending address order, IPv4 before IPv6.
- Route deletions: every protocol-200 route on the interface that is not desired.
- Route additions: every desired route the kernel does not hold.
- 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:
| Operation | Request |
|---|---|
| link up or down | RTM_SETLINK changing only IFF_UP |
| MTU | RTM_SETLINK with IFLA_MTU |
| address add | RTM_NEWADDR with NLM_F_CREATE and NLM_F_REPLACE |
| address delete | RTM_DELADDR |
| IPv4 route add | RTM_NEWROUTE with NLM_F_CREATE and NLM_F_APPEND, main table, protocol 200 |
| IPv6 route add | RTM_NEWROUTE with NLM_F_CREATE and NLM_F_EXCL, main table, protocol 200 |
| route delete | RTM_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_LOCALandIFA_ADDRESSset 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.Offeredand 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 socketand tries again on the next pass.
A new client starts with no lease. It is configured with:
| Setting | Value |
|---|---|
chaddr | the 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 |
| randomness | 8 bytes of /dev/urandom XORed with the interface index, seeding transaction ids and jitter |
| a previous address | the 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 #
| State | Entered | Leaves on |
|---|---|---|
| Selecting | start without a previous address; a NAK while requesting or rebooting; a request that went stale; a reboot nobody confirmed; a lost lease | an acceptable OFFER |
| Requesting | an OFFER in Selecting | an ACK (Bound), a NAK (Selecting), four unanswered transmissions (Selecting) |
| Rebooting | start with a previous address | an ACK (Bound), a NAK (Selecting), two unanswered transmissions (Selecting) |
| Bound | an ACK | T1 (Renewing) |
| Renewing | T1; or an operator renew while bound, renewing or rebinding | an ACK (Bound), a NAK (lease lost, Selecting), T2 (Rebinding) |
| Rebinding | T2 | an 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:
| Option | Content |
|---|---|
| 53 | the message type |
| 61 | the client identifier |
| 57 | maximum message size 1500 |
| 55 | the parameter request list: 1, 3, 6, 12, 15, 26, 28, 42, 51, 58, 59, 119, 121 |
| 12 | the 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 #
| Message | When | Broadcast flag | ciaddr | Option 50 | Option 54 | Sent |
|---|---|---|---|---|---|---|
| DISCOVER | Selecting | set | 0 | the address of a lease that expired, until a NAK or a reboot timeout forgets it | — | broadcast |
| REQUEST | Requesting | set | 0 | the offered address | the offer's | broadcast |
| REQUEST | Rebooting | set | 0 | the previous address | — | broadcast |
| REQUEST | Renewing | clear | the lease address | — | — | unicast to the server |
| REQUEST | Rebinding | clear | the lease address | — | — | broadcast |
| RELEASE | a stop while holding a lease | clear | the lease address | — | the server | unicast 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.
| State | Transmissions before it gives up | Then |
|---|---|---|
| Selecting | never gives up | — |
| Requesting | four REQUESTs (about 0, 4, 12 and 28 s) | at the next timer, about 60 s, Selecting with a new DISCOVER |
| Rebooting | two 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
chaddris 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 #
| State | Message | Result |
|---|---|---|
| Selecting | OFFER with a non-zero yiaddr and a server identifier | taken: Requesting. The first acceptable OFFER wins; there is no comparison between offers. |
| Selecting | OFFER without either | ignored |
| Requesting, Rebooting, Renewing, Rebinding | ACK that reads as a lease (below) | Bound, with the lease |
| Requesting, Rebooting, Renewing, Rebinding | ACK that does not read as a lease | ignored; retransmission continues |
| Requesting, Rebooting | NAK | Selecting; the previous address and the offer are forgotten |
| Renewing, Rebinding | NAK | the lease is lost (§5.4); Selecting |
| any other combination | ignored |
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 #
| Option | Kept as |
|---|---|
| 6 | DNS servers, every 4-byte entry |
| 15 | the domain name: the bytes up to the first NUL; dropped if not UTF-8 |
| 119 | the domain search list, RFC 1035 names with compression pointers followed, at most 16 jumps per name |
| 12 | the hostname offered: the bytes up to the first NUL; dropped if not UTF-8 |
| 26 | the MTU, when it is at least 68 |
| 28 | the broadcast address |
| 42 | NTP 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 logsinterface <name>: lease lostand forgets the lease. The next reconcile removes the address and the routes that came with it.Keep: netd logsinterface <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:
| Field | Value |
|---|---|
| source | 0.0.0.0 |
| destination | 255.255.255.255 |
| TOS | 0x10 |
| identification | 0 |
| flags | don't-fragment |
| TTL | 64 |
| UDP ports | 68 → 67 |
| UDP checksum | 0 (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:
- the registry's
Machine\System\Network Duid, as hex, when it is set and parses; - otherwise the file
/var/state/netd/duid, when it holds at least 4 bytes; - otherwise a new DUID-LL:
00 03 00 01followed 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):
- the
RequestedAddressof the network identified on the interface, when there is one; otherwise - the
RequestedAddressof the network the interface'sStatus LastNetworknames (§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.Offeredand 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:
| Option | Accepted when | Limits |
|---|---|---|
| Prefix information (3) | 32 bytes long; prefix length ≤ 128; the prefix neither multicast nor link-local | the first 16 per advertisement |
| MTU (5) | 8 bytes long | |
| RDNSS (25) | at least 24 bytes, and a whole number of addresses | 16 servers per option; unspecified, multicast, and loopback addresses dropped |
| DNSSL (31) | at least 16 bytes | 16 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:
- the bytes
peios-ndp-stable-iid|; - the machine's 32-byte secret;
- the prefix's first 8 bytes;
- the interface id's text;
- 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 lifetime | Remaining valid lifetime | Result |
|---|---|---|
| above two hours, or above what remains | any finite | the advertised lifetime |
| two hours or less, not above what remains | two hours or less | unchanged |
| two hours or less, not above what remains | above two hours | two hours from now |
| above two hours | forever | the advertised lifetime |
| two hours or less | forever | two 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:
| Option | Content |
|---|---|
| 1, client identifier | the machine's DUID (§5.7) |
| 8, elapsed time | hundredths of a second since this exchange began, capped at 65535 |
| 6, option request | 23 (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:
| Signal | From |
|---|---|
| kind | the interface's Interface.Kind |
| server | the DHCPv4 lease's server identifier |
| subnet | the lease address masked to the lease prefix |
| gateway | the lease's gateway (§5.3) |
| router | the default router router discovery chose (§6.1) |
| prefixes | the subnet, then every non-deprecated autoconfigured address's prefix, each once |
| DNS servers | the 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:
| Value | Type | Content |
|---|---|---|
Kind | REG_SZ | the interface kind it was seen on |
Server | REG_SZ | the DHCPv4 server; removed when there is none |
Gateway | REG_SZ | the lease's gateway; removed when there is none |
Router | REG_SZ | the IPv6 default router; removed when there is none |
Prefixes | REG_MULTI_SZ | the subnet and the autoconfigured prefixes, CIDR form |
DnsServers | REG_MULTI_SZ | the DNS servers offered, either family |
LastSeen | REG_SZ | the wall-clock time of the identification, in Unix seconds |
LastInterface | REG_SZ | the 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:
| Value | Read as | Meaning |
|---|---|---|
Name | REG_SZ, empty is unset | the Network.Name fact |
Trust | REG_SZ, empty is unset | the Network.Trust fact |
RequestedAddress | REG_SZ, an IPv4 address | the 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 #
| Value | Content | Present |
|---|---|---|
Name | the kernel's name for the link | always |
Kind | wired, wireless, or other | always |
Mac | the hardware address, lower-case, colon-separated | when the link has one |
Path | the bus path | when there is one |
Driver | the driver | when there is one |
Verdict | JOIN, IGNORE, or DOWN | when a rule spoke; removed when the backstop answered or rules tied |
Rule | the 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 |
Profile | the profile path as written | JOIN only |
Readiness | the interface's level (§8.2) | JOIN only |
Network | the id of the network identified on the link now | while one is identified; removed when the carrier goes |
LastNetwork | the id of the network the link last stood on | from 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:
| Level | When |
|---|---|
absent | the interface is not up, or has no carrier |
link | up with carrier, and no usable address |
addressed | a usable address, and no default route |
routed | a 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:
- logs
machine readiness is <level>; - sends the complete readiness set below in one datagram on the notify
socket named by
NOTIFY_SOCKET; - writes
ReadinessonMachine\System\Network.
The notify set is determined by the highest machine level:
| Machine level | LEVEL values, in wire order |
|---|---|
absent | absent |
link | link |
addressed | link, addressed |
routed | link, 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:
| Field | Content |
|---|---|
ifid | the interface id |
name | the kernel name |
servers | DNS servers, as text, in the order to try them (below) |
domains | search domains, likewise |
ntp | the lease's NTP servers (option 42) |
addresses | every address the kernel holds on the interface, address/prefix, link-local ones included |
default_route | the profile's Dns.Default when set; otherwise whether the interface's level is routed |
exclusive | the profile's Dns.Exclusive |
metric | the interface's metric (§4.2) |
level | the interface's level (§8.2) |
8.3.4 Merging DNS facts #
Servers, in this order:
- the profile's
Dns.Servers, always; - with
Dns.Offered: the lease's servers (option 6); - with
Dns.Offered: the routers' RDNSS servers, including link-local IPv6; - with
Dns.Offered: the DHCPv6 reply's servers, including link-local IPv6.
Domains, in this order:
- the profile's
Dns.Domains, always; - with
Dns.Offered: the lease's domain search list (option 119) if it is not empty, otherwise its domain name (option 15); - with
Dns.Offered: the routers' DNSSL domains; - 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 #
Machine\System\Network Hostname, when it is set and not empty;- otherwise the hostname option (12) of a lease. netd takes the first
joined interface, in kernel index order, whose profile has
Hostname.Offeredand whose lease carries a hostname; - 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:
- creates
/run/netdif it is missing, sets its mode to0755, and gives it the descriptor below; - removes a socket file left by a previous run, logging
removed a stale /run/netd/control.sock; - 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:
| Trustee | Rights |
|---|---|
| SYSTEM | NETWORK_ALL_ACCESS |
| Administrators | NETWORK_ALL_ACCESS |
| Everyone | NETWORK_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 #
| Right | Value |
|---|---|
NETWORK_QUERY | 0x00000001 |
NETWORK_CONTROL | 0x00000002 |
NETWORK_ALL_ACCESS | 0x000F0003: both, plus the standard rights |
The generic mapping:
| Generic right | Maps to |
|---|---|
| read | NETWORK_QUERY, READ_CONTROL |
| write | NETWORK_CONTROL, READ_CONTROL |
| execute | NETWORK_QUERY |
| all | NETWORK_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 stringerror.
An oversized, incomplete-at-EOF, or undecodable request is answered with an error reply and the connection ends:
| Problem | error |
|---|---|
no query | missing field query |
an unknown query | unknown query "<query>" |
| a duplicate key | duplicate field <key> |
renew without interface | missing field interface |
| malformed MessagePack | malformed 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 #
query | Right | Does | Reply |
|---|---|---|---|
status | NETWORK_QUERY | nothing | the status (below) |
subscribe | NETWORK_QUERY | keeps the connection as a subscriber (§8.3) | a snapshot now, and another on each change |
reconcile | NETWORK_CONTROL | a full pass (§2.2) | {ok: true} |
renew, with interface | NETWORK_CONTROL | the 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 #
| Field | Content |
|---|---|
hostname | the name netd last set, empty if none (§8.4) |
level | the machine level (§8.2) |
refusal | why the newest generation was refused, or nil (§3.2) |
interfaces | one map per non-loopback interface netd has seen, joined or not, in kernel index order |
Each interface:
| Field | Content |
|---|---|
ifid, name, index | the interface id, kernel name, and index |
mac, path, driver | identity (§4.1); empty strings when absent |
verdict | JOIN, IGNORE, or DOWN; nil when the backstop answered or rules tied |
rule | the rule that spoke, backstop, or the tied rules <a> vs <b> |
profile | the profile path, JOIN only |
network, network_name, network_trust | the network identified now (§7) |
warning | discovery unanswered (§5.2), or a tie (§3.3); nil otherwise |
up, carrier | the link's flags |
level | the interface's level (§8.2), computed for every interface |
addresses | every address the kernel holds, address/prefix, link-local ones included |
gateway, gateway6 | the gateway of the interface's first IPv4 and IPv6 default route, any owner's |
dns, search | the merged DNS facts (§8.3); empty for an interface not joined |
lease | while 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 #
| Command | Does |
|---|---|
net status | prints the status reply (§9.2) |
net renew <interface> | sends renew |
net reconcile | sends reconcile |
net rules | prints 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 list | prints 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 policy | prints 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 --version | prints 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 #
| Code | Meaning |
|---|---|
| 0 | success |
| 1 | netd unreachable, an error reply, a timeout, a refused policy, or a registry key that cannot be opened |
| 2 | usage: 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/kmsgatKERN_INFO,KERN_WARNINGorKERN_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/kmsgdescriptor, 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 shows | Likely cause |
|---|---|
warning asked for an address; nobody answered, a 169.254 address, or none | no 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 warning | the 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 address | no 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 shows | Meaning |
|---|---|
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 backstop | no rule speaks for the interface. It is left as the kernel left it. |
verdict (none) by <a> vs <b>, warning rules … tie | two 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 it | by 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.Staticinstead. - A route added by hand stays, unless it carries protocol 200.
- A pinned gateway never appears.
Route.Gatewayis not checked against the interface's subnets. When the kernel cannot reach it, every reconcile logsreconcile: AddRoute(…) failed, and the interface staysaddressed. - The hostname does not change back when
Hostnameis 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/netdlost its descriptor. The service restarts netd always;evctlshows 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), orMachine\System\Networkdid not exist then (§2.1). Restart netd.
11.1.8 Getting back to a known state #
- Undo the last registry write. A refused generation names what to undo, and the next good write is taken at once.
net reconcileruns a full pass without waiting for an event.net renew <interface>renews a lease without releasing it.- 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 #
| Path | Use |
|---|---|
Machine\System\Network | configuration root, readiness, DUID (§2.3, §8) |
/run/netd/control.sock | control socket (§9.1) |
/run/netd | runtime directory, created by peinit (§2.1) |
/var/state/netd/duid | the DUID, when the registry has none (§5.7) |
/var/state/netd/secret | the RFC 7217 secret (§6.2) |
/usr/sbin/netd | the daemon |
/proc/sys/net/ipv6/conf/<name>/accept_ra | set to 0 (§6.1) |
A.2 Numbers #
| Constant | Value | § |
|---|---|---|
| Routing protocol stamped on netd's routes | 200 | §4.3 |
| Default route metric | 100; 600 for wireless | §4.2 |
| Minimum MTU applied | 68 | §4.3 |
| Converge repetitions per pass | at most 4 | §2.2 |
| Registry tree depth read | 16 | §2.3 |
| Control message ceiling | 65536 bytes | §9.2 |
| Control read and write timeout | 2 s | §9.1 |
| DHCPv4 first backoff, ceiling | 4 s, 64 s, ±1 s jitter | §5.2 |
| DISCOVER retransmissions before "nobody answered" | 3 | §5.2 |
| REQUESTs in Requesting before rediscovery | 4 | §5.2 |
| REQUESTs in Rebooting before rediscovery | 2 | §5.2 |
| Renewing and rebinding retransmission floor | 60 s | §5.2 |
| Shortest lease accepted | 4 s | §5.3 |
| DHCPv4 maximum message size advertised | 1500 | §5.1 |
| DHCPv4 message padding | to 300 bytes | §5.1 |
| Domain-search compression jumps per name | 16 | §5.3 |
| Link-local range | 169.254.1.0–169.254.254.255 | §5.5 |
| Router solicitation interval, ceiling | 4 s, 3600 s, ±10% jitter | §6.1 |
| Solicitations before backoff | 3 | §6.1 |
| Prefixes, RDNSS servers, DNSSL domains per advertisement option | 16 | §6.1 |
| SLAAC prefix length | 64 | §6.2 |
| Two-hour rule | 7200 s | §6.2 |
| Temporary address preferred lifetime | 86400 s minus 0–599 s | §6.2 |
| Temporary address valid lifetime | 172800 s | §6.2 |
| Temporary addresses per prefix | 4 | §6.2 |
| Stable address counter attempts | 8 | §6.2 |
| DHCPv6 first retransmission, ceiling | 1 s, 3600 s, ±10% jitter | §6.3 |
| DHCPv6 refresh default, floor | 86400 s, 600 s | §6.3 |
| DHCPv6 servers and domains kept | 16 each | §6.3 |
A.3 Identifiers #
| Identifier | Value | § |
|---|---|---|
| Interface id digest prefix | peios-netd-ifid| | §4.1 |
| Network id digest prefix | peios-netd-network| | §7.1 |
| Stable address digest prefix | peios-ndp-stable-iid| | §6.2 |
| DUID-LL header | 00 03 00 01 | §5.7 |
Status descriptor | O:SYG:SYD:P(A;;KA;;;SY)(A;;KR;;;WD) | §8.1 |
NETWORK_QUERY, NETWORK_CONTROL, NETWORK_ALL_ACCESS | 0x1, 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):
| Door | Where | Who uses it |
|---|---|---|
| Native socket | /run/resolvd/resolv.sock | The resolv command, the NSS shim, Peios tools |
| Stub listener | 127.0.0.53:53 (UDP and TCP) | Programs that speak DNS themselves |
| NSS shim | libnss_peios_net.so.2, loaded into every glibc process | getaddrinfo 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:
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:
| Crate | What it is |
|---|---|
dns | The DNS wire codec: names, messages, records. No I/O and no policy. |
resolvd-core | The native channel's types, MessagePack codec, and framing. No I/O beyond framing. |
resolvd | The engine, the cache, the stub door's DNS rendering, and the daemon around them. |
resolv | The operator command. |
libresolvd | The public C shared library, with owned results and bounded exchanges. |
resolvd-abi | C-compatible data layouts. |
resolvd-client | Safe Rust wrappers over the shared library. |
nss | The 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 #
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:
| Key | Value | Type |
|---|---|---|
Machine\System\Network\TcpIp\PortReservations | tcp,udp:53 | REG_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=1to the socket named by theNOTIFY_SOCKETenvironment 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_SOCKETis unset, and logs a failure to send asreadiness 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:
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 #
- 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). - 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 logsstub listener on 127.0.0.53:53: <error>and exits with status 1. - The registry.
Machine\System\Network\Dnsis 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. - The registry watch. A subtree watch is armed on
Machine\System\Network(§2.3). If it cannot be armed, resolvd logsregistry watch unavailable (<error>); configuration is read onceand runs on the configuration it read in step 3 until it restarts. - 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. - 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. - The control object is built from
ControlSecurity(§5.2). - netd. The first attempt to subscribe is made immediately (§3.1). Its failure is not fatal and is retried with backoff (§3.2).
- The listening line. resolvd logs
listening on /run/resolvd/resolv.sock and 127.0.0.53:53at info level. - Readiness.
READY=1is sent (§2.1). - 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.
| Value | Type read | Default | Used for |
|---|---|---|---|
FallbackServers | REG_MULTI_SZ, or one REG_SZ / REG_EXPAND_SZ | none | The fallback scope's servers (§4.4) |
ExtraSearchDomains | REG_MULTI_SZ, or one REG_SZ / REG_EXPAND_SZ | none | Search domains after every interface's (§4.3) |
ControlSecurity | REG_BINARY | the compiled default | The control object (§5.2) |
Hosts\ | a subkey | empty | Static names (§4.2) |
2.3.2 Reading strings #
- A
REG_SZorREG_EXPAND_SZis one string: its data up to the first NUL, read as UTF-8. Invalid UTF-8 rejects the complete configuration read. - A
REG_EXPAND_SZis read as it is stored; nothing in it is expanded. - A
REG_MULTI_SZis 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 loneREG_SZthat is empty or only whitespace, a whitespace-only string in a multi-string, and an address with a zone such asfe80::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_BINARYvalue 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 defaulteach 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\Hostsis one static name. The value's name is the host name and its data is one address (REG_SZorREG_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 asDns 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
Printerandprinterare 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:
- rebuilds the control object from
ControlSecurity; - 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;
- replaces the static names;
- logs
configuration changedat 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-armingand 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:
- creates
/run/resolvdif peinit has not, and sets its mode to0755; - replaces the directory's DACL (below);
- removes any existing
/run/resolvd/resolv.sock, loggingremoved a stale /run/resolvd/resolv.sockat warn level when there was one, and a removal that fails is fatal (§2.2); - binds the socket, sets its mode to
0666, and replaces its DACL in the same way; - 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:
| Trustee | Access |
|---|---|
| SYSTEM | GENERIC_ALL |
| resolvd's own account (its token's user) | GENERIC_ALL |
| Everyone | GENERIC_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.53port 53 and both nonblocking (PSPU §6.8). - Nothing is bound on
::1or on any other address.
Binding port 53 depends on the port reservation (§2.1).
2.4.3 Other descriptors #
| Descriptor | Count | Lifetime |
|---|---|---|
The registry watch on Machine\System\Network | 0 or 1 | From startup; replaced on a watch error (§2.3) |
| The netd channel | 0 or 1 | While subscribed (§3.1) |
| Native connections reading or awaiting resolution | up to 256 total | Reading: at most 5 s (§5.1); resolving: until completion or definite departure (§4.1) |
| Stub TCP connections reading or awaiting resolution | up to 256 total | Reading: at most 10 s (§6.1); resolving: until completion or definite departure (§4.1) |
| Queued native reply writers | up to 256 | Until written, failed, or the one-second write deadline (§2.5) |
| Queued stub TCP reply writers | up to 256 | Until written, failed, or the one-second write deadline (§2.5) |
| Upstream sockets | one per transaction, at most 4 096 including retries | One 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:
- the native listener, except during its accept-error backoff;
- the stub UDP socket;
- the stub TCP listener, except during its accept-error backoff;
- the netd channel, while connected;
- the registry watch, while armed;
- every native connection still sending its request;
- every stub TCP connection still sending its query;
- every upstream socket — for reading, or for writing while a TCP connection is still being established or its query is still being sent;
- native and stub TCP replies waiting to write, for writability;
- 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:
- waiting native and stub TCP streams with definite hangup/error, canceling their questions and upstream transactions;
- upstream sockets — replies that have arrived are answers already owed;
- queued native replies, then queued stub TCP replies, whose sockets are writable;
- the stub UDP socket, reading at most 64 datagrams;
- the stub TCP listener, accepting at most 64 connections;
- stub TCP connections still sending queries;
- the native listener, accepting at most 64 connections;
- native connections still sending requests;
- the netd channel;
- 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:
- opens a nonblocking connection to
/run/netd/control.sock; - writes the
subscriberequest using a four-byte little-endian length and a MessagePack map; - 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:
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:
| Attempt | Time after the first |
|---|---|
| 2 | 0.5 s |
| 3 | 1.5 s |
| 4 | 3.5 s |
| 5 | 7.5 s |
| 6 | 15.5 s |
| 7 and later | every 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 reachablewarning is not logged for the failures that follow, however many there are; thelost the netd channel; reconnectingline 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
hostnameis 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
statusreports an emptyhostname. - 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:
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 #
- 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
notfoundat once. - Synthetic names. The name as asked is checked against the synthetic names (§4.2). A match answers the task.
- 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. - Routing. Each candidate in turn is routed to one scope (§4.4).
When no scope can take it, the task is answered
unavailable. - The cache. Unless the request asked to bypass the cache, the cache is consulted under that scope (§4.5).
- The network. Otherwise the candidate is sent upstream (§4.6 to §4.8).
- The next candidate. A
notfoundfor a candidate — from the cache or from a server — moves to the next candidate when there is one. Any other result answers the task. - The last candidate. When the last candidate is
notfound, the task is answerednotfound.
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 #
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 #
localhost, or any name under it.127.0.0.1forA,::1forAAAA, both forANY. Sourcesynthetic.- A static name. An exact, case-insensitive match against the
Hosts\values (§2.3). The name's addresses of the asked family — IPv4 forA, IPv6 forAAAA, both forANY. Sourcehosts. - The machine's hostname. An exact, case-insensitive match against
the hostname (§3.3), answered with the machine's own addresses
(below). Source
synthetic. .local. The namelocalor any name under it isnotfound, whatever the type asked. Sourcesynthetic. No query is sent.- A reverse-mapping name, for
PTRorANYonly. 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
addressedor 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.1and::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.arpalabel parses as a decimal number from 0 to 255. Leading zeros and a leading+are accepted, so1.0.0.0127.in-addr.arpaand+1.0.0.127.in-addr.arpaboth name127.0.0.1. - Each
ip6.arpalabel 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:
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_cacheflag has no effect on them. - Each one adds one to the
syntheticcounter (§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 asprinteris. - A top-level domain such as
comis 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.unavailableis the answer, and later candidates are not asked.- When the last candidate is
notfound, the question isnotfound(§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 #
- Exclusive. Choose an exclusive scope at
addressedor better, preferring the lowest metric and then snapshot order. - Search domain. Among up scopes, choose the longest matching domain suffix, compared by labels without case distinctions.
- 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.
- Default route. Choose an up default-route scope, preferring the lowest metric and then snapshot order.
- Lowest metric. Choose an up scope that has servers, preferring the lowest metric and then snapshot order.
- 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 matchingINanswer 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:
4.5.2.1 The negative lifetime #
- The negative lifetime comes from the first
INSOArecord 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'sMINIMUMfield 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
SOAin 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
notfoundhit with further candidates waiting moves to the next candidate, as anotfoundfrom a server would (§4.1).
4.5.4 Bypassing the cache #
- A
resolverequest withno_cacheset skips the lookup for each of its candidates. The reply it gets is still stored. - Stub queries,
lookup, andreversealways 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_entriescount instatusincludes 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:
- every entry whose expiry is at or before the current time;
- 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 #
| Event | Discards |
|---|---|
| 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 restart | Everything |
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:
| Bound | Value |
|---|---|
| Transaction timeout | 2 s |
| Attempts per question (all candidates and transports) | 3 |
| Demotion period | 30 s |
| Upstream transactions in flight | 4 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
NOERRORnorNXDOMAIN—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
NOERRORorNXDOMAINthat resolvd uses — a UDP reply withoutTC, or a TCP reply — removes the server's mark at once. A UDP reply withTCset 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.
statuslists, 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
NXDOMAINthat 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
unavailableat once, and therefusedcounter goes up by one. A question whose scope has no servers left is answeredunavailablebefore 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 #
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
TCset 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 isunavailable. - A TCP reply with
TCset 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:
- it decodes as a DNS message — bytes after its last section are tolerated;
- its ID equals the transaction's;
- its
QRbit is set; - it has exactly one question;
- that question's type and class equal those sent;
- 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:
| Reply | Result |
|---|---|
UDP, TC set | TCP retry to the same server (§4.7) |
Response code NOERROR | found |
Response code NXDOMAIN | notfound |
| Any other response code | The 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
NXDOMAINnone 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
INCNAME 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
INtypes 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:
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' outcomes | outcome |
|---|---|
At least one found, with or without records | found |
None found, at least one unavailable | unavailable |
Every one notfound | notfound |
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.
- 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 theCNAME's target. - This repeats at most 16 times; a loop stops there.
- The addresses are the
A(for theAtask) orAAAA(for theAAAAtask) 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 #
addresseslists 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.canonicalandsourcecome from the same selectedfoundtask. Prefer a task that produced addresses; when both or neither did, preferAoverAAAA. Completion order does not affect this choice.canonicalis the name that task's CNAME chase ended at, after search expansion. Without afoundtask it is the name asked, as parsed, in presentation form without a trailing dot (the root is.).- A
foundwith no addresses still reports the expanded or chased name. - A name that does not parse is answered at once with
outcomenotfound,canonical., no addresses andsourcelocal; no task is started. sourceis the source of the selected task, andlocalwhen no task wasfound. It describes that task; the other family's records can have a different source.validationisunvalidated.- A
lookupadds one toquerieshowever 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 #
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.
- Read exactly the four-byte little-endian payload length. A length
above 65 536 gets the reply
request too largeand the connection closes, without reading any payload bytes. - 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.
- 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:
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 #
- 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. - 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.
- A denied request is answered
access denied(§5.1).
5.2.1.1 The generic mapping #
The check uses this generic mapping:
| Generic right | Maps to |
|---|---|
GENERIC_READ | RESOLVER_QUERY, READ_CONTROL |
GENERIC_WRITE | RESOLVER_CONTROL, READ_CONTROL |
GENERIC_EXECUTE | RESOLVER_QUERY |
GENERIC_ALL | RESOLVER_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):
| Component | Value |
|---|---|
| Owner | SYSTEM |
| Group | SYSTEM |
| DACL | SYSTEM: 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:
statusandflushare 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 #
The reply's outcome, source, server, interface, and rcode are
as §4.1 describes. Each record carries:
| Type | text |
|---|---|
A, AAAA | The address |
CNAME, PTR, NS | The target name, written as name is |
SOA | mname rname serial refresh retry expire minimum |
MX | preference exchange |
SRV | priority weight port target |
TXT | Each 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 #
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:
subnetsholds the interface's addresses asaddress/prefix— the address itself, not the network it is in;demotedholds those of the scope's servers that are demoted at this moment (§4.6);- a scope's
levelis not reported.
5.3.6 flush #
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:
- A datagram whose source address is not a loopback address — anything
outside
127.0.0.0/8— is dropped without a reply. - It is checked as a query (below). A refused query gets its error reply, or nothing.
- 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 bothqueriesandrefused. This admission check precedes synthetic and cache lookup. - 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 #
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,
RDandCDbits, and setsQRandRA; every other bit is clear; - the question section is the query's, whatever it holds;
- when the query carried an
OPTrecord, the reply carries one whose payload size is the size the query advertised, withDOclear and no options; without one, the reply has none.
6.1.4 What an accepted query contributes #
- Only
INquestions 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, theDObit, 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,
RDandCDbits and its question section. QRandRAare set.AA,ADandTCare clear, except thatTCis 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
CNAMEfrom 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
foundwith no records at an expanded name isNOERRORwith only that leadingCNAME. Its TTL is the negative cache lifetime: the lesser of the enclosing upstreamSOArecord's TTL and minimum field, capped at 300 seconds and at the TTL of anyCNAMEpath the reply followed (§4.5). A cache hit uses the remaining lifetime, rounded down to whole seconds. With no enclosingSOA, the TTL is zero; no lifetime is invented. The authority section remains empty. An unexpanded emptyfoundhas noCNAME.
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
OPTadvertised, or 512 bytes when that is smaller or there is noOPT. - A reply over the limit is replaced by a truncated one, which keeps the
same header with
TCset, and the question. - The truncated reply keeps the
OPTrecord 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.2is installed bydev.peios.resolvd-nssat/usr/lib/x86_64-linux-peios/libnss_peios_net.so.2.- It is built from the
nsscrate, with the native channel codec compiled in. Its only shared-object dependencies arelibc.so.6and 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 loadlibgcc_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 point | Asks |
|---|---|
_nss_peios_net_gethostbyname4_r | lookup, family any |
_nss_peios_net_gethostbyname3_r | lookup, family from af |
_nss_peios_net_gethostbyname2_r | as gethostbyname3_r, with no TTL or canonical name out |
_nss_peios_net_gethostbyname_r | as gethostbyname3_r, with af AF_INET |
_nss_peios_net_gethostbyaddr2_r | reverse |
_nss_peios_net_gethostbyaddr_r | as 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 #
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
localhostor 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.1for IPv4,::1for IPv6, or both, IPv4 first, with canonical namelocalhostand 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 isNOTFOUND(§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:
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:
| Field | Content |
|---|---|
h_name | The reply's canonical name |
h_aliases | Empty |
h_addrtype | The af asked for |
h_length | 4 or 16 |
h_addr_list | Every 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). Afoundreply with no records isNOTFOUND(§7.1). - A found reply without a PTR record returns
NOTFOUND,ENOENT, andNO_DATA. ExplicitnotfoundreturnsHOST_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:
| Field | Content |
|---|---|
h_name | The first PTR record's name |
h_aliases | The remaining PTR records' names |
h_addrtype | The af asked for |
h_length | 4 or 16 |
h_addr_list | The 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 #
8.1.2.1 The command line #
--no-cacheis recognized anywhere on the command line and removed before the rest is matched; it affects onlyquery.- 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>ofqueryisAwhen omitted. It is one ofA,NS,CNAME,SOA,PTR,MX,TXT,AAAA,SRVorANY, in any case, orTYPE<n>for any type number from 0 to 65 535. - Any other
<type>printsresolv: unknown record type "<type>"and exits 1 without contacting resolvd. - The
<address>ofreverseis checked in the same way: anything that is not an IPv4 or IPv6 address printsresolv: "<address>" is not an addressand 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 #
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 #
| Signal | Tells you |
|---|---|
resolv status | Whether 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-cache | Where 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 resolv | 2 for notfound, 3 for unavailable, 1 when resolvd could not be asked (§8.1) |
| The door's own error | NXDOMAIN 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:
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 connectedandscopes (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_failedrising 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 #
| Door | What a client sees |
|---|---|
| NSS shim | localhost and loopback reverses still answer; everything else is UNAVAIL with NO_RECOVERY (§7.1) |
| Stub listener | Nothing listens on 127.0.0.53; UDP queries go unanswered or are refused by the kernel, TCP connections are refused |
resolv | Exit 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 fortcp,udp:53is not in the registry — its seed is inert until the image applies it (§2.1) — or something else already holds127.0.0.53:53. The error text says which.native socket: <error>:/run/resolvdcould 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 descriptorline. Ordinary programs cannot reach the socket at all. ControlSecurityholds a valid descriptor that does not grantRESOLVER_QUERYto them (§5.2). They reach the socket and are denied:resolv queryprintsresolv: 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 #
| Bound | Value | Described in |
|---|---|---|
| Native request size ceiling (payload) | 65 536 bytes | §5.1 |
| Maximum buffered native frame | 65 540 bytes | §5.1 |
| Native connection read chunk | 4 096 bytes | §5.1 |
| Native request delivery bound | 5 s | §5.1 |
| Native connections still sending a request | 256 | §5.1 |
| Queued native replies | 256 | §2.5 |
| Queued stub TCP replies | 256 | §2.5 |
| Native reply write deadline | 1 s total | §5.1 |
| Stub TCP connections still sending a query | 256 | §6.1 |
| Stub TCP query delivery bound | 10 s | §6.1 |
| Stub TCP message buffer | 65 537 bytes | §6.1 |
| Stub TCP read chunk | 4 096 bytes | §6.1 |
| Stub UDP read buffer | 4 096 bytes | §6.1 |
| Stub TCP reply write deadline | 1 s total | §6.2 |
Classic UDP reply limit, no OPT | 512 bytes | §6.2 |
| EDNS0 payload size advertised (upstream and stub) | 1 232 bytes | §4.7, §6.2 |
| Transaction timeout | 2 s | §4.6 |
| Attempts per question (all candidates and transports) | 3 | §4.6 |
| Demotion period | 30 s | §4.6 |
| Service descriptor limit | 16 384 | §2.1 |
| Listener retry delay after accept error | 250 ms | §2.5, §9.1 |
| Upstream transactions in flight | 4 096 | §4.6 |
| Upstream UDP read buffer | 4 096 bytes | §4.7 |
| Cache entries | 8 192 | §4.5 |
| Positive lifetime cap | 86 400 s | §4.5 |
| Negative lifetime cap | 300 s | §4.5 |
CNAME chase depth in lookup | 16 | §4.9 |
| netd reconnect backoff | 0.5 s doubling to 10 s | §3.2 |
| netd subscription write | Nonblocking | §3.1 |
resolv exchange deadline | 10 s total | §8.1 |
| Readiness notification deadline | 1 s | §2.1 |
| netd frame ceiling | 65 536 bytes | §3.1 |
| netd channel read chunk | 8 192 bytes | §3.1 |
| Registry watch event buffer | 16 384 bytes | §2.3 |
| Kernel hostname read buffer | 256 bytes | §3.3 |
| Unknown-value nesting depth, native requests | 32 | §5.1 |
| NSS shim read and write timeout | 10 s | §7.1 |
| DNS label | 63 bytes | §4.1 |
| DNS name on the wire | 255 bytes | §4.1 |
A.2 Rights #
| Right | Value | Described in |
|---|---|---|
RESOLVER_QUERY | 0x00000001 | §5.2 |
RESOLVER_CONTROL | 0x00000002 | §5.2 |
RESOLVER_ALL_ACCESS | 0x000F0003 | §5.2 |
A.3 Paths, addresses, and identities #
| Item | Value | Described 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 listener | 127.0.0.53:53 (UDP and TCP) | §2.4 |
| netd control socket | /run/netd/control.sock | §3.1 |
| Upstream port | 53 | §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 SID | S-1-5-80-3864064249-1823296737-2008945602-1354971773-2894779966 | §2.1 |
| Fallback scope key | fallback | §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 #
| Key | Value | Type | Default | Described in |
|---|---|---|---|---|
Machine\System\Network\Dns | FallbackServers | REG_MULTI_SZ (or one REG_SZ or REG_EXPAND_SZ) | none | §2.3 |
Machine\System\Network\Dns | ExtraSearchDomains | REG_MULTI_SZ (or one REG_SZ or REG_EXPAND_SZ) | none | §2.3 |
Machine\System\Network\Dns | ControlSecurity | REG_BINARY | the compiled default of §5.2 | §2.3, §5.2 |
Machine\System\Network\Dns\Hosts | any name: a static name | REG_SZ, REG_EXPAND_SZ, or REG_MULTI_SZ | none | §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).
| Seed | Key | Values |
|---|---|---|
resolvd-service.reg | Machine\System\Services\resolvd | ImagePath, Triggers, Identity, Readiness, RuntimeDirectories, RestartPolicy, ErrorControl, DisplayName, Description |
resolvd-port.reg | Machine\System\Network\TcpIp\PortReservations | tcp,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 #
| Resource | Default or bound |
|---|---|
| RADIUS declared packet length | At most 4096 bytes |
| Reassembled TLS message | At most 65536 bytes |
| Buffered inner AVPs | At most 4096 bytes |
| Inner username | 1 to 253 bytes |
| Inner password before padding removal | At most 1024 bytes |
| Configured shared secret | 16 to 1024 bytes |
| Idle conversation timeout | 30 seconds |
| Overall conversation deadline | Two minutes |
| Active conversations | 256 globally; 32 per client |
| Cached replies | 1024 for 15 seconds |
| Outgoing TLS fragment payload | 1000 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 #
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:
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:
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 #
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:
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.
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:
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:
| Entries | Raw targets |
|---|---|
bin/peinit2, bin/svctl | peinit: peinit2 svctl |
bin/authd, bin/lpsd, bin/lps | authd: authd lpsd lps |
bin/radiusd | radius: radiusd |
lib/libauth.so.1 | authd: libauth |
lib/libpeios.so.0 | peios-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:
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:
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:
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 \
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:
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:
In the guest, apply the prepared profile and rule, then run:
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:
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.
In the freshly initialized guest:
PEIOS_OFFLINE_VM_PROOF=yes
PEIOS_OFFLINE_VM_PROOF=yes
After binary activation and again after a clean shutdown and normal boot:
PEIOS_OFFLINE_VM_PROOF=yes
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:
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.
| Object | Purpose |
|---|---|
| Client | Source addresses, shared secret, and allowed policies |
| Access policy | Exact SSID, Connect permissions, profile, and reauthentication |
| Authentication profile | Ordered allowed methods and server identity |
| Server identity | Named certificate chain and matching private key |
| Access profile | Complete assignment settings, including an optional VLAN |
| Assignment rule | Policy-owned conditions, action, priority, and exceptions |
| Session control profile | Reusable 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 --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:
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:
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:
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:
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:
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:
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.
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.REJECTrefuses admission.NULLabstains. 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 #
| Fact | Meaning and type |
|---|---|
Subject.User | Authd-verified user SID |
Subject.Group | Authd-disclosed enabled group SIDs; any-member matching |
Subject.Name | Authd's canonical username; exact string |
Subject.Claim.<name>.<type> | Disclosed claim; explicit native type |
Client.Id | GUID of the configured client that verified the request |
Client.Address | Actual packet source IP address |
Request.SSID | Reported SSID bound to the selected access policy |
Request.Station | AP-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:
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:
--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:
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:
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:
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:
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.
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:
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.
| Workload | Window / batch | Completed per second | p99 latency |
|---|---|---|---|
| Synthetic TTLS/PAP, serial | 1 / none | 3,990 | 0.29 ms |
| Synthetic TTLS/PAP | 32 / none | 4,112 | 8.05 ms |
| Synthetic TTLS/PAP | 128 / none | 4,088 | 31.66 ms |
| Accounting Starts | 64 / 16 | 4,908 | 25.68 ms |
| Accounting Starts | 256 / 128 | 13,180 | 21.65 ms |
| Accounting Starts | 1,024 / 512 | 17,323 | 59.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:
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:
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:
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:
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.