# Reference

> Formats and constants, and the technical reference manuals that describe how each component works inside.

---

# Formats and Constants

_Peios / Reference / Interface References_

> Find the specification or owning implementation for a binary layout, access right, or numeric constant.

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](/specifications/pcds/sid/binary-format.md) |
| Globally unique identifier (GUID) | [PCDS GUIDs](/specifications/pcds/guid/binary-format.md) |
| Locally unique identifier (LUID) | [PCDS LUIDs](/specifications/pcds/luid/binary-format.md) |
| Self-relative security descriptor and its control flags | [SD Structure](/specifications/pcds/security-descriptor/structure.md) |
| Access control list (ACL) header and entries | [ACL Format](/specifications/pcds/security-descriptor/acl-format.md) |
| Access mask and generic-right interpretation | [Access Masks](/specifications/pcds/security-descriptor/access-masks.md) |
| Access control entry (ACE) types and bodies | [ACE Types](/specifications/pcds/security-descriptor/ace-types.md) |
| Inheritance and propagation flags | [Inheritance](/specifications/pcds/security-descriptor/inheritance.md) |
| Claims, resource attributes, and conditional expressions | [Security Descriptors](/specifications/pcds/security-descriptor/claim-attribute-format.md) |

PCDS describes the representation. The kernel's [descriptor and ACE
semantics](/kernel/userspace/native/kacs/descriptor-and-ace-semantics.md) and
[MS-DTYP compatibility notes](/kernel/userspace/native/kacs/ms-dtyp-compatibility-and-divergences.md)
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](/kernel/userspace/native/kacs/generated-token-and-session-abi.md) |
| Access checks, descriptors, central policies, and security-information flags | [Access-Check and Descriptor ABI](/kernel/userspace/native/kacs/generated-access-check-and-descriptor-abi.md) |
| File rights, create dispositions, and mount templates | [File and Mount ABI](/kernel/userspace/native/kacs/generated-file-and-mount-abi.md) |
| Process rights, process security blocks, and mitigations | [Process and PSB ABI](/kernel/userspace/native/kacs/generated-process-and-psb-abi.md) |
| Registry rights and key security | [Key and Security ABI](/kernel/userspace/native/lcs/generated-key-and-security-abi.md) |
| Registry watch records | [Watch ABI](/kernel/userspace/native/lcs/generated-watch-abi.md) |
| Event-ring records and constants | [KMES ABI](/kernel/userspace/native/kmes/generated-abi-tables.md) |

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](/kernel/userspace/native/kacs/abi-status-and-naming-differences.md) 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](/kernel/internals/kacs/privileges/privilege-catalogue.md) describes what
privileges enforce. Assignment and restriction remain separate questions:
[authd policy](/peios/using-peios/authentication/granting-access.md) supplies grants,
while [peinit privilege
restriction](/peios/reference/peinit/service-identity/privilege-restriction.md) removes
unrequested privileges using the names supported by that build.

Service-control rights belong to [Peinit's
constants](/peios/reference/peinit/constants-and-paths.md) and [service access
model](/peios/using-peios/services-and-jobs/who-can-manage-a-service.md). 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](/specifications/pspk.md) 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](/specifications/pspu.md). 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 and the only service manager on a Peios system — what makes it not systemd, the shape of the daemon, and what it is not.

peinit is PID 1. [*intro.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.
[*intro.every-supervised-process-is-forked-by-peinit]

It is a single-threaded Rust process.
[*intro.peinit-is-single-threaded] 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)
[*intro.the-registry-is-read-at-boot-and-on-reload] — 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.
[*intro.no-uid-gid-or-capability-is-set] 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.
[*intro.a-terminal-job-or-operation-is-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
[*intro.no-mounting-beyond-phase-1] — 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.
[*intro.forking-daemons-are-not-supported] 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_

> The scope of this manual, what in peinit is a contract and what is not, and where the constants and registry keys live.

This manual describes peinit as it is built: the boot sequence, the
service model and its registry schema, how a service acquires its
identity, the exact sequence between "start this" and "the binary is
running", the state machine and its causes, dependencies, jobs and
operations, timers, output handling, shutdown, and the security model.

## 1.2.1 What is a contract and what is not

Three of peinit's interfaces are specified separately. PSPU §4 gives
the **control socket**, spoken by administrative tools and by any
program that manages services or observes jobs, and the **notification
socket**, spoken by every service and every submitted job that reports
readiness, status, keepalives, or a stored descriptor. PSPU §7 gives
the **jobs socket**, spoken by any process that asks peinit to run and
supervise a program on its behalf. Those are contracts. A third party
implements one side of each, and what is written there binds both.

This manual covers the other side of that boundary — how peinit fulfils
them, and everything that is not a contract at all:

- how a command becomes an operation, and what happens when two of them
  collide (§8.2, §8.3)
- what a command does to a service in each state (§10.3)
- how a notification is authenticated and applied (§10.5, §10.6)
- how a submission becomes a running job, and what it is checked
  against afterward (§8.5, §10.7)

Where a chapter touches the contract it references PSPU §4 rather than
restating it.

The **service definition schema** is here rather than in PSPU. It is
registry configuration, protected by the registry's descriptors and
administered by the same tools as the rest of the registry, and it is
documented for the people who write service definitions rather than
specified as a wire format. §3.2 is the reference.

## 1.2.2 What this manual does not cover

- **KACS** — tokens, Security Descriptors, AccessCheck, and the
  per-service SID algorithm peinit reproduces. Peios Kernel TRM §3.
- **LCS** — the registry syscalls, watches, and layer resolution peinit
  reads through. Peios Kernel TRM §5.
- **KMES** — the ring buffer peinit emits its events into. Peios Kernel
  TRM §2.
- **loregd** — the storage behind registryd. Its own TRM.
- **eventd** — where the logs and events go. Its own manual.
- **authd** — token minting and identity routing. peinit's requirements
  of it are described in §4.3; its interface is authd's own.
- **How a token is conveyed on a socket, and what the kernel checks
  when it is** — peer-token capture, `KACS_SCM_TOKEN`, the
  impersonation gates, and the level ratchet that job submission relies
  on. Peios Kernel TRM §3.5.
- **Using peinit** — writing service definitions, the `svctl` command
  surface including `svctl job`, and everyday administration are
  covered in Using Peios.

## 1.2.3 Constants and keys

Registry keys and compiled-in constants are collected in the appendices,
so a chapter's reference material does not interrupt the prose that
explains it. Where an appendix defines a value the body references it
rather than repeating it.

---

# 1.3 Terminology

_Peios / Reference / peinit / Introduction_

> The terms this manual uses without redefining them, and where each is introduced.

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.
[*term.registryd-is-loregd]

**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/`.
[*term.a-submitted-job-is-under-the-jobs-cgroup]
§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 of anything — where it meets sd_notify, the fd store, calendar expressions and the Windows SCM, and what it deliberately omits.

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,
[*compat.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 [*compat.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,
[*compat.sub-second-precision-is-not-parsed] 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, [*compat.rlimit-nofile-and-core-are-the-only-limits] 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_

> The service, job and operation model, compatibility boundaries, event-loop invariant and dependencies of PID 1.

These design notes explain the boundaries behind the [operator
workflows](/peios/using-peios/services-and-jobs/overview.md). 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](/peios/using-peios/services-and-jobs/the-service-lifecycle.md)) 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](/kernel/internals/kacs/auditing/overview.md) as they complete, which is how the
history of a service is reconstructed after the fact. They get their own page:
[Jobs and operations](/peios/using-peios/services-and-jobs/jobs-and-operations.md).

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](/kernel/internals/kacs/tokens/the-token-model.md).
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](/peios/using-peios/services-and-jobs/identity-and-privileges.md).

## 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](/peios/developing-for-peios/sdk-registry/overview.md) 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](/kernel/internals/kacs/auditing/overview.md)'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](/peios/using-peios/services-and-jobs/output-and-logging.md).

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](/peios/using-peios/services-and-jobs/service-types.md); 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](/peios/using-peios/services-and-jobs/defining-a-service.md).
- **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](/kernel/internals/kacs/start-here/boot-and-trust-invariants.md): 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](/kernel/internals/kacs/access-check/the-dacl-walk.md). |
| **LCS / the registry** | Service definitions, boot configuration, and its own parameters. See [The registry](/peios/developing-for-peios/sdk-registry/overview.md). |
| **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](/peios/using-peios/boot/boot-and-boot-modes.md).) |
| **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](/peios/using-peios/services-and-jobs/jobs-and-operations.md). |

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](/peios/using-peios/boot/boot-and-boot-modes.md).

## 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](/peios/reference/peinit/service-identity/the-authd-path.md).** |
| 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-per-service-sid). The
minted token is fully independent — the [privilege
trimming](/peios/using-peios/services-and-jobs/identity-and-privileges.md#privilege-restriction)
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](/peios/using-peios/boot/boot-and-boot-modes.md). Standard eventd
and lpsd deployments now use `Identity=Service`, take the authd path, and
start after authd (§4.2).

> [!NOTE]
> There is no allow-list restricting which services *can* be `SYSTEM`. The
> security boundary is the [registry key
> descriptor](/peios/using-peios/services-and-jobs/who-can-manage-a-service.md) on
> `Machine\System\Services\` — an administrator who can create service
> definitions is already trusted to assign any identity, so a second gate
> would add nothing. The dangerous case is never *implicit*, though: `SYSTEM`
> must be written out explicitly; an empty `Identity` defaults to the minimal
> `LocalService`, never to SYSTEM.

### 1.5.6.2 The authd path

For any other identity, peinit asks
[authd](/peios/reference/peinit/service-identity/the-authd-path.md) for a token: it
sends the `Identity` value verbatim, and authd routes it to the right source —

- **Well-known principals** (`LocalService`, `NetworkService`, …) → a
  built-in identity with a predefined minimal privilege set;
- **Local service accounts** → lpsd, the local
  principal store;
- **Domain accounts** → the directory connector;

— resolves the principal's SIDs, mints a token, creates a logon session, and
hands the token back to peinit to install. peinit neither knows nor cares
whether the identity is local or domain; routing is authd's job.

authd records each request as an `authd.service.attested` event: the service
(`object.service.name`), the identity it got (`object.token.sid`), its session
and the privileges policy granted it. A refused request is recorded too, with
the reason, such as `account-restricted` for an identity that can not be used
for a service logon. The event is standard, so the emission policy can switch
it off on a machine that restarts services often.

> [!IMPORTANT]
> Every non-SYSTEM service start depends on authd. peinit interacts with it
> over a non-blocking, timed channel — if authd is unreachable or
> unresponsive, the service start *fails* rather than hanging PID 1. A broken
> authd therefore prevents non-SYSTEM service starts, including any platform
> service configured that way, while SYSTEM-minted services do not need this
> request. The authd interface is `ServiceAttest` on `/run/logon.sock`,
> specified in PGSS §2.19 and used through libauthd (§4.3).

## 1.5.7 The per-service SID

Every service token — minted or authd-issued — carries a **per-service SID**
in its group list. It uses authority `S-1-5-80` and is derived
deterministically from the service name: the SHA-1 of the uppercased name (as
UTF-16LE), with the digest split into five sub-authorities. authd adds it
automatically for the tokens it mints; peinit computes and adds it itself for
SYSTEM tokens, no authd involvement needed.

The point of the per-service SID is **fine-grained access control even when
services share an identity.** A dozen services might all run as `LocalService`
, but each has a *unique* service SID, so an ACL can grant access to exactly
one of them without inventing a dedicated account. It also keeps services
configured as SYSTEM distinguishable to
[AccessCheck](/kernel/internals/kacs/access-check/the-dacl-walk.md). 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](/peios/using-peios/services-and-jobs/execution-environment.md#the-fd-store).
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](/peios/using-peios/boot/shutdown.md);
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:

```text
/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](/peios/using-peios/services-and-jobs/the-service-lifecycle.md) 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](/peios/using-peios/services-and-jobs/supervision.md).

---

# 2.1 The Initramfs Contract

_Peios / Reference / peinit / Boot_

> peinit starts with the root already assembled — what the handoff guarantees, and everything that stays outside it.

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. [*handoff.peinit-performs-no-root-assembly]

## 2.1.1 The handoff

The initramfs transfers control by `chroot` -ing into the assembled root
and exec'ing peinit there. [*handoff.control-arrives-by-chroot-and-exec]
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`.
[*handoff.peinit-never-pivots]

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.
[*handoff.peinit-is-reached-through-bin-peinit2] 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. [*handoff.the-stratafs-views-exist-at-handoff]

At handoff:

- the real root is mounted **read-write** at `/`;
  [*handoff.the-root-is-mounted-read-write]
- `/proc`, `/sys`, and `/dev` are mounted and have been moved into the
  real root; [*handoff.proc-sys-dev-are-moved-into-the-root]
- the environment holds `TERM` and nothing else, and argv is
  peinit's own path. [*handoff.the-environment-holds-only-term]

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. [*handoff.the-read-write-requirement-is-registryds]

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).
[*handoff.peinit-passes-none-of-its-environment-on]

## 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. [*handoff.non-root-storage-is-not-peinits-concern]

> [!NOTE]
> The initramfs itself is assembled by mkirf from hook scripts that
> packages contribute; mkirf resolves the ordering and bakes the
> sequence its PID 1 runs. What peinit depends on is the handoff
> contract above, not how the initramfs arranged to satisfy it.

---

# 2.2 Bootstrap Identity

_Peios / Reference / peinit / Boot_

> The steady-state identity flow cannot start the system, so platform services run as SYSTEM until authd exists.

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).
[*bootstrap.a-system-identity-is-minted-by-peinit] No authd interaction
is involved — which is the point, since authd does not exist when the
first of these services starts.
[*bootstrap.a-system-identity-does-not-consult-authd]

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`.
<!-- lint-disable-next-line spelling -->
[*bootstrap.no-allowlist-governs-who-may-be-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).
[*bootstrap.a-minted-system-token-carries-the-per-service-sid] That is
what keeps platform services distinguishable to an access check despite
all of them running as `S-1-5-18`.

> [!NOTE]
> This is the same arrangement Windows uses: the SCM, LSASS, and the core
> platform services all run as LocalSystem. The trust anchor is that
> peinit *is* SYSTEM, and the kernel guarantees that by handing PID 1
> the boot token.

## 2.2.2 After authd

Once authd is running, every subsequent service gets its token
through the ordinary authd flow (§4.3).
[*bootstrap.after-authd-every-token-comes-from-authd] A definition with
no `Identity` field defaults to `LocalService` — a well-known principal
with a minimal privilege set [*bootstrap.identity-defaults-to-localservice]
— and authd adds the per-service SID to the token it mints.
[*bootstrap.authd-adds-the-per-service-sid]

---

# 2.3 Phase 1

_Peios / Reference / peinit / Boot_

> The compiled-in phase with no registry dependency, whose whole purpose is to reach the point where a registry can serve.

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 [*phase1.root-writability-is-probed]

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.
[*phase1.an-unwritable-root-is-recovery]

## 2.3.2 Step 2: Mount what is missing [*phase1.mounts-only-what-is-absent]

`/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 [*phase1.devpts-gets-a-synthesise-ephemeral-policy]:
`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
[*phase1.securityfs-gets-a-synthesise-ephemeral-policy]:

```text
O:SYG:SYD:(A;;GA;;;SY)(A;;GRGX;;;AU)
```

KACS publishes `kacs/self` and `kacs/sessions` there (see
[Logon
sessions](/kernel/internals/kacs/tokens/logonsessions-and-revocation.md)), 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. [*phase1.mountinfo-enoent-retries-after-mounting-proc] Any
other failure to read or parse mountinfo sends peinit to recovery.
[*phase1.unreadable-mountinfo-is-recovery]

For the three initramfs-provided rows, an already-mounted filesystem is
success, and so is an `EBUSY` from an attempted mount.
[*phase1.an-already-mounted-kernel-filesystem-is-success] For the five
peinit owns, a mount failure sends peinit to recovery.
[*phase1.a-failed-peinit-owned-mount-is-recovery]

After successful mount setup, peinit ensures `/run/lock` exists as a
directory. [*phase1.runtime-lock-directory-is-restored] 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.

<!-- lint-disable-next-line line-length -->
### 2.3.2.1 Seeding descriptors on the new filesystems [*phase1.fresh-mounts-are-seeded]

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:

```text
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.
[*phase1.seed-everyone-ace-is-container-inherit-only] 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.
[*phase1.a-failed-seed-is-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.
[*phase1.the-initramfs-filesystems-are-not-stamped]

### 2.3.2.2 Device node policy [*phase1.device-nodes-get-explicit-descriptors]

`/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
[*phase1.device-node-stamping-replaces-only-the-dacl] — 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. [*phase1.console-is-not-in-the-device-node-list]

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.
[*phase1.device-node-stamping-is-advisory]

<!-- lint-disable-next-line line-length -->
## 2.3.3 Step 3: Restore the persisted random seed [*phase1.the-random-seed-is-restored]

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.
[*phase1.an-absent-random-seed-is-silent] 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.
[*phase1.a-seed-that-cannot-be-credited-is-still-mixed] A seed file that
is empty, or larger than 4096 bytes, is treated as an error.
[*phase1.an-empty-or-oversized-seed-is-an-error]

Nothing in this step can send peinit to recovery.
[*phase1.no-seed-failure-enters-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 [*phase1.the-machine-id-is-ensured]

`/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. [*phase1.machine-id-format] A valid existing
file is left alone. [*phase1.a-valid-machine-id-is-left-alone] A file
that is absent, empty, all zeroes, the wrong length, not hexadecimal, or
missing its trailing newline is replaced
[*phase1.a-malformed-machine-id-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.
[*phase1.a-new-machine-id-is-written-atomically]

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.
[*phase1.a-csprng-failure-is-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
[*phase1.an-unpersistable-machine-id-is-fail-soft]:

```text
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.

<!-- lint-disable-next-line line-length -->
## 2.3.5 Step 5: Set the clock from the hardware RTC [*phase1.the-clock-is-set-from-the-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 [*phase1.rtc-falls-back-to-rtc0], 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.
[*phase1.the-rtc-is-read-as-utc]

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. [*phase1.any-rtc-failure-is-recovery]
Leaking a descriptor in PID 1 during
bootstrap is a symptom of something being badly wrong, not a detail to
swallow.

> [!NOTE]
> NTP corrects the clock properly later in the boot. This step only gets
> it into the right decade, so that early timestamps are not absurd and
> the timer subsystem has a wall clock to anchor to.

## 2.3.6 Step 6: Start registryd

peinit holds a compiled-in definition for registryd — the only compiled-in
service definition there is
[*phase1.registryd-is-the-only-compiled-in-definition]:

| 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.
[*phase1.registryd-is-started-like-any-service] 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.
[*phase1.registryd-start-has-two-thirty-second-timeouts]

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.
[*phase1.registryd-readiness-means-serving]

### 2.3.6.1 The schema-version guard [*phase1.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.
[*phase1.the-base-registry-structure-is-ensured-then-probed]

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. [*phase1.a-malformed-schema-version-fails-the-probe]
A key or value that is absent reads as zero and passes
[*phase1.an-absent-schema-version-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.
[*phase1.an-empty-service-key-boots-with-no-services]

### 2.3.6.2 Keeping registryd [*phase1.registryd-is-retained-as-a-runtime-instance]

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.
[*phase1.a-registry-definition-of-registryd-is-merged-not-restarted] 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.
[*phase1.no-registryd-is-recovery]

<!-- lint-disable-next-line line-length -->
## 2.3.7 Step 7: Autorun scripts [*phase1.autorun-scripts-run-between-registryd-and-provisioning]

Between registryd starting and path provisioning, peinit runs every
non-directory entry in `/lcl/policy/autorun.d`, in sorted order, by
absolute path [*phase1.autorun-runs-every-entry-in-sorted-order], with
the working directory `/` and `PATH=/sbin:/bin`
[*phase1.an-autorun-scripts-environment]. Each runs under peinit's own
SYSTEM token. [*phase1.autorun-scripts-run-as-system]

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. [*phase1.autorun-is-fail-open] Its
console output bypasses the quiet policy (§2.6), because a script that
ran this early and went wrong needs to be visible.
[*phase1.autorun-output-bypasses-the-quiet-policy]

The child's standard output and standard error share one pipe. peinit drains
that pipe before waiting for the child, so a script can write more than pipe
capacity to either stream without blocking behind an unread second pipe.
Writes reach the captured stream in pipe order; the child's own buffering
still controls when those writes happen. If reading fails, peinit attempts
to terminate and reap the child before reporting the failure.

## 2.3.8 Step 8: Provision boot-time paths

Covered in §2.4.

## 2.3.9 Step 9: Infrastructure setup

Three things, before Phase 2 begins:

1. **The control socket** at `/run/services/peinit/control.sock`, which
   serves every runtime command for the lifetime of the system, stamped
   so that any authenticated principal can connect and every command is
   then checked on its own (§10.1).
   [*phase1.the-control-socket-is-created]
2. **The jobs socket** at `/run/services/peinit/jobs.sock`, on which
   any authenticated principal can submit a job once Phase 2 runs,
   stamped so that connecting is the submission permission (§10.7).
   [*phase1.the-jobs-socket-is-created]
3. **Loopback**: peinit brings up `lo` over netlink, because services
   that bind `127.0.0.1` need it. [*phase1.loopback-is-brought-up]

Either socket failing to bind or to take its descriptor sends peinit to
recovery [*phase1.a-socket-failure-is-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.
[*phase1.a-loopback-failure-is-a-warning]

## 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_

> Filesystem objects belonging to no single service — how entries are declared, what descriptors they get, and what failure does.

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. [*provision.runs-after-registryd-and-before-phase-2]

## 2.4.1 Entries

Each child key under `Machine\System\Init\ProvisionedPaths\` is one
entry. [*provision.each-child-key-is-an-entry] Unknown values on an entry
are ignored. [*provision.unknown-values-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.
[*provision.kind-decides-what-is-ensured] In either case a path that
exists with a different file type fails the entry.
[*provision.a-type-mismatch-fails-the-entry] An existing file is opened
rather than created, so provisioning never truncates one.
[*provision.an-existing-file-is-never-truncated]

peinit does not create parent directories. The parent is checked, and has
to already be a directory. [*provision.parents-are-not-created] 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. [*provision.a-supplied-descriptor-is-applied] A malformed or
rejected descriptor fails the entry.
[*provision.a-bad-descriptor-fails-the-entry]

When it is absent, peinit applies a built-in default
[*provision.the-built-in-default-descriptor]:

```text
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.
[*provision.an-optional-entry-is-fail-soft] Entries with `Required=1` are
fail-closed: peinit logs and enters recovery before Phase 2 starts.
[*provision.a-required-entry-that-fails-is-recovery]

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`.
[*provision.a-malformed-entry-is-skipped-whatever-required-says]
`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_

> The registry-driven phase — reading the definitions, building and validating the graph, starting it, and deciding the boot succeeded.

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\`.
[*phase2.definitions-come-from-the-services-key] The reads are bounded by
LCS's request timeout: if registryd hangs mid-read, peinit receives
`ETIMEDOUT` and enters recovery. [*phase2.a-registry-read-timeout-is-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`.
[*phase2.an-undecodable-definition-fails-only-that-service] 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.
[*phase2.only-boot-triggered-services-are-roots] 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.
[*phase2.a-demand-only-service-can-still-be-pulled-in] 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. [*phase2.a-disabled-service-is-loaded-but-not-booted]

## 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.
[*phase2.the-boot-graph-is-the-roots-transitive-closure] `Requires` and
`BindsTo` pull their target in even if the target has no `boot` trigger.
[*phase2.a-hard-dependency-pulls-in-an-untriggered-target] `Wants`
targets come in as best-effort members; missing or disabled ones are
ignored. [*phase2.a-missing-wants-target-is-ignored] A missing or
disabled `Requires` or `BindsTo` target blocks the dependent with cause
`DependencyFailure`, and that blocking propagates.
[*phase2.a-missing-hard-dependency-blocks-and-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.
  [*phase2.a-cycle-fails-every-service-in-it]
- **An unresolvable conflict** fails both services. Same downgrade if
  either is Critical. [*phase2.a-conflict-fails-both-services]
- **A missing `Requires` target** fails the dependent.
- **Warnings** — a `Readiness=Alive` service with dependents that
  require it — are logged and do not prevent boot: a `[ WARN ]`
  `peinit warning:` line on the console and a
  `peinit.graph.validation.warned` event under phase `boot`, whether or
  not the same graph also has
  findings. [*phase2.a-validation-warning-does-not-prevent-boot]

## 2.5.3 Starting

peinit walks the graph and starts services, parallelising wherever the
graph allows, up to a configurable limit:

| Key | Default | Meaning |
|---|---|---|
| `Machine\System\Boot\MaxParallelStarts` | 10 | Services starting concurrently. [*phase2.maxparallelstarts-bounds-concurrency] |

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 [*phase2.an-invalid-maxparallelstarts-is-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.
[*phase2.a-satisfying-state-releases-dependents] A Oneshot without
`RemainAfterExit` passes through Completed, releasing its dependents, and
then goes Inactive.
[*phase2.a-oneshot-releases-dependents-before-going-inactive]

Dependents blocked on a `Requires` or `BindsTo` target wait for that
target to reach a satisfying state.
[*phase2.a-hard-dependent-waits-for-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. [*phase2.a-wants-dependent-waits-only-for-a-terminal-state]

### 2.5.3.1 The typical order

Nothing below is hardcoded. It falls out of the dependency graph that
the standard role definitions produce, and an administrator who changes
a dependency gets a different order.

1. **eudev** — device management. SYSTEM, with `RequiredPrivileges`
   stripped to the minimum it needs. Starts before authd exists.
2. **lpsd** — the local identity database. Depends only on registryd.
3. **authd** — the identity authority. Depends on registryd and lpsd.
   Once it is ready, token minting is available.
4. **eventd** — logging and audit. Services started before it sign in to
   peinit's pre-eventd buffer.
5. **Networking** — the first service to receive a token from authd.
6. **Application services**, in dependency order.
7. **Sign-in services**, last, so the system is operational before it
   accepts a session.

### 2.5.3.2 The bootstrap matrix

| 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. [*settle.a-deferred-service-is-outside-the-boot-plan]

"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. [*settle.which-states-count-as-settled] Starting,
Reloading, Stopping and **Backoff** do not, because a service between
restart attempts is going to produce more output.
[*settle.backoff-is-not-settled]

A deadline bounds the wait:

| Key | Default | Meaning |
|---|---|---|
| `Machine\System\Boot\SettleTimeout` | 5 | Seconds before deferred services start regardless. [*settle.settletimeout-bounds-the-wait] |

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. [*settle.an-invalid-settletimeout-is-recovery] Zero
is legal and means "start on the next turn, settled or not".
[*settle.a-settletimeout-of-zero-is-legal]

Whichever comes first — the set settling or the deadline expiring — the
deferred services start, once, each independently.
[*settle.deferred-services-start-once-each] A start that fails is
recorded and dropped: one refusing service does not stop the others and
does not affect the boot.
[*settle.a-failed-deferred-start-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. [*settle.the-dispatch-says-whether-the-deadline-expired]

> [!NOTE]
> The motivating case is a console sign-in prompt being scribbled over by
> peinit's own progress messages. That is a scheduling preference, not a
> dependency — the prompt does not *require* anything to have started,
> it wants the console to itself. Expressing it as a dependency
> would mean naming every service that might print, which changes every
> time the system does.

## 2.5.5 Boot success

A boot is successful once every Critical service has held a
dependent-satisfying state continuously for a grace period:

| Key | Default | Meaning |
|---|---|---|
| `Machine\System\Boot\BootSuccessGrace` | 30 | Seconds of held health before the boot counts. [*success.the-grace-period-must-be-held-continuously] |

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.the-criterion-is-satisfying-not-active]

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](/peios/reference/peinit/boot/boot-modes.md).

---

# 2.6 Boot Modes

_Peios / Reference / peinit / Boot_

> Full, Safe,  and Recovery — the escalation path from normal operation to last-resort maintenance, and what causes each downgrade.

peinit boots in one of three modes, forming an escalation path from
normal operation to last-resort maintenance.

```text
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 [*mode.full-is-the-default]

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.
[*mode.safe-does-not-start-a-service-with-no-boot-trigger] 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.
  [*mode.safe-starts-critical-services]
- **`SafeMode=1` services** are attempted best-effort. If one fails,
  Safe mode continues without it.
  [*mode.safe-attempts-safemode-services-best-effort]

`ErrorControl=Critical` implies `SafeMode`, so a Critical service does
not have to declare both. [*mode.critical-implies-safemode]

### 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".
[*mode.a-service-excluded-from-the-rebuild-is-not-marked-failed]

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.
[*mode.a-service-that-survives-the-rebuild-can-still-fail-there]

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.
[*mode.the-downgrade-reason-is-recorded-at-boot-level]

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.
[*mode.every-downgrade-finding-is-reported]

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.
[*mode.safe-drops-dependencies-on-excluded-services] 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.
[*mode.a-successful-safe-boot-resets-the-counter]

> [!NOTE]
> Safe mode is purely a boot-sequencing concern. Once booted, an
> administrator starts anything by hand exactly as in Full mode. It is
> for a system whose configuration is broken but whose TCB is healthy.

### 2.6.2.2 Entry

- **A cycle involving a Critical service at boot.** Graph validation
  detects it and peinit downgrades in place, without rebooting — the
  cycle is a configuration error, and rebooting would find it again.
  [*mode.a-critical-cycle-downgrades-in-place]
- **An unresolvable conflict involving a Critical service at boot.**
  Same reasoning. [*mode.a-critical-conflict-downgrades-in-place]
- **`peios.safemode=1`** on the kernel command line.
  [*mode.safemode-can-be-forced-from-the-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.
[*mode.a-runtime-critical-failure-does-not-enter-safe-mode]

## 2.6.3 Console output

`peios.quiet=N` bounds what peinit writes to the console:

| Value | Behavior |
|---|---|
| `0` | Write unconditionally. [*quiet.zero-writes-unconditionally] |
| `1` | Do not write to a terminal held as the controlling terminal of a running service, except to announce loss of the system. This is the default. [*quiet.one-is-the-default-and-respects-terminal-ownership] |
| `2` | Additionally drop ordinary progress everywhere, while still emitting errors. [*quiet.two-drops-progress-but-not-errors] |

The two rules are independent, and an error is never less visible at `2`
than at `1`. A terminal is matched by device rather than by path, since
`/dev/console` and `/dev/ttyS<n>` can name the same device
[*quiet.a-terminal-is-matched-by-device-not-path]; where the device
cannot be determined, peinit treats the terminal as free and writes to
it. [*quiet.an-undeterminable-device-is-treated-as-free] 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.
[*quiet.suppressed-messages-are-discarded]

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

| Parameter | Effect |
|---|---|
| `peios.safemode=1` | Force Safe mode. |
| `peios.recovery=1` | Force recovery mode regardless of the counter. [*cmdline.recovery-forces-recovery-mode] |
| `peios.bootattempts=N` | Set the recovery threshold; `0` disables the check. [*cmdline.bootattempts-sets-the-threshold-and-zero-disables-it] |
| `peios.quiet=N` | Console verbosity, as above. |
| `peios.notifysocket=PATH` | Override the notification socket path. [*cmdline.notifysocket-overrides-the-socket-path] |

A malformed value is ignored in favor of the default rather than
failing the boot. [*cmdline.a-malformed-value-falls-back-to-the-default]
Nothing exists this early to report a diagnostic to.

---

# 2.7 The Boot Attempt Counter

_Peios / Reference / peinit / Boot_

> The on-disk counter that turns a repeated failure into an escalation — its cycle, and the threshold that reaches Recovery.

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 [*attempts.the-counter-is-a-file-on-the-root]
— 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. [*attempts.the-threshold-is-checked-pre-increment]

- **Absent file:** treated as 0. [*attempts.an-absent-counter-is-zero]
- **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.
  [*attempts.an-unreadable-counter-is-recovery]

peinit increments once per boot, after the root is known writable and
before Phase 2 begins. [*attempts.the-counter-increments-once-per-boot]
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.
[*attempts.an-early-recovery-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. [*attempts.a-write-failure-reads-as-zero]

The counter resets to 0 on a successful Full or Safe boot, after the
grace period. [*attempts.a-successful-boot-resets-the-counter]

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. [*attempts.the-default-threshold-is-three] 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.
[*attempts.a-threshold-of-zero-disables-the-check]

`peios.recovery=1` forces recovery without consulting the counter, but
does not suppress the increment.
[*attempts.forced-recovery-still-increments]

> [!NOTE]
> The counter catches boots where peinit runs but the system never
> reaches health — a crash-looping Critical service being the usual
> case. It deliberately does not try to catch a peinit too broken to
> reach its own increment. Recovery mode is itself a peinit mode, so a
> peinit that cannot start cannot deliver recovery either, and a higher
> count could not help. That failure belongs to binary integrity, not to
> the counter.

---

# 2.8 Recovery Mode

_Peios / Reference / peinit / Boot_

> The last resort — no TCB guarantee, an administrator shell, registry recovery limits, and console access.

Recovery mode is the last resort. There is no TCB guarantee and no
degraded boot to speak of — it is a maintenance environment that hands
the administrator an unrestricted SYSTEM shell on the console.

## 2.8.1 Entry

- The boot attempt counter reaching the threshold (§2.7).
- `peios.recovery=1` on the kernel command line.
- Any of the Phase 1 failures listed in §2.3, most importantly a
  registryd that will not start or will not serve.
- A Phase 2 registry read that fails or times out, or invalid boot
  configuration.
- A required provisioned path that cannot be created or secured.
- The runtime loop failing on an error about supervision itself: the
  event wait, event source registration, a listener, the event ring
  refusing even the small `peinit.event.dropped`, shutdown finalization. An
  error peinit can attribute to one service is contained to that
  service instead and does not enter recovery (§8.2).

## 2.8.2 What peinit does

peinit records the reason as a `peinit.recovery.entered` KMES event —
`essential`, so no emission policy switches it off — with the reason in
`outcome.reason` and what went wrong, in the error's own words, in
`outcome.detail`; a Phase 2 plan that would not build adds its finding
as a `peinit.graph.validation.failed` under phase `phase2-boot`
[*recovery.the-reason-is-audited], then:

1. Completes Phase 1 steps 1–5 if they have not been reached yet.
2. Ensures the base registry structure exists, so the shell sees a
   normal layout even on a system that has never been provisioned.
   [*recovery.the-base-registry-structure-is-ensured]
3. Attempts to start registryd. A failure here is ignored — recovery
   delivers a shell whatever registryd's state.
   [*recovery.a-registryd-failure-does-not-prevent-the-shell]
4. Skips all Phase 2 services. [*recovery.no-phase-2-service-starts]
5. Starts a shell on `/dev/console` from a compiled-in definition, with
   no registry dependency: `/bin/recsh` if it is present and
   executable, otherwise `/bin/sh` [*recovery.recsh-is-preferred-over-sh],
   running as SYSTEM with a fixed environment of `PATH=/sbin:/bin`,
   `TERM=linux` and `HOME=/`. [*recovery.the-shells-environment] peinit
   does not care where either binary comes from.
6. Logs the failure reason to the console.
   [*recovery.the-reason-reaches-the-console]

If the shell exits, peinit respawns it. Recovery never exits to an
unmanaged PID 1. [*recovery.the-shell-is-respawned]

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.
[*recovery.no-shell-at-all-syncs-and-halts] 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.
[*recovery.the-shell-is-not-a-session-leader]

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.
[*recovery.phase-1-steps-are-retried-idempotently]

Step 3 runs only if Phase 1 has not already reached its own registryd
start, and it runs at most once.
[*recovery.recovery-starts-at-most-one-registryd] 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.
[*recovery.a-recovery-registryd-uses-this-boots-settings]

> [!NOTE]
> Recovery mode is not a degraded boot; it is a maintenance environment.
> There are no security protections beyond what the kernel provides. The
> administrator has a SYSTEM shell and the corresponding responsibility.

## 2.8.3 Registry diagnosis and recovery limits

Recovery provides a console maintenance shell when one is available as
described above; it does not define an offline storage-repair interface
for the registryd provider. Preserve the console failure reason
and source startup output, then identify the deployed provider and version,
its hive declarations, and the actual database paths. See
[LCS and sources](/peios/developing-for-peios/registry-sources/overview.md).

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](/peios/reference/loregd/startup/exit-and-shutdown.md)
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](/peios/reference/loregd/startup/command-line.md#unsupported-recovery-switches)
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](/peios/reference/loregd/startup/startup-sequence.md#backup-and-repair-limits).
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](/kernel/internals/lcs/backup-and-restore/overview.md)
workflow is separate: LCS coordinates operations through a working source.
[Backup](/kernel/internals/lcs/backup-and-restore/backup.md) requires a read-only snapshot
transaction; [restore](/kernel/internals/lcs/backup-and-restore/restore.md) replaces a
target
subtree, including descriptors, in a read-write transaction. Neither is a
way to repair a source that cannot serve those operations.

> [!NOTE]
> `/bin/recsh` exists so a system can ship a purpose-built recovery
> shell — one that bundles the offline registry tools, presents
> guidance, or curates a command set — without making it mandatory.
> `/bin/sh` is the floor where it is absent. peinit treats both as
> opaque executables.

## 2.8.4 Remote recovery

Recovery requires console access: physical, IPMI, or serial. Two
post-v1 features address headless servers — rolling the registry back to
a last-known-good state from the recovery shell, and an emergency sshd
started without registry involvement.

---

# 3.1 Services

_Peios / Reference / peinit / The Service Model_

> The primary unit of management — names, the two service types, and how a forking daemon differs from a simple one.

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. [*svc.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.
[*svc.a-name-is-1-to-128-bytes-of-the-name-alphabet]

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. [*svc.a-simple-services-main-process-is-the-service] 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. [*svc.notify-waits-for-ready-and-alive-does-not]

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. [*svc.a-oneshots-readiness-field-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`.
[*svc.a-oneshot-succeeds-on-zero-or-a-listed-code]

The differences from Simple are:

- A successful exit goes to Completed. With `RemainAfterExit=1` it stays
  there; [*svc.remainafterexit-holds-a-completed-oneshot] without, it
  passes through Completed to release dependents and then goes Inactive.
- A non-zero exit goes to Failed. [*svc.a-nonzero-oneshot-exit-is-failed]
- `ExecStartPost` runs after the successful exit rather than after a
  readiness signal, and does not run at all if the Oneshot failed.
  [*svc.a-oneshots-post-hooks-run-after-a-successful-exit]
- `StartTimeout` covers the entire execution, from the first pre-hook to
  the process exiting.
  [*svc.a-oneshots-starttimeout-covers-the-whole-execution]

`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.
[*svc.supervision-follows-the-forked-child] There is no `MAINPID=`, and
no way to point supervision at a different process.
[*svc.there-is-no-mainpid]

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 default, and why decoding is all-or-nothing.

Every field a service definition can carry, with its registry type and
its default. [*schema.the-field-table] The semantics of each are in the
section named alongside.

Value names are matched case-insensitively, so `ImagePath` and
`imagepath` are the same field
[*schema.value-names-are-matched-case-insensitively]
— 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. [*schema.a-type-mismatch-is-a-decode-error] So is a dword
carrying a value outside an enumerated field's range.
[*schema.a-dword-outside-an-enumerated-range-is-a-decode-error]

## 3.2.2 Schema version and forward compatibility

`Machine\System\Services\SchemaVersion` is a dword, 1.
[*schema.the-services-schema-version-is-one] peinit creates it if it is
absent (§2.3).

Unknown values on a service key are ignored,
[*schema.an-unknown-value-on-a-service-key-is-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.
[*schema.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,
[*schema.a-duplicate-known-field-is-a-decode-error] 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).
[*schema.a-decode-failure-fails-only-that-service-on-reload]

---

# 3.3 Field Formats

_Peios / Reference / peinit / The Service Model_

> How a field's value must be written, as distinct from what it means — strings, identity, privileges, directories,  and environment.

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. [*fmt.a-present-string-field-is-non-empty]
Three fields treat the empty string as absence:
[*fmt.three-fields-treat-the-empty-string-as-absence]

- `Identity` — empty is the same as absent, and defaults to
  `LocalService`.
- `HookIdentity` — empty is the same as absent, and falls back to the
  service's `Identity`.
- `DisplayName` and `Description` — empty is the same as absent.

`WorkingDirectory`, when present, is a non-empty absolute path.
[*fmt.workingdirectory-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.
[*fmt.workingdirectory-existence-is-checked-at-start-not-at-read]

`TTYPath` is checked for emptiness before absoluteness: an empty value
means no terminal, and a non-empty relative path is rejected.
[*fmt.an-empty-ttypath-means-no-terminal-and-a-relative-one-is-rejected]

## 3.3.2 Identity and HookIdentity

Either a well-known principal name — `SYSTEM`, `LocalService`,
`NetworkService` — matched case-insensitively and canonicalised,
[*fmt.a-well-known-identity-is-matched-case-insensitively], 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.
[*fmt.privilege-names-are-matched-case-sensitively]

## 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.
[*fmt.a-runtime-directory-entry-is-one-relative-name]

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.
[*fmt.hooks-do-not-cause-runtime-directory-provisioning]

If creation or descriptor assignment fails, the start fails with
`ParentSetupFailure`.
[*fmt.a-failed-runtime-directory-is-a-parent-setup-failure]

peinit does not remove runtime directories when a service stops.
[*fmt.runtime-directories-are-not-removed-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.
[*fmt.an-environment-entry-is-key-equals-value]

## 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.
[*fmt.a-success-exit-code-is-a-decimal-integer-0-to-255] 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
[*fmt.an-illegal-dependency-name-is-a-decode-error] — 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.
<!-- lint-disable-next-line spelling -->
[*fmt.a-list-dependency-may-carry-a-level] `OnFailure` takes a bare
service name and no level: it names a handler to run, not a state to
wait for. [*fmt.onfailure-takes-no-level]

## 3.3.8 Timeouts and intervals

Every timeout and interval in the schema is in whole seconds unless the
field says otherwise. [*fmt.timeouts-and-intervals-are-in-whole-seconds]
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. [*fmt.generated-identifiers-are-uuidv7] UUIDv7 is
time-ordered, so identifiers sort by creation time
[*fmt.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_

> What makes a service start by itself — the trigger kinds, how arity is enforced, and how the set is extended.

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. [*trig.triggers-are-independent-of-service-type]

`Triggers` is a multi_string, each entry either `type` or
`type:argument`. [*trig.a-trigger-entry-is-a-type-or-a-type-and-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.
[*trig.multiple-triggers-of-one-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.
[*trig.boot-accepts-only-the-listed-sub-triggers] `tty` carries the same
rule: the bare word names no event, and `tty:` accepts only `released`.
[*trig.a-bare-tty-is-malformed-and-tty-accepts-only-released] `timer`
with no schedule is malformed, as is `timer:` with an empty one.
[*trig.a-timer-with-no-schedule-is-malformed]

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
[*trig.tty-released-without-a-ttypath-is-refused] — 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.
[*trig.ttyprecedence-without-a-ttypath-is-refused] Emptying `TTYPath`
(§3.3) takes both down with it.
[*trig.emptying-ttypath-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.
[*trig.disabled-suppresses-every-trigger] A disabled service's timers
are neither armed nor serviced.
[*trig.a-disabled-services-timers-are-not-armed]

The definition is still loaded into the in-memory model, and an explicit
start still works. [*trig.a-disabled-service-can-still-be-started-explicitly]
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,
[*trig.a-new-trigger-type-needs-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_

> Two start-time checks in the same form over the same four check types, differing only in what a failure means.

Both are start-time checks in the same `type:argument` form, over the
same four check types. [*check.the-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, [*check.a-skipped-service-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`
[*check.a-failed-assert-fails-the-service-with-assertionerror] — the
service was expected to run and a precondition it depends on is missing.

All entries of a kind are AND'd. [*check.entries-of-a-kind-are-anded]
Conditions are evaluated first; asserts only if every condition passed.
[*check.conditions-are-evaluated-before-asserts] Both are evaluated
before dependency resolution and before any pre-exec hook,
[*check.checks-precede-dependency-resolution-and-the-hooks] and an entry
with an empty argument or an unrecognized type is a decode error.
[*check.an-empty-argument-or-unknown-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. [*check.a-registry-check-must-name-a-cached-key]

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.
[*check.a-services-registry-check-is-a-service-existence-test]

### 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**
[*check.a-check-that-does-not-report-in-time-is-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.
[*check.the-result-is-cached-for-the-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_

> The four fields holding executable commands, how all four are parsed, how the executable is located, and ExecReload signals.

Four fields hold executable commands: `ExecStartPre`, `ExecStartPost`,
the command form of `ExecReload`, and `HealthCheck`. All four are parsed
the same way. [*cmdstr.the-four-command-fields-are-parsed-alike]

## 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. [*cmdstr.there-is-no-shell] 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,
[*cmdstr.whitespace-is-exactly-six-ascii-characters] 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`.
[*cmdstr.quotes-group-and-are-not-retained] An empty quoted string is
preserved as an empty argv entry.
[*cmdstr.an-empty-quoted-string-is-an-empty-argv-entry]

Backslash has no escape semantics and is copied literally. A single
quote is an ordinary character.
[*cmdstr.a-backslash-and-a-single-quote-are-ordinary-characters]

An empty or whitespace-only command is invalid,
[*cmdstr.an-empty-or-whitespace-only-command-is-invalid] and so is an
unclosed double quote. [*cmdstr.an-unclosed-double-quote-is-invalid]

## 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. [*cmdstr.argv0-must-be-an-absolute-path] Everything after
argv[0] is an opaque string and is not path validated.
[*cmdstr.arguments-after-argv0-are-not-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.
[*cmdstr.a-reload-signal-is-an-exact-canonical-name]

`SIGKILL` and `SIGSTOP` are invalid for reload,
[*cmdstr.sigkill-and-sigstop-are-not-reload-signals] 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: [*cmdstr.the-accepted-reload-signal-set]

`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. [*cmdstr.an-absent-execreload-means-sighup]

---

# 3.7 Configuration Generations

_Peios / Reference / peinit / The Service Model_

> peinit operates on snapshots rather than a live registry view — the boot and activation generations, field mutability, and pinning.

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.
[*confgen.peinit-answers-from-the-model-rather-than-the-registry]

> [!NOTE]
> The model exists because the event loop cannot block on a userspace
> service during normal supervision. In single-threaded PID 1
> a blocking syscall blocks everything — child reaping, watchdog expiry,
> shutdown signals, every other event stops while the syscall is stuck.
> Reading the registry means waiting on registryd, and registryd is a
> service peinit supervises.

Change notifications arrive as events on a pollable descriptor. peinit
subscribes to `Machine\System\Services\` and `Machine\System\Init\` at
boot, [*confgen.the-watch-covers-services-and-init] 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.
<!-- lint-disable-next-line line-length -->
[*confgen.a-write-during-the-boot-window-is-deferred-for-an-unlaunched-service]

## 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.
[*confgen.a-field-changed-while-starting-takes-effect-at-the-next-start]

A service in Inactive or Failed has no activation snapshot, so starting
it uses the current model.
[*confgen.an-inactive-service-starts-from-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:
[*confgen.the-pinned-fields]

`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
<!-- lint-disable-next-line line-length -->
[*confgen.triggers-and-disabled-take-effect-at-once-on-a-service-that-is-not-running]
— 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: [*confgen.the-next-start-fields]

`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:
[*confgen.the-runtime-reloaded-fields]

`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_

> What happens when a definition disappears from the registry, depending on whether the service is running.

When a definition disappears from `Machine\System\Services\`, peinit
learns of it through the ordinary change-notification path.
[*remove.a-removal-arrives-through-the-watch] 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.
[*remove.a-non-running-entry-is-discarded-immediately]
There is no process to consider.

Backoff belongs in this list rather than the next one,
[*remove.backoff-is-discarded-like-any-other-non-running-state] 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. [*remove.a-running-instance-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.
[*remove.the-entry-is-marked-definition-removed] 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.
[*remove.an-exit-is-not-restarted-and-the-entry-is-discarded]

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.
[*remove.a-removal-leaving-a-dangling-dependency-is-refused]

While an entry is definition-removed:

- `stop` is accepted, so an administrator can drain it cleanly, using
  the cached `StopTimeout`;
- `start`, `restart`, and `reload` are rejected with `UNKNOWN_SERVICE` —
  there is no definition to work from;
- `status` reports the current runtime state with `definition_removed`
  set, so the draining instance is visible rather than silent.

`definition-removed` is a flag on the existing runtime state, not a
state of its own. The state machine (§6.1) and the command × state
matrix (§10.3) are unchanged by it.

A `restart` already in its stop phase is a case of its own. The stop
phase still drains the existing instance; the start phase does not
begin, because there is nothing to start from. When the instance exits,
the operation is aborted with the reason
`definition_removed_during_restart_stop_leg` and the entry takes the
ordinary removal discard. [*remove.a-restart-in-its-stop-leg-is-aborted]
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. [*remove.a-crash-is-routed-to-failed-rather-than-a-restart] 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 — where peinit obtains or creates it, and where it is installed.

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. [*identity.a-service-never-shares-peinits-token]

Which route the token comes from depends on the `Identity` field:

| Identity | Source | Mechanism |
|---|---|---|
| `SYSTEM` | Minted by peinit from its own identity | `kacs_create_token`. §4.2 |
| `Service` | authd | A virtual account unique to this service. §4.3 |
| `LocalService` / `NetworkService` | authd | A shared service account, with this service's SID as a group. §4.3 |
| Another principal | authd | A principal designated for service logon. §4.3 |
| Absent or empty | authd | Defaults to `LocalService`. [*identity.an-absent-identity-defaults-to-localservice] |

peinit reads its own token with `kacs_open_self_token` requesting the
real token rather than any impersonation, and opens it query-only: it is
a template to copy from, never a thing to hand out.

<!-- lint-disable-next-line line-length -->
## 4.1.1 Where a token is materialised [*identity.materialisation-is-per-launched-process]

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.

| Context | Identity used |
|---|---|
| Main process | `Identity` |
| `ExecStartPre` / `ExecStartPost` | `HookIdentity` if set, otherwise `Identity` [*identity.hooks-use-hookidentity-when-set] |
| Health checks | `Identity`, always [*identity.health-checks-always-use-identity] |
| `ExecReload` external command | `Identity`, always [*identity.execreload-always-uses-identity] |
| Submitted jobs | The prepared primary token: the submitter's own, or the token the kernel attached to the submission (§8.5) |

Health checks and reload commands deliberately do not honor
`HookIdentity`. A health check reports on the service's own health and
should see what the service sees; a reload command acts on the running
service. `HookIdentity` exists for setup work — creating directories in
privileged locations, running a migration — which is a different job
from either.

> [!NOTE]
> `HookIdentity` typically grants *more* than the service itself.
> peinit does not validate filesystem permissions on hook binaries, so
> where it grants elevated privileges the administrator is responsible
> for the hook binary and its parent directories not being writable by
> anything lower-privileged.

If materialisation fails at any point — authd unreachable, an identity
that cannot be resolved, a KACS error — no child exists yet, and the
start fails with `ParentSetupFailure` for the main process or
`PreHookFailure` for a hook.
[*identity.a-materialisation-failure-fails-the-start]

---

# 4.2 The SYSTEM Path

_Peios / Reference / peinit / Service Identity_

> peinit mints SYSTEM tokens itself, which is what breaks the bootstrap circle for registryd and authd.

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 [*token.minting-copies-peinits-own-token]

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.
[*token.the-mint-requires-secreatetokenprivilege]

Two details of the copy matter.

**The logon session comes from the token's statistics.**
[*token.the-logon-session-comes-from-the-token-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.**
[*token.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.**
[*token.the-service-sid-and-service-group-are-added] 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.**
[*token.the-minted-token-carries-the-system-default-dacl] 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](/peios/reference/peinit/boot/bootstrap-identity.md)),
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.
[*token.the-template-must-be-a-primary-system-token] 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.
[*token.the-minted-token-is-independent-of-peinits]

> [!NOTE]
> Minting is an interim mechanism. The intended model is for peinit to
> *derive* the token from its own handle, through a KACS
> duplicate-with-additions operation — kernel-attested as a descendant
> of peinit's real token, and requiring no token-minting privilege at
> all. That operation does not exist in KACS yet, so peinit mints.

---

# 4.3 The authd Path

_Peios / Reference / peinit / Service Identity_

> Every non-SYSTEM token comes from authd — what peinit sends, what it must never do to obtain one, and why the token it gets back is deliberately weaker.

For any identity other than `SYSTEM`, the token comes from authd.
[*token.a-non-system-identity-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 [*token.the-request-is-a-serviceattest-on-the-logon-socket]

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).
[*token.authd-adds-the-per-service-sid] 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.

<!-- lint-disable-next-line line-length -->
## 4.3.2 This request must come from PID 1 [*token.a-service-attest-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.

<!-- lint-disable-next-line line-length -->
## 4.3.3 The token is weaker than a user's, deliberately [*token.an-attested-token-is-impersonation-not-delegation]

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 [*token.an-unreachable-authority-fails-the-start]

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](/peios/reference/peinit/dependencies/derived-dependencies.md)).
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.
[*token.a-token-contradicting-the-declared-identity-fails-the-launch] 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.

<!-- lint-disable-next-line line-length spelling -->
## 4.3.5 What can be attested [*token.the-platform-service-identities-may-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.
[*token.an-undesignated-principal-is-refused] 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.

<!-- lint-disable-next-line line-length -->
## 4.3.6 The service's own virtual account [*token.service-selects-its-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.
[*token.service-orders-after-the-authority]

## 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_

> The SID derived from a service's name and carried in its token's group list — why it exists, and the uppercasing rule.

Every service token carries a SID derived from the service's name, in
its group list, alongside whatever the principal's own identity brings.
[*sid.every-service-token-carries-one]

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:
[*sid.the-derivation-is-sha1-over-the-uppercased-name]

```text
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. [*sid.peinit-and-authd-derive-the-same-sid]

## 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 [*sid.the-name-is-uppercased-before-encoding]

The name is uppercased before encoding, using full Unicode case mapping
— the one that expands `ß` to `SS` and `ﬁ` 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_

> peinit only ever removes privileges from a token and never adds one, on either identity path.

`RequiredPrivileges` is a list of the privileges a service needs.
Everything else is removed from its token before exec.
[*priv.everything-outside-requiredprivileges-is-removed]

## 4.5.1 Subtractive only [*priv.peinit-never-adds-a-privilege]

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.
[*priv.a-removal-is-total-and-irreversible] The privileges that
*survive* keep the enable state their source gave them: peinit does not
enable, disable, or re-order anything.
[*priv.survivors-keep-their-source-enable-state] 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.
[*priv.privileges-this-build-cannot-name-are-stripped-too] 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.
[*priv.an-absent-list-leaves-the-token-untouched]

## 4.5.2 Names [*priv.an-unmatched-privilege-name-fails-the-start]

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.
[*priv.takeownership-and-relabel-cannot-be-named]

---

# 4.6 Service Security Descriptors

_Peios / Reference / peinit / Service Identity_

> A service carries two independent descriptors answering different questions — the rights, the default, the check, and hot reload.

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.
[*svcsd.servicesecurity-governs-runtime-operations]

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

| Right | Bit | Grants |
|---|---|---|
| `SERVICE_QUERY_STATUS` | 0x0001 | Query state, PID, cause, health, warnings. [*svcsd.query-status-grants-status] |
| `SERVICE_START` | 0x0002 | Start the service. [*svcsd.start-grants-start] |
| `SERVICE_STOP` | 0x0004 | Stop the service. [*svcsd.stop-grants-stop] |
| `SERVICE_INTERROGATE` | 0x0008 | Reload the service. [*svcsd.interrogate-grants-reload] |
| `SERVICE_ALL_ACCESS` | 0x000F | The union of the four. |

Restart requires `SERVICE_START` and `SERVICE_STOP` together.
[*svcsd.restart-requires-start-and-stop] Reset
requires `SERVICE_STOP`, because clearing a Failed or Abandoned state is
the tail of stopping something rather than the head of starting it.
[*svcsd.reset-requires-stop]

The generic mapping peinit passes to AccessCheck:

| Generic right | Maps to |
|---|---|
| `GENERIC_READ` | `SERVICE_QUERY_STATUS` [*svcsd.generic-read-is-query-status] |
| `GENERIC_WRITE` | `SERVICE_START` \| `SERVICE_STOP` \| `SERVICE_INTERROGATE` [*svcsd.generic-write-is-start-stop-interrogate] |
| `GENERIC_EXECUTE` | `SERVICE_START` \| `SERVICE_STOP` \| `SERVICE_INTERROGATE` [*svcsd.generic-execute-is-start-stop-interrogate] |
| `GENERIC_ALL` | `SERVICE_ALL_ACCESS` [*svcsd.generic-all-is-service-all-access] |

<!-- lint-disable-next-line line-length -->
## 4.6.2 Inheritance and the default [*svcsd.a-definition-with-no-value-takes-the-services-keys]

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:
[*svcsd.the-built-in-default-grants-system-and-administrators-everything]

```text
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.
[*svcsd.the-built-in-default-lets-everyone-query]

## 4.6.3 The check

When a control command arrives, peinit:

1. Takes the caller's token, captured when the connection was accepted.
2. Resolves the target service and its ServiceSecurity descriptor. A
   command naming no definition and no addressable definition-removed
   entry returns `UNKNOWN_SERVICE`; peinit does not invent a descriptor
   to check against. [*svcsd.an-unknown-service-is-not-access-checked]
3. Calls AccessCheck with the caller's token, that descriptor, the
   generic mapping above, the right the command needs, and an audit
   context naming the service, `{kind: "service", service: {name}}`.
4. On denial, returns `ACCESS_DENIED`. The attempt is recorded by KACS,
   not by peinit: when the descriptor's SACL asks for it — and the
   built-in default's does — the check writes a
   `kacs.audit.access.checked` record with `object.kind` `service`,
   `object.service.name`, the caller's token, and the access requested
   and granted (§8.4).
   [*svcsd.a-denial-is-recorded-by-kacs-under-the-descriptors-sacl]
5. On grant, proceeds.

## 4.6.4 The SACL is the audit policy, and who can drop it

A service's SACL decides which of its decisions are recorded. A
descriptor written to the registry is used as it is: one with no SACL
records nothing, and one that narrows the default's audits less.

`ServiceSecurity` is a whole registry value. Whoever can write it — on
the service's key, or on `Machine\System\Services`, whose value every
service without its own takes — can replace the descriptor, SACL
included, without holding `SeSecurityPrivilege`, which is what changing
an object's SACL otherwise needs. So those keys must be writable only by
principals trusted to change audit policy. By default they are: both
inherit the Machine hive root, which grants write to SYSTEM and
Administrators alone, and Administrators hold `SeSecurityPrivilege`.
Delegate a service through its `ServiceSecurity` DACL, never by
loosening the key's own descriptor; and a tool that changes only the
DACL must write the SACL back unchanged. The same holds for the control
descriptor in `Machine\System\Init` (§10.2).

## 4.6.5 Hot reload [*svcsd.a-descriptor-change-needs-no-restart]

`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 [*svcsd.list-omits-rather-than-denies]

`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_

> Shutdown, configuration reload,  and the boot query are checked against peinit's own descriptor rather than any service's.

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.
[*svcsd.control-operations-use-peinits-own-descriptor]

## 4.7.1 Access rights

| Right | Bit | Grants |
|---|---|---|
| `SYSTEM_SHUTDOWN` | 0x0001 | Initiate poweroff, reboot,  or halt. [*svcsd.control-shutdown-grants-poweroff-reboot-halt] |
| `SYSTEM_RELOAD_CONFIG` | 0x0002 | Re-read all definitions from the registry. [*svcsd.control-reload-config-grants-a-definition-reread] |
| `SYSTEM_QUERY_STATUS` | 0x0004 | Read peinit's own status: how this boot went, with `boot` (§10.2). [*svcsd.control-query-status-grants-the-boot-query] |

The generic mapping:

| Generic right | Maps to |
|---|---|
| `GENERIC_READ` | `SYSTEM_QUERY_STATUS` [*svcsd.control-generic-read-is-query-status] |
| `GENERIC_WRITE` | `SYSTEM_RELOAD_CONFIG` [*svcsd.control-generic-write-is-reload-config] |
| `GENERIC_EXECUTE` | `SYSTEM_SHUTDOWN` [*svcsd.control-generic-execute-is-shutdown] |
| `GENERIC_ALL` | all three [*svcsd.control-generic-all-is-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 [*svcsd.the-control-default]

Absent a value in the registry, peinit applies:

```text
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.
[*svcsd.the-control-default-grants-system-and-administrators-both]

Authenticated Users get `SYSTEM_QUERY_STATUS` and nothing else.
<!-- lint-disable-next-line line-length -->
[*svcsd.the-control-default-lets-every-authenticated-user-ask-how-the-machine-booted]
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 [*svcsd.controlsecurity-is-loaded-at-phase-2-and-hot-reloaded]

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 them all at once.

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.
[*cgroup.no-accounting-and-no-limits]

Every service gets a tree: [*cgroup.every-service-gets-a-tree]

```text
/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.
[*cgroup.sub-cgroups-are-created-on-demand] 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.the-id-is-the-encoded-service-name]

`<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 [*cgroup.a-leak-moves-the-service-to-a-fresh-tree]

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:

```text
/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.rmdir-ebusy-also-records-a-leak]
`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. [*cgroup.the-generation-advances-once-per-tree] 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_

> Evaluating conditions and asserts before anything is forked — the two check mechanisms, and how results are cached.

Before anything is forked, peinit evaluates the service's conditions and
asserts (§3.5). The definition comes from the in-memory cache, so this
never touches the registry.

1. If the service names a `TTYPath` and another service is holding that
   terminal, it goes to Skipped with cause `TtyUnavailable` and the
   start is abandoned (§11.6).
   [*start.a-held-terminal-skips-before-the-checks] Asked first because
   a terminal is a fact about the machine right now, and evaluating
   conditions ahead of it would fork a check helper for a start that was
   never going to happen.
2. Conditions are evaluated. Any failure transitions the service to
   Skipped and abandons the start. Skipped satisfies dependents.
3. If every condition passed and the service has asserts, they are
   evaluated. Any failure transitions the service to Failed with cause
   `AssertionError` and abandons the start.

Only when all three pass does the pre-exec sequence continue.

## 5.2.1 Where the transition happens [*start.the-evaluation-gates-the-transition]

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
[*start.the-terminal-is-rechecked-after-the-helper]: 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. [*start.one-helper-run-covers-both-lists]
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 deciding to start a service and its binary running — timeouts, runtime directories, hooks,  and the fork.

Everything between "peinit decides to start service X" and "X's binary
is running". The service is in Starting throughout.

<!-- lint-disable-next-line line-length -->
## 5.3.1 Step 1: Arm the start timeout [*preexec.one-deadline-covers-the-whole-sequence]

`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
[*preexec.the-start-timeout-cause-depends-on-where-it-landed]: a timeout
during pre-hooks is `PreHookFailure`; one during the readiness wait or
the main process's execution is `ReadinessTimeout`.

<!-- lint-disable-next-line line-length -->
## 5.3.2 Step 2: Provision runtime directories [*preexec.runtime-directories-are-created-under-run]

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`.

<!-- lint-disable-next-line line-length -->
## 5.3.3 Step 3: Run pre-exec hooks [*preexec.pre-hooks-run-in-sequence-into-the-hooks-cgroup]

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`. [*preexec.a-hook-exiting-non-zero-fails-the-service]

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.
[*preexec.the-hooks-cgroup-is-killed-before-the-main-process]

<!-- lint-disable-next-line line-length -->
## 5.3.4 Step 4: Materialise the service token [*preexec.a-token-failure-is-a-parent-setup-failure]

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.

<!-- lint-disable-next-line line-length -->
## 5.3.5 Step 5: Create the cgroups and the error pipe [*preexec.the-error-pipe-carries-post-fork-failures]

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)`:**
[*preexec.the-error-payload-is-eight-bytes]

| 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`.
[*preexec.malformed-evidence-fails-closed]

The step identifiers: [*preexec.the-child-setup-step-identifiers]

| 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
[*preexec.identifier-8-is-reserved]: 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 [*preexec.the-child-is-cloned-straight-into-the-main-cgroup]

`clone3(CLONE_PIDFD | CLONE_INTO_CGROUP)`, targeting `main/`. This does
two things atomically: it returns a pidfd for the child, and it places
the child directly into `main/` at creation. There is no window in which
the child exists without a pidfd, and none in which it runs or execs in
peinit's own cgroup.

Placing the child at creation also avoids the alternative, which would
be having the child write its own PID into `cgroup.procs` — something
its post-installation token could not do.

A `clone3` failure means no child exists: `ParentSetupFailure`, with
`EMFILE` /`ENFILE`, `EAGAIN` and `ENOMEM` the usual causes.

peinit does not take the atomicity on trust. If `clone3` reports success
without setting the pidfd, or the pidfd cannot be made close-on-exec,
peinit writes to `cgroup.kill` through the `main/` directory descriptor
before returning `ParentSetupFailure` — because by then a child does
exist, running in the service's cgroup with the service's token, and the
parent has no handle on it. Walking away would leave a process peinit
cannot supervise, cannot stop, and has no record of, which the
zero-delay cleanup that follows a `ParentSetupFailure` would then record
as a leaked tree rather than kill.

Immediately after `clone3` returns, in the parent and on either outcome,
peinit closes the token descriptor and the `main/` cgroup descriptor,
exactly once each. The child relies on close-on-exec and its own exit
instead. A failure to close is cleanup evidence and does not change how
the start is classified.

## 5.3.7 Step 7: The parent after the fork

1. Close the write end of the error pipe.
2. Register the read end with the event loop. peinit does not block on
   it — signals, control traffic, timers, and log pipes stay serviceable
   while the child's setup is pending.
3. When the read end becomes readable or hangs up, read it
   non-blocking:
   - **Would block:** leave the source registered, the job stays in
     pending setup.
   - **EOF:** exec succeeded. Record the pidfd on the job, emit
     `peinit.job.started`, and only then apply readiness side effects such as
     Simple/Alive activation.
   - **Data:** setup failed. Parse the step and errno, log the specific
     failure, fail the service with `PreExecFailure`.
     [*preexec.a-child-setup-failure-is-a-pre-exec-failure]

While setup is pending the job is not Running, and no dependent that
waits on this service's readiness is released.

## 5.3.8 Steps 8 and 9

The child's own path is §5.4. What follows exec is the readiness wait
and the post-readiness work:

- **Simple with `Readiness=Notify`:** wait for `READY=1`, then Active.
- **Simple with `Readiness=Alive`:** Active as soon as exec succeeds.
- **Oneshot:** wait for the exit. Success is Completed; without
  `RemainAfterExit` it then goes Inactive once dependents are released.
  A non-zero exit is Failed.

On readiness or successful exit, peinit runs `ExecStartPost` in sequence
into `hooks/`, releases the service's dependents, kills `hooks/`, and —
for a Simple service only — arms the watchdog if `WatchdogTimeout` is
non-zero and the health check timer if `HealthCheck` is set.
[*preexec.post-hooks-run-after-readiness]

A post-hook that fails is logged and does not fail the service.
[*preexec.a-failed-post-hook-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.
[*preexec.the-state-transition-precedes-the-post-hooks]

## 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_

> The deliberately minimal straight line between clone3 returning and execve — streams, signals, resources, the token,  and the environment.

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. [*child.a-setup-failure-exits-126-and-a-failed-exec-127]

The steps, in the order the child runs them:
[*child.the-child-setup-order]

| # | 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 [*child.setsid-precedes-the-stream-setup]

`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. [*child.without-a-ttypath-the-terminal-steps-do-not-run]

## 5.4.2 The standard streams [*child.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.
[*child.a-terminal-attached-service-gets-the-terminal-on-all-three-streams]
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.

<!-- lint-disable-next-line line-length -->
## 5.4.3 The signal environment [*child.the-signal-mask-is-emptied-and-dispositions-reset]

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 [*child.oom-score-adj-follows-error-control]

`-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.

<!-- lint-disable-next-line line-length -->
## 5.4.5 Resources before the token [*child.resources-are-set-before-the-token-is-installed]

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.
[*child.notify-socket-is-confirmed-not-set]

<!-- lint-disable-next-line line-length -->
## 5.4.7 What the child does not inherit [*child.only-the-streams-and-injected-descriptors-are-inherited]

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.
[*child.natively-opened-descriptors-have-cloexec-set-by-hand]

---

# 5.5 The Base Environment

_Peios / Reference / peinit / Starting a Service_

> Every service environment is built from scratch in four layers, lowest precedence first, with nothing inherited.

peinit constructs every service and hook process's environment from
scratch, in four layers, lowest precedence first. Nothing is inherited
[*env.nothing-is-inherited-from-peinit]: 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 [*env.the-compiled-in-path]

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.

<!-- lint-disable-next-line line-length -->
## 5.5.2 Layer 2: global environment variables [*env.global-envvars-become-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.
[*env.an-envvars-path-overrides-the-compiled-in-one]

A malformed entry — an empty name, or a name containing `=` — fails the
whole layer, which at boot means recovery mode.
[*env.a-malformed-envvars-entry-fails-the-layer]

**registryd does not receive this layer.**
[*env.registryd-does-not-receive-the-global-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`.
[*env.the-exemption-matches-identity-and-name] 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 [*env.the-services-own-environment-overrides-the-layers-below]

The definition's `Environment` entries, overriding both layers below.

## 5.5.4 Layer 4: protocol variables [*env.notify-socket-is-always-set]

`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). [*env.the-listen-variables-appear-only-with-injected-descriptors]

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.
[*env.the-protocol-names-are-filtered-out-of-the-configurable-layers]
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.
[*env.listen-pid-is-appended-by-the-child]

## 5.5.5 What peinit does not set [*env.no-home-user-logname-shell-or-term]

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 [*env.hooks-and-probes-receive-the-identical-environment]

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.
[*env.hooks-never-receive-listen-fds]

## 5.5.7 When changes apply [*env.changes-take-effect-at-the-next-start]

The global layer is a snapshot refreshed at boot and on reload-config,
and both it and the per-service `Environment` take effect at a service's
next start. Neither is applied to a running process.

> [!NOTE]
> Write access to `Machine\System\Init\EnvVars\` is equivalent to
> compromising every service on the system. peinit does not filter
> variable names, consistent with the registry's write-authority threat
> model — the key's descriptor is the boundary. The recommended default
> is SYSTEM full control and Administrators read-only.

---

# 5.6 Health Checks

_Peios / Reference / peinit / Starting a Service_

> A watchdog says a service is still ticking; a health check says it still works — execution, overlap, failure,  and the flap constraint.

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 [*health.the-check-runs-with-the-services-own-token]

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.
[*health.an-invocation-runs-in-the-health-cgroup-as-a-child-of-peinit]

## 5.6.2 Overlap [*health.an-overlapping-check-is-skipped]

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. [*health.a-timed-out-check-counts-as-a-failure]

A launch failure — a token that could not be materialised, a fork that
failed — is **not** counted. [*health.a-launch-failure-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 [*health.consecutive-failures-restart-the-service]

`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.
[*health.a-success-resets-the-failure-count]

Escalation kills the service's **root** cgroup rather than `main/`,
so it takes hooks and probes with it.
[*health.escalation-kills-the-root-cgroup]

## 5.6.4 The flap constraint [*health.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:

```text
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.
[*health.a-violating-definition-is-blocked-at-boot] On reload-config, it
is a validation finding, and a finding rejects the entire reload.
[*health.a-violating-definition-rejects-a-reload]

The constraint applies only where a check will actually run, which means
Simple services. [*health.the-constraint-applies-only-to-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.
[*health.a-health-check-on-a-non-simple-service-is-rejected] That is the
thing actually wrong with the definition; reporting it as timing
arithmetic let an operator adjust `RestartWindow`, see the definition
validate, and still have a `HealthCheck` that does nothing.

> [!NOTE]
> Active health checks on `ErrorControl=Critical` services deserve
> caution. A false positive eventually exhausts the restart budget and
> reboots the machine. Critical services — registryd, authd, lpsd,
> eventd — are usually better served by a passive watchdog with a
> generous timeout: the service knows whether it is healthy and can stop
> sending keepalives when it decides it is not. peinit does not prevent
> health checks on Critical services and applies identical semantics to
> them, but the escalation path ends at a reboot.

---

# 5.7 Leaked Sub-Cgroups

_Peios / Reference / peinit / Starting a Service_

> A D-state process does not die when SIGKILLed — what happens to its cgroup, and how the leak becomes visible.

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.
[*cgroup.a-post-kill-deadline-detects-a-survivor]

## 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).
[*cgroup.an-unkillable-main-process-abandons-the-service]

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:
[*cgroup.a-leaked-hook-or-health-cgroup-is-orphaned]

1. Marks it leaked, recording the path, the kind, and the time.
2. Increments the service's cgroup generation, so the next start builds
   a fresh tree (§5.1).
3. Carries on supervising the service normally.

A leaked **pre-start check helper** is treated the same way: its
`checks/` sub-cgroup is recorded and the generation bumped, which matters
because otherwise the next start would build into a tree that still
contains the unkillable process.
[*cgroup.a-leaked-check-helper-is-treated-the-same-way]

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.
[*cgroup.a-tree-back-in-use-is-not-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 [*cgroup.a-leak-is-both-pushed-and-queryable]

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: [*cgroup.a-leak-is-announced-once]

- A **`peinit.cgroup.leaked` event** on the event stream, carrying the
  service, the sub-cgroup path (`object.cgroup.path`) and its kind
  (`object.cgroup.type`: `service-tree`, `health`, `hooks`, or `helper`).
  When it was found is the event's own time. [*cgroup.the-leak-event]

- A **console line** naming the same service, kind and path.
  [*cgroup.the-leak-console-line]

The pull side survives the moment of detection, for anyone who was not
watching:

- A **status query** includes a `warnings` array, one entry per leak,
  each an object with the sub-cgroup path, its kind, and the time of
  detection: [*cgroup.status-carries-a-warnings-entry-per-leak]

  ```json
  {"path": "/sys/fs/cgroup/peinit/jellyfin/health", "type": "health",
  "detected_at": "2026-06-01T12:34:56.123456789Z"}
  ```

- A **start command** on a service with leaks returns a warning in its
  acknowledgment, saying the service has leaked sub-cgroups from a
  previous generation and that this indicates an I/O problem needing
  investigation. [*cgroup.a-start-on-a-service-with-leaks-warns]

The `type` is the same vocabulary everywhere
[*cgroup.the-leak-type-vocabulary]: `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_

> The ten states a service can be in, the four that satisfy dependents, and the invariants that hold across all of them.

Every service is in exactly one state. There are ten.
[*state.every-service-is-in-exactly-one-of-ten-states]

| 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**.
[*state.only-active-reloading-completed-and-skipped-satisfy-dependents]
Nothing else does, and a dependent blocked on a `Requires` target in any
other state does not start.
[*state.a-dependent-on-an-unsatisfied-requires-target-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.
[*state.completed-satisfies-regardless-of-remainafterexit]

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.
[*state.a-dependent-of-a-service-in-backoff-waits-rather-than-failing]
It is the state that makes a restart something other than a
transit through Failed. A dependent held this way looks exactly like a
start held on a readiness level — Inactive, its start operation Pending
(§8.2) — and is released when the service next reaches a
dependent-satisfying state. It fails with `dependency_failure` only when
the service gives up: its restart budget is exhausted, or it is stopped
or its definition withdrawn while in Backoff.

## 6.1.2 Invariants

1. A service is in exactly one state at any moment. There is one state
   field and exactly one place in the implementation that assigns to it.
2. Only the transitions in §6.2 are performed. The assignment is gated
   by a central allowlist, so an unlisted transition is not merely
   avoided by convention — it cannot be written.
3. Only peinit transitions a service. The control socket produces
   operations; nothing outside peinit writes state.
   [*state.nothing-outside-peinit-writes-service-state]
4. A service object is securable independently of its process token.
   [*state.a-service-is-securable-independently-of-its-process-token] The
   ServiceSecurity descriptor governs who can manage the service; the
   process token governs what the service can reach. Neither implies
   anything about the other.
5. Readiness is per start generation. The generation increments on every
   transition into Starting,
   [*state.the-generation-increments-on-every-entry-to-starting] and a
   `READY=1` carrying a stale generation is rejected — so a notification
   from a previous incarnation can never be mistaken for this one's.
   [*state.a-ready-carrying-a-stale-generation-is-rejected]

---

# 6.2 Transitions

_Peios / Reference / peinit / The State Machine_

> Every transition peinit performs — anything absent from the table is not performed — plus reset from Abandoned.

Every transition peinit performs. Anything not listed here is not
performed. [*trans.a-transition-absent-from-the-table-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.
[*trans.a-restart-never-passes-through-failed] 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.
[*trans.onfailure-does-not-fire-on-each-retry]

**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. [*trans.a-simple-clean-exit-goes-to-inactive-under-cleanexit]
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.
[*trans.a-clean-exit-under-always-goes-to-backoff-as-cleanexitrestart]

**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.
[*trans.stopping-to-failed-carries-the-cause-that-started-the-stop] 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. [*trans.an-administrative-restart-detours-through-inactive] 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.
[*trans.a-restarts-pass-through-inactive-is-not-observable]

**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.
[*trans.a-pre-readiness-exit-is-a-restart-eligible-processcrash]

**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: [*trans.an-exit-in-an-unexpected-state-performs-no-transition]

```text
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. [*trans.an-unexpected-exit-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.
[*trans.a-reset-of-an-emptied-abandoned-service-cleans-up-and-goes-inactive]

If it is still populated, peinit leaves the cgroup leaked, transitions
to Inactive anyway, and returns this warning in the operation
acknowledgment:
<!-- lint-disable-next-line line-length -->
[*trans.a-reset-of-a-populated-abandoned-service-warns-and-leaves-the-cgroup-leaked]

```text
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.
[*trans.the-reset-warning-is-also-written-to-the-console]

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.
[*trans.the-two-paths-into-abandoned-probe-different-cgroups]

---

# 6.3 Transition Causes

_Peios / Reference / peinit / The State Machine_

> Every transition carries a cause — the taxonomy, which causes are restart-eligible, OnFailure, the loop guard and the logging contract.

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.
[*cause.every-transition-carries-the-cause-of-the-most-recent-transition]

## 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.
[*cause.a-restart-eligible-cause-consults-the-policy-and-the-budget]

`ProcessCrash`, `WatchdogTimeout`, `HealthCheckFailure`,
`ReadinessTimeout`, `PreHookFailure`, `PreExecFailure`,
`ParentSetupFailure`.

> [!NOTE]
> The startup failures are restart-eligible because a transient problem
> during startup should get another go. A pre-hook that failed because a
> network mount was briefly unavailable deserves a retry rather than an
> immediate give-up.

**Always-only.** `CleanExitRestart` applies when a Simple service exits
successfully and the policy is Always. It uses the same backoff and the
same budget as a failure,
[*cause.cleanexitrestart-uses-the-same-backoff-and-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,
[*cause.bindstorecovery-is-exempt-from-the-policy-and-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:
[*cause.a-never-restart-cause-does-not-consult-the-policy]
`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.
[*cause.entering-failed-starts-the-named-onfailure-service]
`OnFailure` fires on *entry* to Failed, and Failed to Failed is not a
transition, so it fires at most once per failure.
[*cause.onfailure-fires-at-most-once-per-failure]

It does not fire for:
[*cause.onfailure-does-not-fire-for-shutdown-or-definition-breakage]

- **`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.
[*cause.onfailure-fires-for-a-non-critical-budget-exhaustion]

For a **Critical** service exhausting its budget, the reboot takes
precedence and no fallback is started.
[*cause.a-critical-budget-exhaustion-starts-no-handler] 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.
[*cause.a-handler-already-active-or-reloading-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.
[*cause.a-satisfied-handler-start-records-no-chain-entry]

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.
[*cause.a-handler-in-any-other-state-is-started-normally]

### 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,
[*cause.a-handler-already-in-the-chain-is-not-started-again] and it will
not follow the chain past a fixed depth of 16.
[*cause.the-chain-is-not-followed-past-a-depth-of-sixteen] When either
trips, peinit records a `peinit.on-failure.suppressed` event naming
which (`outcome.reason` `cycle` or `max-depth`), and stops.
[*cause.a-suppressed-loop-records-an-audit-event]

A chain entry is retired two ways.

**The handler stopped needing tracking.** Completed, Inactive, Skipped, or
Abandoned — it ended, gave up, or became unkillable.
[*cause.a-chain-entry-is-retired-when-the-handler-ends]

**The handler arrived.** It has been dependent-satisfying for its
`RestartWindow` — the same window that resets a restart budget (§6.4).
[*cause.a-chain-entry-is-retired-when-the-handler-holds-for-restartwindow]
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.
[*cause.a-transition-into-a-bad-state-is-written-to-the-console] 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.
[*cause.there-is-no-per-transition-event]

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_

> What happens when a restart-eligible cause occurs — the policies, backoff, the budget and when it resets, and exhaustion.

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.

```text
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`.
[*restart.a-relaunch-gets-a-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.
[*restart.successexitcodes-applies-to-a-pre-readiness-exit-too]

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.
[*restart.a-failure-with-no-exit-code-cannot-match-successexitcodes] That
is not a gap: a success code is a statement about how the service's own
process ended.

## 6.4.1 The policies [*restart.the-three-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.
[*restart.a-oneshot-that-succeeds-is-not-restarted-whatever-the-policy]
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.
[*restart.the-delay-doubles-and-caps-at-sixty-seconds] The arithmetic is
overflow-safe, so a large `RestartDelay` or a long failure run saturates
at the cap rather than wrapping.
[*restart.the-backoff-arithmetic-saturates-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;
<!-- lint-disable-next-line spelling -->
[*restart.an-explicit-start-during-backoff-honours-the-remaining-delay] a
`stop` cancels the pending restart and takes the service to Inactive.
[*restart.a-stop-during-backoff-cancels-the-pending-restart]

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**.
[*restart.the-budget-resets-only-after-restartwindow-active] 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.
[*restart.a-crash-restarts-the-window-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.
<!-- lint-disable-next-line line-length -->
[*restart.a-service-healthy-for-a-window-between-crashes-never-exhausts-its-budget]
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.
[*restart.a-clean-exit-or-a-reset-also-zeroes-the-counter] An explicit
stop while in Backoff does not — the accrued failures are preserved.
[*restart.a-stop-in-backoff-preserves-the-accrued-failures]

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.
[*restart.a-reload-across-the-window-boundary-defers-the-reset]

## 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`.
[*restart.exhaustion-is-failed-with-restartbudgetexhausted] peinit then
applies `ErrorControl`:

- **Normal** — the service stays Failed.
  [*restart.errorcontrol-normal-leaves-the-service-failed]
- **Critical** — peinit syncs the filesystems and reboots immediately.
  [*restart.errorcontrol-critical-syncs-and-reboots]
  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.
<!-- lint-disable-next-line line-length -->
[*restart.a-budget-exhausted-by-startup-failures-still-reboots-a-critical-service]

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. [*restart.the-handler-is-skipped-exactly-when-a-reboot-is-owed]

A failure during a shutdown reboots nothing (§12.2 step 2), and the
handler is not started either — the machine is already going down.
[*restart.a-failure-during-shutdown-neither-reboots-nor-starts-a-handler]

---

# 6.5 Reload

_Peios / Reference / peinit / The State Machine_

> Telling a service to re-read its configuration without restarting — choosing the signal or command path, auto-detection, and interruptions.

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. [*reload.a-reload-moves-the-service-to-reloading]

A failed reload never takes a running service out of Active.
[*reload.a-failed-reload-never-takes-a-service-out-of-active] And reload
never gets stuck: every path has a timeout.
[*reload.every-reload-path-has-a-timeout]

## 6.5.1 Choosing a path

`ExecReload` absent means SIGHUP to the main process.
[*reload.an-absent-execreload-means-sighup] A `signal:<NAME>`
value means that signal instead.
[*reload.a-signal-value-sends-that-signal] 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.
[*reload.a-reload-command-runs-in-hooks-under-the-services-own-identity]

## 6.5.2 The signal path

There is no command exit to observe, so completion is inferred from the
main process's own notifications.
[*reload.the-signal-path-resolves-on-the-main-processs-notifications]

```text
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.
[*reload.the-detection-window-is-a-fixed-two-seconds] 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.
[*reload.a-short-starttimeout-does-not-shorten-the-detection-window] 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:
[*reload.an-unconfirmed-reload-is-reported-on-the-console-and-audited]

```text
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,
[*reload.the-outcome-is-carried-in-the-operations-result] 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.
[*reload.a-detection-window-expiring-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.
[*reload.the-command-exit-gates-failure-and-ready-gates-confirmation]

```text
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.
[*reload.the-handshake-needs-no-per-service-configuration]

## 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.
[*reload.a-crash-while-reloading-is-a-processcrash-on-the-restart-path]
Both reload timers are canceled and any in-flight reload command is
killed. [*reload.a-crash-cancels-the-timers-and-kills-the-reload-command]

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.
[*reload.a-stop-while-reloading-cancels-the-reload-and-sigterms-at-once]

---

# 6.6 The Watchdog and Timeout Extension

_Peios / Reference / peinit / The State Machine_

> The two notification fields a running service uses to adjust the deadlines it is held to, their caps, and where they do not apply.

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.
[*wdog.both-fields-carry-microseconds]

## 6.6.1 The watchdog

`WatchdogTimeout` sets the interval peinit expects `WATCHDOG=1` pings
at. Zero, the default, disables it.
[*wdog.watchdogtimeout-sets-the-ping-interval-and-zero-disables-it]
Missing a ping is a `WatchdogTimeout` cause and takes the ordinary
restart path. [*wdog.a-missed-ping-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.
  [*wdog.a-runtime-interval-update-re-arms-immediately]
- A value of zero disables the watchdog entirely, equivalent to
  `WatchdogTimeout=0`.
  [*wdog.a-runtime-value-of-zero-disables-the-watchdog]

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.
[*wdog.a-runtime-interval-does-not-survive-a-restart]

`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.
[*wdog.watchdog-usec-while-starting-is-ignored]

> [!NOTE]
> Runtime watchdog updates suit a service whose phases have genuinely
> different latency. A database engine might want a tight five-second
> watchdog in normal operation and sixty seconds during a compaction
> pass. The service knows its own phases better than whoever wrote its
> definition does.

## 6.6.2 Timeout extension

A service can ask for more time during a start, stop or reload by
sending `EXTEND_TIMEOUT_USEC=<value>`.

peinit sets the current phase's deadline to expire that many
microseconds from now.
[*wdog.extend-timeout-usec-extends-the-current-phases-deadline] 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.
[*wdog.an-extension-replaces-the-deadline-rather-than-adding-to-it]

Because it replaces, a small value shortens the remaining time rather
than being ignored, and a value of zero sets the deadline to now.
[*wdog.a-small-extension-shortens-the-remaining-time]

### 6.6.2.1 The caps

The extended deadline cannot exceed four times the phase's base timeout:
[*wdog.the-extended-deadline-is-capped-at-four-times-the-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.
[*wdog.a-value-beyond-the-cap-is-clamped-not-rejected] Because the cap is
anchored to when the operation started rather than to the previous
deadline, repeated messages cannot creep past it.
[*wdog.repeated-extensions-cannot-creep-past-the-cap]

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.
[*wdog.during-shutdown-the-stricter-of-the-two-caps-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.
[*wdog.an-extension-in-a-non-transitional-state-is-ignored]

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.
[*wdog.before-its-stop-wave-an-active-service-has-no-deadline-to-extend]
A service that expects its stop to take longer sends the request once
its stop has begun.

> [!NOTE]
> Timeout extension is for a service doing variable-duration work in a
> transition — replaying a write-ahead sign in startup, say. It sends
> periodic messages to prove it is making progress; if it stops sending,
> the last deadline fires and peinit escalates as usual. The fourfold
> cap is what stops a buggy service extending forever.

---

# 7.1 Relationships

_Peios / Reference / peinit / Dependencies_

> The four relationship types — Requires, Wants, BindsTo,  and Conflicts — and what each means at start, at stop and on failure.

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`.
  [*rel.a-requires-target-is-started-first-with-dependencystart] If B
  enters Failed, A goes to Failed with cause `DependencyFailure`
  without attempting to start.
  [*rel.a-failed-requires-target-fails-the-dependent]
- **Stop.** Stopping B does not stop A.
  [*rel.stopping-a-requires-target-does-not-stop-the-dependent] 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.
  [*rel.a-requires-target-crashing-leaves-an-active-dependent-alone]
  B's own restart policy handles B.
- **Missing target.** A goes to Failed with `DependencyFailure`,
  detected at graph validation.
  [*rel.a-missing-requires-target-fails-the-dependent-at-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.
[*rel.a-wants-target-that-exists-and-is-enabled-is-started-first] If B
fails to start, or does not exist at all, A starts anyway.
[*rel.a-failing-or-absent-wants-target-does-not-stop-the-dependent]
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.
[*rel.a-wants-dependent-waits-only-for-a-terminal-state] 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`.
  [*rel.bindsto-starts-exactly-as-requires-does]
- **Stop.** If B stops for *any* reason — explicit stop, conflict,
  crash, shutdown — A stops too, transitioning to Stopping with cause
  `BindsToPropagation`.
  [*rel.a-bindsto-target-stopping-stops-the-dependent]
- **Recovery.** When B returns to Active, peinit automatically restarts
  anything sitting in Failed with cause `BindsToPropagation` from B's
  stop. [*rel.a-bindsto-target-returning-to-active-restarts-the-dependent]
  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.
  [*rel.a-bindsto-recovery-restart-does-not-consume-the-restart-budget]

`BindsTo` implies `Requires`. A definition can list both for clarity,
and if it does, the `BindsTo` semantics apply.
[*rel.bindsto-implies-requires]

## 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. [*rel.starting-a-service-evicts-an-active-conflicting-one]

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. [*rel.conflicts-are-symmetric]

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. [*rel.a-missing-conflict-target-is-dropped]

> [!NOTE]
> `Conflicts` is for real mutual exclusion: two services binding the
> same port, or two implementations of one role where exactly one must
> run. It is not a way to solve resource contention that has a better
> answer.

## 7.1.5 Ordering and self-reference

Dependencies imply start ordering, and — except for `BindsTo` — imply
nothing about stopping. peinit starts dependencies before dependents;
during shutdown it reverses the same graph and stops dependents before
dependencies (§12.2), derived from the one graph rather than from a
separate stop-ordering configuration.

A service can not name itself in any dependency field. peinit rejects a
self-reference at graph validation as a `CycleDetected` failure, which
is what it is — a cycle of length one.
[*rel.a-self-reference-is-a-cycle-of-length-one]

---

# 7.2 Graph Validation

_Peios / Reference / peinit / Dependencies_

> peinit validates the dependency graph before executing it — cycles, missing targets, and the errors and warnings it produces.

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.
[*validate.validation-runs-once-per-graph-build]

## 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. [*validate.every-cycle-is-detected-not-only-the-first]

Every service in a cycle is failed with cause `CycleDetected`, and the
cycle path is logged so an administrator can see what to break.
[*validate.every-member-of-a-cycle-fails-with-cycledetected]

If any service in a cycle is Critical, peinit downgrades to Safe mode
(§2.6) rather than rebooting.
[*validate.a-critical-service-in-a-cycle-downgrades-to-safe-mode] The
cycle is a configuration error, and rebooting would find it again.

<!-- lint-disable-next-line line-length -->
## 7.2.2 Missing targets [*validate.a-missing-hard-target-fails-the-dependent-and-a-missing-soft-one-is-dropped]

| 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.
[*validate.safe-mode-drops-a-hard-edge-only-on-a-service-it-excluded] 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.
[*validate.a-missing-or-disabled-target-blocks-in-safe-mode-too]

## 7.2.3 Validation errors

A service that hits one is failed with cause `ValidationError` and never
started: [*validate.a-validation-error-fails-the-service-and-it-never-starts]

- 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.
  [*validate.an-invalid-timer-expression-is-checked-across-every-definition]
- Two boot-triggered services that conflict with each other. Both are
  failed. Safe mode applies if either is Critical.
  [*validate.two-boot-triggered-services-that-conflict-both-fail]

## 7.2.4 Validation warnings

Logged, and do not prevent boot:
[*validate.a-validation-warning-does-not-prevent-the-graph-from-running]

- A service using `Readiness=Alive` that something else depends on
  hard. [*validate.alive-readiness-with-a-hard-dependent-is-warned-about]
  `Alive` readiness means the process exists, which is no
  guarantee it is functional, so anything waiting on it is waiting on
  the wrong thing.
- Services that need a role no service fills — in practice `authn`,
  needed by every service whose `Identity` is not `SYSTEM`. Warned about
  rather than failed, because a missing hard dependency rejects the whole
  reload transaction, and that would prevent reloading the very
  definition that installs the missing provider. See
  [§7.6](/peios/reference/peinit/dependencies/derived-dependencies.md).

## 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:
[*validate.the-primary-cause-is-chosen-by-precedence]

1. `CycleDetected`
2. `ValidationError`
3. `DependencyFailure`

The precedence affects only which cause is stored. Every other finding
for the service is retained beside it, in discovery order, and the
operation's failure message enumerates all of them:
[*validate.every-finding-is-retained-beside-the-primary-one]

```text
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.
[*validate.a-later-higher-precedence-finding-demotes-rather-than-deletes]

Every finding is also emitted as its own `peinit.graph.validation.failed`
KMES event, carrying `graph.phase` `boot` and the finding as
`outcome.reason`.
[*validate.each-finding-is-its-own-validation-failed-event-at-boot]
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.
[*validate.a-blocked-dependency-is-reported-as-hard-dependency-blocked]
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).
<!-- lint-disable-next-line line-length -->
[*validate.reload-validation-rejects-the-whole-reload-under-phase-reload-config]
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_

> Starting everything whose dependencies are satisfied and repeating until nothing more can start — contexts, failure propagation,  and shutdown ordering.

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.
[*exec.a-member-starts-when-every-one-of-its-dependencies-is-satisfied]

```text
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. [*exec.maxparallelstarts-is-counted-per-context]

The events are not only member completions. A dependency naming a
[readiness level](/peios/reference/peinit/dependencies/readiness-levels.md)
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.
[*exec.there-is-one-boot-context-and-one-per-explicit-start]

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.
[*exec.a-shared-dependency-is-one-operation-both-contexts-hear-about]

So when a pre-start outcome is terminal for an operation, peinit
dispatches the corresponding graph event once **per associated
context**.
[*exec.a-terminal-outcome-dispatches-one-graph-event-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. [*exec.an-unneeded-member-is-pruned-rather-than-started]

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.
[*exec.a-context-is-retired-once-every-member-is-terminal] Its operation
associations go with it, except where an operation is also associated
with a context that is still live.

Retirement happens on the operation-maintenance sweep rather than at the
moment the last member goes terminal. The callers of a terminal outcome
walk the graph events it produced and release the contexts those events
name, so dropping a context inline would pull it out from under the rest
of the same turn's work.

Without this a context and its associations persisted for the lifetime
of the process. The memory was the smaller half: dispatching a terminal
outcome walks every context associated with the operation, so on a
long-lived machine where services are started regularly the terminal
path grew steadily slower, in PID 1's single thread.

## 7.3.2 Failure propagation

When a service enters Failed during graph execution:

1. Everything that `Requires` or `BindsTo` it transitions to Failed with
   cause `DependencyFailure`.
2. Everything that `Wants` it is unaffected and starts normally.
3. Propagation is transitive: if A requires B and B requires C, and C
   fails, then B fails and then A fails.
   [*exec.failure-propagation-is-transitive]

## 7.3.3 On-demand start

Starting a service explicitly resolves its dependencies first:
[*exec.an-on-demand-start-resolves-its-closure-first]

1. Collect the transitive `Requires` and `BindsTo` closure.
2. Collect the transitive `Wants` closure, best-effort.
3. Validate the sub-graph — cycles, missing targets.
4. Resolve conflicts, stopping whatever has to stop.
5. Start the sub-graph with the same parallel algorithm. Dependencies
   started this way carry cause `DependencyStart` and operation source
   `DependencyPropagation`.
   [*exec.a-dependency-started-on-demand-carries-dependencypropagation]

A service already in a satisfying state — Active, Completed, or Skipped —
is not restarted. Its dependency is already met.
[*exec.a-dependency-already-in-a-satisfying-state-is-not-restarted]

A **disabled** hard-dependency target blocks the dependent, on both
paths. [*exec.a-disabled-hard-dependency-target-blocks-the-dependent]
`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.
[*exec.a-disabled-service-can-still-be-started-explicitly]

A disabled `Wants` target is skipped rather than blocking anything: a
soft dependency is advisory, so there is nothing to fail.
[*exec.a-disabled-wants-target-is-skipped-rather-than-blocking]

## 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.
[*exec.shutdown-stops-dependents-before-their-dependencies]

Only hard dependencies — `Requires` and `BindsTo` — contribute to the
ordering. A `Wants` dependent can therefore be stopped after its target.
[*exec.only-hard-dependencies-order-the-shutdown]

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.
[*exec.there-is-no-floor-or-pinning-in-the-shutdown-order]

---

# 7.4 The Boot and On-Demand Paths

_Peios / Reference / peinit / Dependencies_

> The two ways a graph gets built and how they differ beyond scope — including the three places a bad definition can surface.

The two ways a graph gets built differ in more than scope, and the
differences are worth having in one place.
[*ondemand.the-boot-and-on-demand-paths-differ-beyond-scope]

| | 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 with `ValidationError` and the rest
  continue, at boot and on reload alike (§3.2).
<!-- lint-disable-next-line line-length -->
  [*ondemand.a-definition-that-does-not-parse-is-caught-when-the-registry-is-read]
- **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).
  [*ondemand.a-definition-that-does-not-fit-is-caught-at-graph-validation]
- **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).
  [*ondemand.a-precondition-that-does-not-hold-is-caught-at-start]

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_

> How a service waits for a condition inside another service — Requires = ["netd:routed"] — and how publishers report a set of current conditions.

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

```text
Requires = ["netd:routed"]
Wants    = ["timed:synchronised"]
```

`netd:routed` waits for netd to be active **and** to have published the
level `routed`.
[*ready.a-level-dependency-waits-for-the-level-as-well-as-the-service]
`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.
[*ready.a-declared-target-splits-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](/peios/reference/peinit/dependencies/relationships.md),
applied to
the stricter test. [*ready.each-relationship-keeps-its-semantics-with-a-level]

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.
[*ready.a-service-name-can-never-contain-a-colon]

A trailing colon — `"netd:"` — reads as a plain dependency on `netd`.
[*ready.a-trailing-colon-is-a-plain-dependency] 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:

```text
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](/peios/reference/peinit/dependencies/derived-dependencies.md)
resolves a role. The level rides across unchanged.
[*ready.a-role-carrying-a-level-is-rewritten-to-the-provider-with-that-level]
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.
[*ready.a-role-with-several-providers-becomes-one-entry-per-provider] 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.
[*ready.an-unfilled-role-fails-validation-naming-the-role]

## 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=`:

```text
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.
[*ready.a-datagram-replaces-the-whole-level-set]

`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.
[*ready.an-empty-level-retracts-it] peinit records the set against the
sending service, and holds any dependent whose requested level is absent.
<!-- lint-disable-next-line line-length -->
[*ready.a-level-is-recorded-against-the-sender-and-holds-a-mismatched-dependent]

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
[*ready.peinit-never-connects-to-a-publishers-own-socket] — 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.
[*ready.a-level-matches-membership-in-the-published-set]

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.
[*ready.a-level-is-cleared-when-its-publisher-stops-satisfying-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](/peios/reference/peinit/dependencies/graph-execution.md)
re-checks it against the service table every time it considers releasing
the dependent, and holds the start until the answer is yes.
<!-- lint-disable-next-line line-length -->
[*ready.a-level-is-re-checked-at-every-release-rather-than-settled-at-planning]

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.
[*ready.a-level-edge-is-kept-to-a-target-that-is-not-being-started]

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.
[*ready.only-the-level-itself-opens-a-hard-gate] 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.
[*ready.a-publisher-leaving-a-satisfying-state-releases-wants-waiters]

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.
[*ready.a-held-start-does-not-time-out] 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.
[*ready.a-level-dropping-after-the-start-does-nothing]

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 [*ready.netd-and-timed-are-the-shipped-publishers]

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

> Provides names a role, and peinit derives the dependency a service's Identity implies — why the edge is derived rather than declared, and why a role is not an online target.

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](/peios/reference/peinit/service-identity/the-authd-path.md)).
That is a hard dependency in every sense
[`Requires`](/peios/reference/peinit/dependencies/relationships.md)
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:

```text
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.
[*derived.a-real-service-name-and-a-role-share-one-namespace]

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.
[*derived.a-level-on-a-provides-entry-is-rejected]

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.
[*derived.a-declared-role-reference-is-rewritten-at-boot-and-on-every-reload]
`Requires`, `Wants`, and
`BindsTo` are rewritten;
[*derived.requires-wants-and-bindsto-are-all-rewritten] a real service
name is never mistaken for a role,
[*derived.a-real-service-name-wins-over-a-role-of-the-same-name] 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](/peios/reference/peinit/dependencies/readiness-levels.md) 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.
<!-- lint-disable-next-line line-length -->
[*derived.a-service-needing-the-authority-gains-a-requires-on-each-authn-provider]

A service needs it when its `Identity` is not `SYSTEM`, **or** when it has
hooks and its `HookIdentity` is not `SYSTEM`.
[*derived.hooks-running-as-a-non-system-identity-also-need-the-edge] 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.**
  [*derived.a-provider-never-gains-a-dependency-on-its-own-role] An
  authority declaring a non-SYSTEM identity would otherwise require
  itself, and a service that requires itself never starts.
- **An edge already declared is not added again**, whether it was
  declared as `Requires` or `BindsTo`, and including one carrying a
  level. [*derived.an-already-declared-edge-is-not-added-again]
  `Requires = ["authd:ready"]` already orders against the
  authority, and more strictly; adding a plain edge beside it would be a
  second edge to the same service saying less. `BindsTo` requires its
  target as well as binding to it, so the same holds for it.
- **Nothing is derived when no service fills the role.**
  [*derived.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](/peios/reference/peinit/dependencies/graph-validation.md),
in [graph
execution](/peios/reference/peinit/dependencies/graph-execution.md),
at shutdown, and in `svctl status`, where it appears as the dependency it
is rather than as a hidden ordering.
[*derived.the-derived-edge-behaves-exactly-like-a-declared-requires]

Several services MAY fill one role; each becomes its own `Requires`, so
the dependent is ordered after all of them.
[*derived.every-provider-of-the-role-becomes-its-own-requires] 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.
[*derived.an-unfilled-role-is-a-warning-and-the-reload-still-succeeds]

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.
[*derived.the-launch-that-cannot-get-a-token-is-what-fails]

## 7.6.4 A role is not an online target

[§7.5](/peios/reference/peinit/dependencies/readiness-levels.md) 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, and every fork peinit performs is one — its lifecycle, fields, retention,  and ownership.

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).
[*job.every-fork-peinit-performs-is-a-job]

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.
[*job.a-restart-creates-a-new-job]

## 8.1.1 Lifecycle [*job.the-lifecycle-states]

```text
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

```text
Job {
    id:                 GUID       // UUIDv7
    service:            string?    // null for a submitted job
    job_type:           enum       // ServiceMain, PreExecHook, PostExecHook,
                                   // ReloadHook, HealthCheck, Submitted
    state:              enum
    pid:                u32?
    pidfd:              fd?
    resolved_identity:  string     // the resolved service, hook or submitter identity
    token_summary:      object     // the resulting SID, groups, privileges
    image_path:         string
    arguments:          string[]
    created_at_ns:      u64
    started_at_ns:      u64?
    ended_at_ns:        u64?
    exit_code:          i32?
    exit_signal:        i32?
    failure_cause:      string?
    cgroup_id:          string
    cgroup_generation:  u32
    activation_generation: u32
    operation_id:       GUID?      // null for a submitted job
    hook_index:         u32?
}
```

The rules that govern when the nullable fields are populated are what
make a job record trustworthy:

- `id` is assigned **before** the fork, so a job that never forks still
  has an identity. [*job.the-id-is-assigned-before-the-fork]
- `pid` and `pidfd` land on the record only once exec success is
  confirmed by EOF on the error pipe. Until then they are held in
  pending setup state and the job is Created.
  [*job.pid-and-pidfd-land-only-on-exec-confirmation]
- **An exit observed during that window is held, not applied.**
  [*job.an-exit-in-the-setup-window-is-held-not-applied] peinit
  resolves a reaped child to a job by PID, and inside this window no job
  carries the PID yet — a short-lived process can be gone before the
  error pipe is read. The exit is kept against its PID and replayed once
  the job has been started and can receive it. Discarding it would be
  unrecoverable: the job would be started against a PID that is already
  dead and reaped, and no second `SIGCHLD` is coming, so it would stay
  Running for ever. A reaped PID that matches no job *and* no pending
  setup is genuinely not peinit's — PID 1 reaps orphans it never
  started — and is ignored.
- **A notification sent during that window is not refused for it.**
  A service can send `READY=1` before the turn that reads its setup
  status. peinit reads the status first and authenticates the datagram
  after. If the status cannot yet be read, peinit holds the datagram
  until it can (§10.5).
- A setup failure takes the job straight from Created to Failed.
  `ended_at_ns` records the **classification** time, `failure_cause`
  records what went wrong, and `pid`, `pidfd`, `started_at_ns`,
  `exit_code` and `exit_signal` all stay null.
  [*job.a-setup-failure-goes-created-to-failed-with-the-exit-fields-null]
  There was no process to have a PID or an exit status.
- `exit_code` and `exit_signal` are populated only when peinit observed
  an exit — never both, since a process either exits or is killed.
  [*job.exit-code-and-exit-signal-are-never-both-populated]
- For an Abandoned job, `ended_at_ns` records when peinit stopped
  supervising, and the exit fields stay null.
  [*job.an-abandoned-jobs-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).
[*job.a-submitted-jobs-resolved-identity-is-the-job-identitys-user-sid]
`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. [*job.a-terminal-job-is-emitted-then-dropped] 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).
[*job.a-submitted-jobs-entry-outlives-its-record-by-sixty-seconds] 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.
[*job.a-stale-queue-entry-is-discarded-rather-than-fatal] 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.
[*job.a-status-query-returns-the-services-current-main-job]

---

# 8.2 Operations

_Peios / Reference / peinit / Jobs and Operations_

> A requested state machine action as a first-class object — every control command creates one rather than mutating state directly.

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.
[*op.every-control-command-creates-an-operation]

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 [*op.the-operation-states]

```text
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.
[*op.a-deadline-that-raised-is-contained-once] 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.
[*op.a-deadline-that-keeps-raising-is-paced]

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).
[*op.a-restart-is-aborted-when-its-definition-is-withdrawn-mid-stop]

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.
[*op.an-ended-start-leaves-no-readiness-deadline]

## 8.2.2 Fields

```text
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: [*op.the-operation-sources]

| 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).
[*op.shutdown-creates-per-service-stop-operations] 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.
[*op.a-start-completes-when-the-service-reaches-its-goal-state]

**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.
[*op.a-stop-completes-when-the-service-reaches-inactive]

**Restart** is a stop then a start, tracked under one identifier across
both phases, and the type stays `Restart` throughout for observability.
[*op.a-restart-keeps-one-identifier-and-type-across-both-legs]

**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. [*op.reset-is-synchronous]

## 8.2.5 Timeouts

A start, reload, or reset inherits the target's `StartTimeout` as its
maximum lifetime; a stop inherits `StopTimeout`.
[*op.a-start-inherits-starttimeout-and-a-stop-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.
[*op.a-held-start-has-no-lifetime]

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.
[*op.the-operation-clock-starts-at-creation-including-queue-time]

## 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.
[*op.a-terminal-operation-is-dropped-after-sixty-seconds]

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_

> Resolving a new operation against one already pending or running — merging, cross-type conflicts, and the principles behind both.

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. [*conflict.an-operation-of-the-same-type-merges]

| 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. [*conflict.restart-is-not-mergeable-with-itself]
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 [*conflict.the-cross-type-resolutions]

| 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.
[*conflict.combinations-outside-the-table-are-rejected] 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.
[*conflict.a-start-while-reloading-is-answered-with-the-status]

## 8.3.3 The principles

1. **Stop wins over start.** An explicit stop always takes priority. The
   administrator said stop, so stop; a queued start can follow.
   [*conflict.stop-wins-over-start]
2. **Later supersedes earlier.** Start then immediately stop means the
   stop wins and the start is canceled, recorded as superseded.
   [*conflict.a-superseded-start-records-that-it-was-superseded]
3. **Merging is transparent.** The merged caller gets the original
   identifier and blocks on the original operation's outcome.

Reset is rejected outright while anything is in flight, because reset
means "clear a terminal state" and nothing in flight has one.
[*conflict.reset-is-rejected-while-anything-is-in-flight]

## 8.3.4 Dependency propagation

When a start executes against a service with unsatisfied dependencies,
peinit creates start operations for them:

- **`Requires`** — source `DependencyPropagation`. If one fails, the
  parent operation fails with `DependencyFailure`.
  [*conflict.a-failed-requires-dependency-fails-the-parent]
- **`Wants`** — source `DependencyPropagation`. If one fails, the parent
  continues. [*conflict.a-failed-wants-dependency-does-not-fail-the-parent]
- **`BindsTo` recovery** — source `BindsToRecovery`, created when a
  bound target returns to Active, for dependents sitting in Failed with
  cause `BindsToPropagation`.

Dependency-created operations follow the same resolution rules as
administrator-created ones. If a dependency is already starting because
something else also depends on it, the operations merge — and both
graph execution contexts are then associated with the one operation
(§7.3).

`BindsToRecovery` restarts are not subject to the restart budget. They
are created because a dependency returned, not because anything failed.
[*conflict.bindstorecovery-restarts-are-outside-the-restart-budget]

## 8.3.5 Restart policy and timers

A restart-eligible failure creates a start operation with source
`RestartPolicy` once the backoff delay elapses.
<!-- lint-disable-next-line line-length -->
[*conflict.a-restart-eligible-failure-creates-a-start-with-source-restartpolicy]
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: [*conflict.a-timer-firing-creates-an-operation-from-the-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`.
[*conflict.boot-generated-starts-use-the-boot-source]

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_

> The structured events peinit emits at every job and operation transition and for its own records, their catalog names, and the emission policy asked before each is built.

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).
[*emit.every-job-and-operation-transition-emits-a-kmes-event]

**There is no event socket.** Structured events are not sent to eventd
over any connection. [*emit.there-is-no-event-socket] 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.
<!-- lint-disable-next-line spelling -->
[*emit.every-event-is-a-catalogue-type-with-a-nested-payload]
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.
[*emit.peinit-asks-the-emission-policy-before-building-an-event]
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 [*emit.the-three-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.
[*emit.job-ended-cuts-its-arguments-and-says-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.
[*emit.a-submitted-jobs-events-carry-no-service-and-no-operation] 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).
[*emit.job-status-is-emitted-at-most-once-per-job-per-second]

**`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).
[*emit.output-dropped-is-emitted-once-per-job]

## 8.4.4 Operation events [*emit.the-operation-events-and-what-they-add]

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.
[*emit.every-operation-event-carries-the-common-fields]

| 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.
[*emit.an-operations-duration-is-measured-from-its-request] 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).
[*emit.an-operations-result-is-its-outcome-detail]

## 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. [*emit.a-graph-dispatchs-events-are-emitted-in-causal-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`.
[*emit.a-graph-contexts-operations-are-requested-when-the-context-is-built]

## 8.4.6 Peinit's own records [*emit.audit-records-go-through-the-same-path]

peinit's own records go through the same path:

- `peinit.on-failure.suppressed` when the fallback chain guard trips;
- `peinit.graph.validation.failed` and `peinit.graph.validation.warned`
  for validation findings, one per finding, and `peinit.boot.downgraded`
  for each finding that forced Safe mode;
- `peinit.config.reload.applied` for an explicit `reload-config` and for
  the reload that ends the boot window, and
  `peinit.config.reload.deferred` for a reload during it (§3.7);
- `peinit.notify.rejected` for a refused notification datagram, and
  `peinit.fd-store.rejected` for a refused descriptor;
- `peinit.notify.status.reported`, `.errno.reported`,
  `.exit-status.reported`, `.stopping.reported` and
  `.progress.reported` for the event-emitting notification fields, the
  last at most once a second for each activation (§10.5);
- `peinit.cgroup.leaked` the first time a sub-cgroup is found still
  populated after its post-kill deadline (§5.7);
- `peinit.graph.operation.ended` for a graph member's terminal outcome;
- `peinit.recovery.entered` for the reason peinit dropped to a recovery
  shell (§2.8);
- `peinit.critical-service.failed` and `peinit.service.abandoned` from
  the shutdown path (§12);
- `peinit.service.reload.timed-out` for a reload a service started and
  never confirmed (§6.5).

Records are events rather than logs, and that distinction is the point:
the ring buffer persists from the moment PKM loads, so a recovery during
Phase 1 is captured before the registry exists, let alone eventd.

## 8.4.7 Access decisions

peinit writes no event of its own for a refused command. Every access
check it makes goes through KACS AccessCheck, and KACS records the
decision, as `kacs.audit.access.checked`, when the descriptor's SACL asks
for it (PGSS §6.7). [*emit.a-refused-command-is-recorded-by-kacs]
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`:
[*emit.every-access-check-names-its-object-in-an-audit-context]

| 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 process any admitted principal asks peinit to run and supervise — the two doors, the two identities, how a submission becomes a running job, and how it is managed, ends and is forgotten.

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`.
[*submit.connecting-to-the-jobs-socket-is-the-permission-to-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.
[*submit.both-doors-check-the-same-descriptor]

## 8.5.2 Two identities

Every submission involves two identities, and peinit keeps them apart.

The **submitter** is the connection identity: the peer token captured
once, at accept, exactly as the control socket captures it (§10.1). It
is recorded on the job, it is what the quota counts against, and it is
the owner of the job's descriptor. A submitter that connects while
impersonating is recorded as the principal it was impersonating.

The **job identity** is what the process runs as. It is established in
exactly one of two ways, and the boundary that does it —
`LinuxJobIdentityProvider` — has no third:

- **No token attached.** peinit opens the primary token of the
  connecting *process* through the kernel's handle on it. The handle
  comes from `SO_PEERPIDFD` at accept; the token comes from
  `peios_token_open_process` on that pidfd with `QUERY | DUPLICATE`.
  The job then has the identity a child of the submitter would have
  had — its primary token, with no impersonation inherited
  [*submit.with-no-token-attached-the-job-runs-as-the-peers-primary-token]
  — so a submitter that was impersonating when it connected produces a
  job running as *itself* while being recorded as a submitter under the
  impersonated identity. A submitter that wants the impersonated
  identity on the job attaches it.
- **A token attached.** The kernel delivered a token with the `submit`
  message through `KACS_SCM_TOKEN`, having run the impersonation gates
  with the submitter as installer and recorded on the token the lower
  of the socket's level and the source's own (Peios Kernel TRM §3.5).
  peinit uses that token as it arrived, at `QUERY | IMPERSONATE |
  DUPLICATE`.

Either way the source is duplicated to a **primary** token at its own
impersonation level, with `TOKEN_ALL_ACCESS`, and the duplicate is
what the child installs. The level carries through: a job started from
an Impersonation-level token cannot convey Delegation, and a submitter
that needs it — for a session that will authenticate onward on its
user's behalf — sets its own jobs connection to Delegation before
attaching, because the attach is clamped to the socket's level.

peinit refuses, with `BAD_TOKEN`, a source whose impersonation level is
below Impersonation
[*submit.a-token-below-impersonation-level-is-refused-with-bad-token] —
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: [*submit.a-refusal-leaves-nothing-behind]

1. **Parse and validate the definition** against the attachment count
   (below). A malformed definition is `INVALID_ARGUMENTS` before any
   identity work is done.
   [*submit.a-malformed-definition-is-invalid-arguments]
2. **Refuse during shutdown** with `INVALID_STATE`. The other four
   commands keep working while the system goes down.
3. **Establish the job identity**, as above.
4. **Check the quota.** peinit counts the submitter's live jobs — those
   not yet terminal — by submitter SID against
   `Machine\System\Init\MaxJobsPerSubmitter`, default 64. SYSTEM
   (`S-1-5-18`) is exempt. At the bound the answer is
   `QUOTA_EXCEEDED`. [*submit.the-quota-counts-a-submitters-live-jobs] A
   job stops counting the moment it is terminal, not when its retained
   record is dropped.
   [*submit.a-job-stops-counting-against-the-quota-when-it-is-terminal]
5. **Build the job's descriptor**: the one the submission supplied in
   SDDL, used as given, or the default (below).
6. **Create the record, the entry and the launch queue entry**, in one
   `SupervisorWork` transaction.

The job is two things in peinit's state. The **job record** is the same
`JobRecord` every fork gets (§8.1), with `job_type: Submitted`, no
service, no operation, the job identity's user SID as
`resolved_identity`, and a cgroup id under `/sys/fs/cgroup/peinit/jobs/`
named by the job's GUID. The **entry** is what the jobs system holds
beside it: the submitter, the job identity's user SID and logon
session, the definition, the descriptor, the prepared token, the
attached descriptors with their names, the output sink, readiness and
the retained `STATUS` and `PROGRESS`, any stop in progress, and once the
job is terminal its outcome and retention deadline. Records are dropped
when terminal, as every job's is; entries outlive them for the grace
period, which is how a terminal job still answers `status`.

The `submit` is answered when the job **leaves `created` ** — on exec
confirmation or on launch failure — and not before.
[*submit.the-submit-is-answered-when-the-job-leaves-created] 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.
[*submit.a-failed-launch-is-still-status-ok] 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 [*submit.the-definitions-defaults-and-validation]

| 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.
[*submit.descriptors-must-match-the-attachment-count]
The combined size of `arguments` and `environment` is bounded at 2 MiB,
below what `execve` accepts.
[*submit.arguments-and-environment-are-bounded-at-two-mib] 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).
<!-- lint-disable-next-line line-length -->
[*submit.the-default-descriptor-grants-the-submitter-system-and-administrators]
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.
[*submit.a-supplied-descriptor-is-used-as-given] 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). [*submit.a-denial-is-answered-access-denied]

## 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).
<!-- lint-disable-next-line line-length -->
[*submit.attached-descriptors-are-placed-from-three-upward-with-the-listen-variables]
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).
[*submit.a-submitter-cannot-override-the-protocol-variables]

The cgroup is `/sys/fs/cgroup/peinit/jobs/<guid>`, a tree of its own
rather than a service's.
[*submit.the-job-runs-in-a-cgroup-of-its-own-under-peinit-jobs]

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`.
[*submit.a-launch-failure-is-parent-setup-failure-or-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.
[*submit.a-stop-on-a-queued-job-cancels-it-before-it-runs] 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:
<!-- lint-disable-next-line spelling -->
[*submit.the-notification-fields-a-submitted-job-may-send]

| 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:
[*submit.the-submitted-job-deadlines]

| 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`.
[*submit.a-stop-sigterms-the-main-process-and-arms-the-kill-deadline] 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.
<!-- lint-disable-next-line line-length -->
[*submit.a-second-stop-changes-nothing-and-a-stop-on-a-terminal-job-is-a-no-op]

At the kill deadline the cgroup is killed.
[*submit.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.
[*submit.a-process-that-survives-sigkill-is-abandoned-as-process-unkillable]

`signal` is the raw mechanism, deliberately: one signal, by number, to
the main process through its pidfd, on a running job only.
[*submit.signal-acts-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.
<!-- lint-disable-next-line spelling -->
[*submit.a-signalled-kill-produces-a-failed-job-with-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.
[*submit.success-is-exit-zero-or-a-code-in-success-exit-codes] 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.
[*submit.cause-is-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.
[*submit.a-stop-the-process-handled-completes-with-cause-explicit-stop] A
stopped job that died to the signal is `failed` with `exit_signal` set
and the same cause.
[*submit.a-stopped-job-killed-by-the-signal-fails-with-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.
[*submit.a-purged-or-unknown-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.
[*submit.every-live-job-is-stopped-with-cause-shutdown] 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. [*submit.the-two-halves-of-svctls-job-commands]
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_

> What the job and operation model looks like from outside — identifiers, waiting, and why merging is invisible to the caller.

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. [*protoview.every-lifecycle-command-returns-an-identifier]

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).
[*protoview.a-command-with-nothing-to-do-returns-the-status-instead]

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.
[*protoview.the-job-commands-never-create-an-operation]

## 8.6.2 Waiting

Lifecycle commands block by default until the operation is terminal.
[*protoview.lifecycle-commands-block-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.
[*protoview.reload-returns-immediately-unless-asked-otherwise]

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.
[*protoview.a-waiting-connection-is-never-closed-by-the-idle-timeout]

## 8.6.3 Merging is invisible

A caller whose command merged receives the surviving operation's
identifier and blocks on that operation's outcome.
[*protoview.a-merged-caller-blocks-on-the-surviving-operations-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.
[*protoview.a-merged-callers-identifier-is-older-than-their-request]

## 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.
[*protoview.what-an-operations-result-carries]

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.
[*protoview.a-reloads-result-determines-its-mode]

## 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. [*protoview.the-job-view-and-its-fields] Every inapplicable
field is present and null, and `pid` is null once the job is terminal —
there is no process to name.
[*protoview.every-inapplicable-field-is-present-and-null] 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.
[*protoview.an-abandoned-jobs-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).
[*protoview.the-job-view-is-one-shape-on-both-sockets] And `job-list`
is a list of the same views, filtered by `JOB_QUERY` on each (§10.2).
[*protoview.job-list-is-filtered-by-job-query] 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_

> Submitted-job identity conveyance, definition fields, descriptor passing,  and status/progress messages.

This reference expands the [submitted-job operator
workflow](/peios/using-peios/services-and-jobs/jobs-and-operations.md#submitted-jobs). 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](/kernel/internals/kacs/access-check/the-dacl-walk.md)) gates the
  attach: it verifies the submitter could act as that identity, at that
  impersonation level, at that moment. peinit turns the attached token into
  the job's primary token. This is how `backupd` runs a backup as its client,
  or a logon service starts a session as the user who authenticated — the
  same [impersonation](/kernel/internals/kacs/impersonation/overview.md) 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](/peios/using-peios/services-and-jobs/execution-environment.md), 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](/peios/using-peios/services-and-jobs/service-types.md) 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_

> The OnCalendar grammar peinit parses — component syntax, named shortcuts, timezones, daylight saving,  and precision.

A timer schedule is a calendar expression in systemd's `OnCalendar`
format. The grammar below is what peinit parses.

```text
DayOfWeek Year-Month-Day Hour:Minute:Second Timezone
```

Every field is optional, and which fields are present is worked out
positionally from their shape.
[*cal.fields-are-optional-and-identified-positionally]

| 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 `*-*-*`.
[*cal.a-time-only-expression-implies-every-date]
`Hour:Minute` alone defaults the seconds to `00`.
[*cal.hour-minute-defaults-the-seconds-to-zero]

Years range 0–9999, months 1–12, days 1–31.
[*cal.numeric-components-have-fixed-ranges]

## 9.1.1 Component syntax

Every numeric component, and the weekday, accepts:
<!-- lint-disable-next-line line-length -->
[*cal.numeric-components-and-the-weekday-take-wildcards-lists-ranges-and-steps]

- **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.
  [*cal.a-reversed-range-is-a-parse-error]
- **Repetition** — a value or range suffixed with `/` and a step.
  `value/step` matches the value and every multiple of the step above
  it, so `0/15` in the minute field is 0, 15, 30 and 45.
  `start..end/step` walks from start to end inclusive.
  [*cal.a-step-matches-every-multiple-above-its-start]

Weekdays are English names, case-insensitive, abbreviated or full, and
accept lists and ranges.
[*cal.weekday-names-are-english-case-insensitive-and-abbreviable]
`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. [*cal.a-tilde-counts-the-day-from-the-end-of-the-month]
`*-*~01` is the last day of every month; `*-02~03` is the
third-to-last day of February.

<!-- "May" here is the month. -->
<!-- lint-disable spelling -->
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. [*cal.a-step-after-a-tilde-walks-the-offset-downwards]
`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.
<!-- lint-enable spelling -->

Wildcards, ranges and lists are also accepted after `~`, so `~*` matches
every day and `~03..07` the third- to seventh-to-last.
[*cal.wildcards-ranges-and-lists-are-accepted-after-a-tilde]

<!-- lint-disable-next-line line-length -->
## 9.1.3 Named shortcuts [*cal.the-named-shortcuts-expand-to-the-equivalent-expression]

| 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.
[*cal.shortcut-names-are-case-insensitive-and-take-a-trailing-timezone]

## 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.
[*cal.a-timezone-is-an-iana-name-and-its-absence-means-system-local]

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. [*cal.an-unrecognised-timezone-is-a-parse-error]

## 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.
  [*cal.a-time-in-the-spring-forward-gap-does-not-fire]
  A schedule of `*-03-31 01:30 Europe/London` skips 2024 entirely.
- **Fall back**, where an hour repeats: a scheduled time inside the
  repeated interval fires exactly once, on the **first** occurrence.
  [*cal.a-time-in-the-repeated-hour-fires-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. [*cal.a-fraction-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. |

> [!NOTE]
> An expression that parses but can never match — `*-02-30`, or a fixed
> year already past — is not rejected at parse time.
> [*cal.an-unsatisfiable-expression-is-not-a-parse-error]
> Computing its next occurrence walks forward a day at a time for ten
> years and then gives up, reporting no future occurrence.
> [*cal.an-unsatisfiable-expression-is-walked-for-ten-years] The horizon
> is there because walking the full year range would turn an
> unsatisfiable schedule into a boot that hangs.

---

# 9.2 Evaluation and Arming

_Peios / Reference / peinit / Timers_

> A timer is a trigger rather than a service type — how one is armed, how it fires, and what multiple triggers do.

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.
[*evalt.a-timer-is-a-trigger-on-an-ordinary-service]

## 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.
[*evalt.every-active-trigger-gets-its-own-armed-descriptor]

A disabled service gets neither a registration nor a firing.
[*evalt.a-disabled-service-is-neither-registered-nor-fired]

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`.
[*evalt.a-bad-schedule-fails-only-its-own-trigger-and-is-reported]
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.
[*evalt.the-next-occurrence-search-gives-up-after-ten-years] 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 [*evalt.a-firing-is-classified-from-the-services-type-and-state]

```text
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.
[*evalt.a-firing-in-any-other-state-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.
[*evalt.a-firing-for-a-service-that-is-gone-does-nothing] 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.
[*evalt.no-last-run-is-recorded-for-a-deleted-definition]

The last-run write happens in a forked child so that the event loop
never waits on the registry
[*evalt.the-last-run-write-happens-in-a-forked-child]
— 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.
[*evalt.timer-writer-closes-inherited-descriptors-before-opening-its-key]

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:

```text
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 [*evalt.a-failed-last-run-write-is-reported-and-nothing-is-retried]
— 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.
[*evalt.a-oneshot-firing-mid-run-becomes-one-pending-run]

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.
[*evalt.multiple-firings-during-one-run-collapse-into-one]

## 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.
[*evalt.triggers-on-one-service-are-independent]

## 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.
[*evalt.status-reports-each-trigger-as-armed]

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.
[*evalt.what-is-reported-is-what-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.
[*evalt.the-last-firing-is-seeded-at-boot-and-kept-across-a-reload]

---

# 9.3 Persistence

_Peios / Reference / peinit / Timers_

> Where last-run history lives in the registry, how a missed firing is caught up after a reboot, and when the timestamp is written.

`TimerPersistent`, on by default, controls whether a run missed across a
reboot is caught up. [*persist.timerpersistent-is-on-by-default]

## 9.3.1 Where history lives

Last-run timestamps are `REG_QWORD` values in the registry, written
after a firing. [*persist.last-run-timestamps-are-reg-qword-values]

A service with a **single** timer trigger stores its timestamp as
`LastTimerRun` on the service's own key:
[*persist.a-single-trigger-stores-lasttimerrun-on-the-service-key]

```text
Machine\System\Services\<name>\LastTimerRun
```

A service with **multiple** triggers stores one per trigger under a
subkey, named by the schedule string:
[*persist.multiple-triggers-store-one-timestamp-per-trigger-under-timerstate]

```text
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.
[*persist.a-schedule-name-is-percent-encoded-with-uppercase-hex]
This is the same encoding used for cgroup ids (§5.1). The schedule
`*-*-* 02:00:00` is stored as:

```text
%2A-%2A-%2A%2002%3A00%3A00
```

Two identical schedule strings on one service encode to the same name
and therefore share one timestamp.
[*persist.two-identical-schedules-share-one-timestamp]

Timer firings are infrequent, so the write cost is negligible.

## 9.3.2 Catching up [*persist.a-missed-run-is-caught-up-once-at-boot]

On boot, for each persistent trigger:

1. Read the last-run timestamp.
2. Compute the next scheduled firing after it.
3. If that time has already passed, at least one run was missed: fire
   once, immediately.
4. Compute the next future occurrence normally.

Catch-up is always a **single** run however many were missed.
[*persist.catch-up-is-one-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.
[*persist.a-trigger-with-no-history-catches-up-once]

`TimerPersistent=0` ignores history entirely — peinit does not even read
the registry for that trigger, and computes the next occurrence from
now. [*persist.timerpersistent-zero-ignores-history]

## 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.
[*persist.the-timestamp-is-written-when-the-start-is-initiated]
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.
[*persist.unchanged-timers-keep-their-armed-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.
[*persist.a-reload-re-arms-from-now-with-no-catch-up]

> [!NOTE]
> Timestamps for a multi-trigger service are keyed by schedule string,
> so changing a schedule orphans its history and the new schedule
> produces one spurious catch-up run.
> [*persist.changing-a-schedule-orphans-its-history]
> A stable trigger identifier would
> fix it; schedule changes are rare and one extra run is the whole cost.
> A single-trigger service is unaffected, since its timestamp lives at a
> fixed name.

---

# 9.4 Jitter and Clocks

_Peios / Reference / peinit / Timers_

> The random delay applied to each firing, which clock a timer is evaluated against, and what a clock change does.

## 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.
<!-- lint-disable-next-line line-length -->
[*jitter.a-random-delay-of-zero-to-timerjitter-seconds-is-added-to-each-firing]

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. [*jitter.the-delay-is-recomputed-on-every-firing]
With `TimerJitter=0` no randomness is consulted at all.
[*jitter.zero-jitter-consults-no-randomness]

Jitter is applied **after** the calendar expression is evaluated and is
only ever added, so a timer never fires early — only late.
[*jitter.a-timer-never-fires-early]

The boot catch-up firing is not jittered. It fires immediately, and
jitter applies from the next armed occurrence onward.
[*jitter.the-boot-catch-up-firing-is-not-jittered]

## 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.
<!-- lint-disable-next-line spelling line-length -->
[*jitter.calendar-timers-are-absolute-realtime-timers-cancelled-on-a-clock-set]

**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. [*jitter.interval-timers-are-monotonic]
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.
[*jitter.last-run-timestamps-are-recorded-on-the-realtime-clock]
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;
  [*jitter.a-backward-step-pushes-the-next-firing-later]
  a forward step that crosses an occurrence fires it once.
  [*jitter.a-forward-step-across-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.
  [*jitter.a-step-inside-a-jitter-window-fires-at-the-unjittered-time]
- **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.
  [*jitter.an-elapsed-absolute-deadline-fires-once-on-resume]
- **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.
  [*jitter.a-missed-occurrence-within-one-uptime-fires-once]
- **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.
  [*jitter.a-last-run-timestamp-in-the-future-is-treated-as-unknown]
- **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.
  [*jitter.a-boot-time-catch-up-decision-is-never-revisited]
  Short of NTP-aware rescheduling, this remains an edge.

> [!NOTE]
> The calendar parser deserves heavy testing. Time parsing is a rich
> source of edge cases: month boundaries, leap years,
> last-day-of-month arithmetic, DST transitions and timezone database
> updates are all fertile ground for subtle errors, and every one of
> them is a bug that only appears on a particular day of a particular
> year.

---

# 10.1 The Control Socket

_Peios / Reference / peinit / The Control Interface_

> The Unix stream socket every runtime command arrives on — how it is created and protected, and the peer token it captures.

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.
[*control.the-listener-flags-and-backlog] Accepted connections come from
`accept4` with both flags, so no connection descriptor is ever inherited
by a service. [*control.no-connection-descriptor-is-inherited]

peinit sets **no POSIX mode bits** on the socket, on the notification
socket, or on anything else it creates.
[*control.no-posix-mode-bits-are-set] 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
[*control.the-socket-descriptor]:

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

| Key | Default | Meaning |
|---|---|---|
| `Machine\System\Init\MaxControlConnectionsPerUser` | 16 | Concurrent connections one caller can hold, counted by the user SID of its token. SYSTEM is exempt. [*control.max-control-connections-per-user] |
| `Machine\System\Init\MaxControlConnections` | 256 | Concurrent connections in all: a bound on peinit's descriptors, set well above what callers reach. [*control.max-control-connections] |
| `Machine\System\Init\MaxRequestSize` | 65536 | Maximum request size, in bytes. [*control.max-request-size] |
| `Machine\System\Init\ConnectionTimeout` | 30 | Seconds before an idle connection is closed. [*control.connection-timeout] |

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.
[*control.an-inadmissible-connection-is-closed-without-a-response]

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 [*control.the-peer-token-is-read-once-at-accept]

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
[*control.an-impersonating-peer-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` [*control.a-connection-with-work-in-flight-is-never-idle]
— 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.
<!-- lint-disable-next-line spelling -->
[*control.pipelined-requests-serialise-behind-a-wait]

## 10.1.5 Timestamps [*control.timestamps-are-projected-from-the-monotonic-clock]

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_

> The fixed sequence a parsed command runs before it does anything — the shutdown gate, the rights checked, and what is filtered rather than denied.

A parsed command runs a fixed sequence before it does anything.

1. **The shutdown gate.** If peinit is shutting down, everything except
   `status`, `list`, `operation-status`, `boot`, `job-status`,
   `job-list` and `job-stop` is rejected. [*dispatch.the-shutdown-gate]
   `boot` stays open because, like the service queries, it changes
   nothing. [*dispatch.boot-passes-the-shutdown-gate] 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.
   [*dispatch.the-gate-runs-before-the-access-check]
2. **Resolve the target.** A command naming no definition, and no
   addressable definition-removed entry, returns `UNKNOWN_SERVICE`;
   one naming no submitted job peinit holds returns `UNKNOWN_JOB`.
   [*dispatch.an-unresolvable-target-is-unknown] peinit does not
   synthesise a descriptor for something that does not exist.
3. **AccessCheck.** The caller's token, the target's descriptor, the
   generic mapping, the right the command requires (§4.6, §4.7), and an
   audit context naming the target: the service, the job, or the
   control door itself (§8.4). For a job the descriptor is the job's own
   and the mapping is the job mapping (§8.5).
   [*dispatch.the-access-check-inputs]
4. **On denial**, return `ACCESS_DENIED`. The decision is recorded by
   KACS, as `kacs.audit.access.checked` naming the caller, the target
   and the access requested and granted, whenever the target's
   descriptor has a SACL that asks for it; every descriptor peinit
   builds itself audits every refusal. peinit writes no event of its
   own. [*dispatch.a-denial-is-answered-and-audited] Silent denial is
   not acceptable; a denial an administrator cannot see is
   indistinguishable from a bug, which is why the defaults audit, and
   why a descriptor written to the registry should keep a SACL that
   does (§4.6).
5. **On grant**, classify the command against the service's state
   (§10.3) and act.

## 10.2.1 Rights

| Command | Right |
|---|---|
| `start` | `SERVICE_START` [*dispatch.right-start] |
| `stop` | `SERVICE_STOP` [*dispatch.right-stop] |
| `restart` | `SERVICE_START` and `SERVICE_STOP`, requested as one mask [*dispatch.right-restart] |
| `reload` | `SERVICE_INTERROGATE` [*dispatch.right-reload] |
| `reset` | `SERVICE_STOP` [*dispatch.right-reset] |
| `status` | `SERVICE_QUERY_STATUS` [*dispatch.right-status] |
| `list` | Filtered per service by `SERVICE_QUERY_STATUS` [*dispatch.right-list] |
| `operation-status` | `SERVICE_QUERY_STATUS` on the target service [*dispatch.right-operation-status] |
| `job-status` | `JOB_QUERY` on the job [*dispatch.right-job-status] |
| `job-list` | Filtered per job by `JOB_QUERY` [*dispatch.right-job-list] |
| `job-stop` | `JOB_STOP` on the job [*dispatch.right-job-stop] |
| `shutdown` | `SYSTEM_SHUTDOWN` [*dispatch.right-shutdown] |
| `reload-config` | `SYSTEM_RELOAD_CONFIG` [*dispatch.right-reload-config] |
| `boot` | `SYSTEM_QUERY_STATUS` on the control descriptor, which by default every authenticated principal holds (§4.7) [*dispatch.right-boot] |

`operation-status` resolves the operation before it checks the right, so
an unknown identifier is reported as unknown regardless of who asked.
[*dispatch.operation-status-resolves-before-it-checks]
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.
[*dispatch.a-retained-operation-keeps-its-services-descriptor]

`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. [*dispatch.job-stop-creates-no-operation]

## 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.
[*dispatch.status-reports-the-callers-rights] A lifecycle command that
has nothing to do answers with the status (§10.3), and that carries
`granted` for its caller too.
[*dispatch.a-status-answering-a-command-reports-the-callers-rights]

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`.
[*dispatch.job-views-on-the-control-socket-report-the-callers-rights]

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.
[*dispatch.a-maximum-allowed-check-is-not-a-denial]

## 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 [*dispatch.list-filters-rather-than-denies]. 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.
[*dispatch.a-definition-removed-service-is-listed-without-saying-so]

`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.
[*dispatch.job-list-filters-before-it-checks]
Terminal jobs still within their retention are listed; a caller that
wants only live ones filters by `state`.
[*dispatch.terminal-jobs-within-retention-are-listed]

---

# 10.3 The Command × State Matrix

_Peios / Reference / peinit / The Control Interface_

> The defined answer for every command sent to a service in an unexpected state, including backoff, abandoned and definition-removed services.

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.

| | Inactive | Starting | Active | Reloading | Stopping | Completed | Backoff | Failed | Abandoned | Skipped |
|---|---|---|---|---|---|---|---|---|---|---|
| start [*dispatch.matrix.start] | Start | MERGE | ALREADY | ALREADY | QUEUE | Start | DEFER | Start | ERROR | Start |
| stop [*dispatch.matrix.stop] | NOOP | Cancel+Stop | Stop | Stop | MERGE | Clear | Clear | NOOP | ERROR | NOOP |
| restart [*dispatch.matrix.restart] | Start | QUEUE | Restart | Restart | QUEUE | Start | Restart | Start | ERROR | Start |
| reload [*dispatch.matrix.reload] | ERROR | ERROR | Reload | MERGE | ERROR | ERROR | ERROR | ERROR | ERROR | ERROR |
| reset [*dispatch.matrix.reset] | NOOP | ERROR | ERROR | ERROR | ERROR | ERROR | ERROR | Clear | Clear | Clear |
| status [*dispatch.matrix.status] | OK | OK | OK | OK | OK | OK | OK | OK | OK | OK |

**ALREADY** — the service is already where the command would take it and
no operation of that type is in flight. peinit returns the current
status rather than an error.

**MERGE** — an operation of that type is already running. The command
merges into it; the caller receives that operation's identifier and, if
waiting, blocks on its outcome.

**DEFER** — create a Pending start operation but do not execute it until
the existing backoff deadline expires. A deferred start already present
is merged into.

**QUEUE** — the operation is queued Pending and executes after the
current one completes.

**NOOP** — the command has no effect. peinit returns the status.

**ERROR** — the command is invalid for the state.

**Clear** — reset to Inactive.

**Cancel** — abort the current operation, then proceed.

## 10.3.1 Backoff

Backoff is the interesting one, because the service is down with an
automatic restart already pending.

- `start` creates or merges into a **deferred** start operation and
  honors the remaining delay. It does not short-circuit the backoff.
  If the automatic restart later becomes due, it merges into the
  administrator's operation, so the identifier the caller holds is the
<!-- lint-disable-next-line spelling -->
  one that executes. [*dispatch.backoff-start-honours-the-remaining-delay]
- `stop` cancels both the pending restart and any deferred start, and
  the service goes Inactive. A subsequent automatic restart is refused,
  because the service is not in Backoff.
  [*dispatch.backoff-stop-cancels-the-pending-restart]
- `restart` replaces the automatic restart with the administrator's.
  A Restart operation with source `admin` is queued Pending and honors
  the remaining delay exactly as a deferred `start` does; when the delay
  expires it is that operation — keeping its type, for observability —
  that executes, so the identifier the caller holds is the one that
  runs. A deferred `start` already pending is canceled with reason
  `superseded_by_restart`, and a second `restart` merges into the
  pending one rather than queueing behind it. Nothing is sent to the
  control boundary, because there is no process for it to act on.
  [*dispatch.backoff-restart-replaces-the-automatic-one]
- `reload` and `reset` are invalid: there is no process to reload, and
  no terminal state to clear.

## 10.3.2 Skipped

`start` and `restart` clear Skipped before they run. A Skipped service
is not in a state a start can proceed from — the state machine permits
`Skipped -> Inactive` and nothing else — so the activation performs that
transition first, then re-evaluates the conditions from scratch.
[*dispatch.skipped-is-cleared-before-a-start-re-evaluates] 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. [*dispatch.the-skipped-clear-is-reported-as-a-transition]

`reset` also clears Skipped, and differs only in stopping there.
[*dispatch.reset-clears-skipped-and-stops-there]

## 10.3.3 Abandoned [*dispatch.abandoned-accepts-only-reset]

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.

<!-- lint-disable-next-line line-length -->
## 10.3.4 Definition-removed services [*dispatch.a-definition-removed-service-accepts-only-stop-and-status]

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_

> A full atomic re-read of the registry rather than a live update — what changes, and how removals and the compiled-in service are handled.

`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.
[*control.reload-config.is-the-registry-watch-path]

## 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.
[*control.reload-config.reads-precede-every-mutation] 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.
[*control.reload-config.a-failed-validation-changes-nothing] 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.
[*control.reload-config.an-undecodable-definition-fails-only-that-service]

## 10.4.2 What changes

- Every service definition is re-read.
  [*control.reload-config.every-definition-is-re-read]
- A new dependency graph is built and validated.
- Running services are unaffected and continue on their activation
  generation. [*control.reload-config.running-services-are-unaffected]
- New definitions take effect at the next start, restart, or trigger.
  [*control.reload-config.a-changed-definition-takes-effect-at-the-next-start]
- New services become available for `start` immediately.
  [*control.reload-config.a-new-service-is-startable-at-once]
- 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.
  [*control.reload-config.calendar-timers-are-re-armed-without-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.
[*control.reload-config.refreshes-more-than-definitions] It also prunes
the fd stores of services that have been removed.
[*control.reload-config.prunes-fd-stores-of-vanished-services]

## 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. [*control.reload-config.registryd-is-exempt] 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_

> The datagram socket services report on themselves over — authenticating a sender, applying a datagram, and the bounds on it.

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.
[*notify.the-path-reaches-a-service-through-notify-socket]
The kernel command line can override it with `peios.notifysocket=`.
[*notify.the-path-is-overridable-on-the-kernel-command-line]
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. [*notify.there-is-one-datagram-socket-for-every-service]

## 10.5.1 The descriptor [*notify.the-socket-descriptor]

```text
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.
[*notify.the-parent-directory-descriptor] 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. [*notify.a-datagram-without-credentials-is-rejected]
Descriptors for the fd store arrive alongside, as `SCM_RIGHTS`.

Authentication then runs five steps, and each closes a hole the previous
one leaves:

1. **Find the sender.** Scan for the current *service-main* job whose
   PID equals the sender's. Only a main job is ever a candidate, which
   is what makes `NotifyAccess=Main` the only mode there is — a hook or
   a health check cannot notify on a service's behalf.
<!-- lint-disable-next-line spelling -->
   [*notify.only-a-services-main-job-may-notify] 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.
   [*notify.the-pidfd-is-verified-against-the-senders-pid]
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.
   [*notify.a-stale-activation-generation-is-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). [*notify.a-rejected-datagram-is-dropped-and-recorded]

The UID and GID in the credentials are parsed and never used.
[*notify.the-credential-uid-and-gid-are-not-policy-inputs] 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.
[*notify.a-senders-pending-setup-status-is-read-before-its-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.
[*notify.a-datagram-whose-setup-cannot-yet-be-read-is-held] 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. [*notify.every-line-of-a-datagram-is-applied] 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.
[*notify.a-malformed-line-voids-the-whole-datagram] 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.
[*notify.status-errno-and-exit-status-emit-events] 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. [*notify.stopping-emits-an-event] 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.
[*notify.progress-emits-at-most-one-event-a-second]

`READY=1` and `RELOADING=1` emit nothing, deliberately: both are
observable through the state transitions they cause.
[*notify.ready-and-reloading-emit-no-event]

`STATUS=` is additionally stored on the service's runtime state and
exposed as `status_text` in a status query.
[*notify.status-is-exposed-as-status-text] 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.
[*notify.status-text-is-cleared-on-each-activation-generation]

`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=`. [*notify.progress-is-exposed-as-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.
[*notify.progress-is-cleared-on-each-activation-generation]

`ERRNO=` and `EXIT_STATUS=` are not stored. They are emitted and
otherwise not retained. [*notify.errno-and-exit-status-are-not-stored]

## 10.5.5 Bounds [*notify.the-datagram-and-descriptor-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_

> Keeping file descriptors across a service's own restart — storing, removing, injecting,  and clearing them.

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
[*fdstore.fdstoremax-defaults-to-zero-and-zero-disables-the-store]: most
services do not need it, and holding descriptors on behalf of a service
that will never ask for them back is pure cost.

## 10.6.1 Storing

When an authenticated datagram carries `FDSTORE=1` with descriptors
attached:

1. If `FdStoreMax` is 0, peinit logs the rejection and **closes** the
   descriptor. [*fdstore.a-disabled-store-closes-the-descriptor]
2. If the store already holds `FdStoreMax` entries, peinit logs the
   rejection and closes the descriptor. The existing store is not
   modified — a full store does not evict.
   [*fdstore.a-full-store-does-not-evict]
3. `FDNAME=<name>` names it; an absent or empty name means `stored`.
   [*fdstore.an-unnamed-descriptor-is-named-stored]
4. `FDPOLL=0` marks the descriptor exempt from poll monitoring.

Either rejection emits a `peinit.fd-store.rejected` event carrying the
service, the descriptor's name and the reason (`disabled` or `full`), so
a service whose descriptors are being silently dropped can find out why.
[*fdstore.a-rejection-emits-an-event]

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
<!-- lint-disable-next-line spelling -->
rejected and closed. [*fdstore.several-descriptors-may-share-a-name]

peinit does not monitor stored descriptors. The `FDPOLL` flag is
recorded and nothing reads it, so no stored descriptor is evicted for
becoming invalid. [*fdstore.stored-descriptors-are-never-monitored]

## 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. [*fdstore.a-named-remove-closes-every-descriptor-of-that-name]

`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. [*fdstore.an-unnamed-remove-aborts-the-fd-store-step]

## 10.6.3 Injecting

When a service restarts, peinit injects the stored descriptors during
the child's pre-exec path (§5.4):

1. They are placed consecutively from `SD_LISTEN_FDS_START` — descriptor
   3 — upward, with close-on-exec cleared: the only sanctioned
   exception to the close-on-exec discipline.
   [*fdstore.descriptors-are-injected-from-descriptor-three-upward]
2. `LISTEN_FDS` is set to the count.
   [*fdstore.listen-fds-is-the-count]
3. `LISTEN_FDNAMES` is set to a **colon-separated** list of names in the
   same order as the descriptor numbers.
   [*fdstore.listen-fdnames-is-colon-separated-and-in-order]
4. The store is cleared. peinit has released them.

All three variables are omitted entirely when the store is empty.
[*fdstore.the-listen-variables-are-omitted-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
[*fdstore.listen-pid-is-appended-by-the-child]; 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
[*fdstore.a-returned-listener-keeps-its-captured-identity]:
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.
[*fdstore.only-the-main-process-receives-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.
[*fdstore.a-failed-launch-does-not-clear-the-store]

## 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.
  [*fdstore.an-explicit-stop-clears-the-store] 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. [*fdstore.a-discarded-definition-clears-the-store]

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.
[*fdstore.the-store-survives-an-automatic-restart]

> [!NOTE]
> The `LISTEN_FDS` and `LISTEN_FDNAMES` convention is systemd's, so
> software already written to receive descriptors that way works
> unmodified. peinit's own C client library exposes the notification
> helpers but no descriptor-passing helper, so reaching the store from
> that library means constructing the control message by hand.

---

# 10.7 The Jobs Socket

_Peios / Reference / peinit / The Control Interface_

> The second socket — sequenced-packet, reachable by every authenticated principal — on which a job is submitted and managed, how peinit accepts and serves a connection, and how a wait is answered.

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
[*jobs.the-socket-is-sequenced-packet] 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.
[*jobs.the-listener-flags-and-backlog] After
binding, and before anything can connect, peinit stamps the socket
inode [*jobs.the-socket-descriptor]:

```text
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`
[*jobs.connecting-is-the-permission-to-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 [*jobs.the-peer-token-and-pidfd-are-captured-on-accept]:

| Key | Default | Meaning |
|---|---|---|
| `Machine\System\Init\MaxJobsConnections` | 64 | Concurrent connections. [*jobs.max-jobs-connections] |
| `Machine\System\Init\MaxJobMessageSize` | 32768 | Maximum message content, in bytes. Half of KMES `MaxEventSize`'s default, so a job whose record fills a message still has its `peinit.job.ended` fit the ring (§8.4). [*jobs.max-job-message-size] |
| `Machine\System\Init\JobsConnectionTimeout` | 30 | Seconds before an idle connection is closed. [*jobs.jobs-connection-timeout] |
| `Machine\System\Init\MaxJobsPerSubmitter` | 64 | Live jobs one submitter SID can hold; SYSTEM exempt. See §8.5. |

A connection over the limit, or one whose peer cannot be identified,
is closed at the socket level without a response.
[*jobs.an-inadmissible-connection-is-closed-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. [*jobs.closing-a-connection-does-not-affect-its-jobs]

## 10.7.4 Messages

Every message is received with room for one attached token and for 64
descriptors, the output sink included.
[*jobs.a-message-carries-one-token-and-up-to-sixty-four-descriptors] 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.
[*jobs.a-truncated-message-is-request-too-large]
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.
[*jobs.truncated-ancillary-data-is-invalid-arguments] Every
descriptor a message carried that is not handed to a job or adopted as
a sink is closed, on every path.
[*jobs.every-unused-descriptor-is-closed]

A response is one compact JSON object, no terminator.
[*jobs.a-response-is-one-compact-json-object] 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. [*jobs.a-submit-answer-carries-the-jobs-pidfd]

Only `REQUEST_TOO_LARGE` closes the connection after an error. Every
other error is answered and the connection kept.
[*jobs.only-request-too-large-closes-the-connection]

## 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.
<!-- lint-disable-next-line spelling -->
[*jobs.pipelined-messages-serialise-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. [*jobs.the-submit-wait] |
| Wait | `wait` | The condition holds — terminal, or ready-or-terminal. [*jobs.the-wait-wait] |
| Stop | `stop` with `wait` | The job is terminal. [*jobs.the-stop-wait] |

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.
[*jobs.waits-are-flushed-when-a-jobs-state-moves]
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.
[*jobs.an-unbuildable-answer-does-not-abort-the-flush]

A connection with a pending wait, or with a response still queued, is
not idle and is never closed by `JobsConnectionTimeout`.
[*jobs.a-connection-with-a-pending-wait-is-never-idle] 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).
[*jobs.every-command-but-submit-is-checked-against-the-jobs-descriptor]

## 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. [*jobs.an-idle-connection-is-closed] During shutdown the socket
stays open: `submit` is refused
with `INVALID_STATE`, and the other four commands keep answering
(§12.2). [*jobs.submit-is-refused-during-shutdown]

## 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_

> What `boot` reports about the current boot — its mode and why, the boot attempt count, and whether the boot has counted as a success — and where peinit gets each answer.

`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.
[*control.boot.reports-the-current-boot]

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). [*control.boot.is-checked-for-query-status]

## 10.8.1 Mode and reason

`mode` is the mode Phase 2 booted in, after any downgrade: `full` or
`safe` (§2.6). [*control.boot.mode-is-the-mode-phase-2-booted-in] 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`. [*control.boot.recovery-is-never-answered]

`reason` says why.
[*control.boot.reason-distinguishes-normal-requested-and-downgraded]

| `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. [*control.boot.downgrade-lists-every-finding]
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.
[*control.boot.attempts-is-the-count-phase-1-checked] 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.
[*control.boot.max-attempts-is-the-threshold]

## 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. [*control.boot.confirmation-states]

| `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.
[*control.boot.confirmed-means-the-counter-was-reset] 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.
[*control.boot.a-confirmed-boot-stays-confirmed]

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_

> Control-socket JSON framing, service and timer status fields, job views and short-lived operation results.

These examples connect the [svctl operator
guide](/peios/using-peios/services-and-jobs/controlling-services.md) 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:

```json
{"command": "start", "service": "jellyfin", "wait": true}
{"status": "ok", "operation_id": "a1b2c3d4-...", "service": "jellyfin", "state": "active", "cause": "explicit_start", "warnings": []}
```

Two properties are worth knowing even if you only ever use `svctl`:

- **Every command is access-controlled.** By default, anyone who is signed in
  can connect. When you connect, peinit captures your
  [token](/peios/using-peios/services-and-jobs/identity-and-privileges.md) from the kernel
  and runs [AccessCheck](/kernel/internals/kacs/access-check/the-dacl-walk.md) 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](/peios/using-peios/services-and-jobs/who-can-manage-a-service.md).
- **Lifecycle commands create
  [operations](/peios/using-peios/services-and-jobs/jobs-and-operations.md).** A `start`
  /`stop`/`restart`/`reload`/`reset` returns an `operation_id` — a GUID you
  can poll. Conflict resolution between concurrent commands happens at the
  operation layer, which is why two simultaneous `start` s merge instead of
  colliding.

## 10.9.2 Reading status

`status` returns the full picture for one service:

```json
{
    "status": "ok",
    "service": "jellyfin",
    "display_name": "Jellyfin",
    "description": "Media server for the living room.",
    "state": "active",
    "cause": "explicit_start",
    "status_text": "Listening on port 8096",
    "progress": null,
    "current_job": {"id": "a1b2...", "type": "service_main", "pid": 1234, "started_at": "...", "identity": "jellyfin-svc"},
    "current_operation": {"id": "e5f6...", "type": "start", "source": "admin"},
    "health": "healthy",
    "uptime_seconds": 86400,
    "definition_removed": false,
    "warnings": [],
    "timers": [],
    "granted": ["query_status", "start", "stop", "interrogate"]
}
```

- `display_name` and `description` are the definition's, or `null`.
- `state` and `cause` are the
  [lifecycle](/peios/using-peios/services-and-jobs/the-service-lifecycle.md) pair — read them
  together.
- `status_text` is the latest `STATUS=` string the service sent through
  sd_notify (`null` if never sent; cleared on each restart).
- `progress` is how far the service last said it had got, from `PROGRESS=` and
  `PROGRESS_UNIT=`:
  `{"current": 3, "total": 10, "bounded": true, "unit": "items"}`, with
  `total` and `unit` `null` when it didn't say them. `null` if it never sent
  one; cleared on each restart.
- `current_job` and `current_operation` are the [job and
  operation](/peios/using-peios/services-and-jobs/jobs-and-operations.md) GUIDs, or `null`.
- `health` is `healthy`, `unhealthy`, `unknown`, or `null` (no health
  check).
- `definition_removed` is `true` when the definition was deleted but an
  instance is still [draining](/peios/using-peios/services-and-jobs/defining-a-service.md).
- `warnings` lists leaked sub-cgroups and other operator-relevant notices.
- `timers` has one entry for each [timer
  trigger](/peios/using-peios/services-and-jobs/triggers-and-timers.md), described below.
- `granted` is what **you** can do to this service, as peinit checks it: the
  rights the service's
  [permissions](/peios/using-peios/services-and-jobs/who-can-manage-a-service.md) give you,
  out of `query_status`, `start`, `stop` and `interrogate` (reload). A
  program shows a control only where its right is listed, rather than offering
  one that will be refused.

Each entry in `timers` describes one schedule as peinit has it armed:

```json
{"schedule": "*-*-* 02:00:00",
 "scheduled_at": "2026-06-02T02:00:00.000000000Z",
 "fires_at": "2026-06-02T02:07:12.000000000Z",
 "last_fired_at": "2026-06-01T02:03:40.000000000Z",
 "not_armed": null}
```

- `scheduled_at` is the schedule's next occurrence.
- `fires_at` is when the timer will actually fire. It is later than
  `scheduled_at` by the random delay `TimerJitter` drew for this firing.
- `last_fired_at` is when it last fired, or `null` if it has not fired since
  peinit started and has no recorded run.
- `not_armed` is set only for a schedule peinit refused, such as one that
  never comes round. It gives the reason, and the times are then `null`.

Times are in UTC. `svctl status` prints them to the second:

```text
$ 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:

```json
{"status": "ok", "services": [
    {"service": "jellyfin", "state": "active", "cause": "explicit_start", "health": "healthy", "next_timer_at": null},
    {"service": "logrotate", "state": "inactive", "cause": "clean_exit", "health": null, "next_timer_at": "2026-06-02T02:07:12.000000000Z"}
]}
```

`next_timer_at` is the soonest `fires_at` of the service's timers.
`svctl list` shows it in a **NEXT TIMER** column.

`operation-status` returns one operation by GUID; an unknown or expired GUID
is the `UNKNOWN_OPERATION` error. (Operations are dropped after a short
retention grace once terminal — long enough for a polling client to read the
result, not forever.)

`job status` returns one submitted job's view under `"job"`, and `job list`
returns the views you can query under `"jobs"`:

```json
{"status": "ok", "job": {
    "id": "5f2a...", "type": "submitted", "state": "running", "cause": null,
    "submitter": "S-1-5-21-...-1001", "identity": "S-1-5-21-...-1001", "logon_session": 999,
    "description": "nightly backup", "image_path": "/usr/bin/backup", "pid": 4521, "ready": null,
    "exit_code": null, "exit_signal": null,
    "status_text": "Backing up /data/media", "progress": {"current": 3, "total": 5, "bounded": true, "unit": "items"},
    "created_at": "...", "started_at": "...", "ended_at": null
}}
```

The fields are explained in [Jobs and
operations](/peios/using-peios/services-and-jobs/jobs-and-operations.md). 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_

> The shared libpeinit interface, version reporting, handle ownership, and the distinction between transport errors and rejected commands.

`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 but it holds the pipes at birth — where a service's output goes, how it is tagged, and terminal-attached services.

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 [*output.a-service-gets-a-stdout-pipe-and-a-stderr-pipe]

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
[*output.the-blocking-discipline-is-asymmetric]:

- 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`.
[*output.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.
[*output.the-epoll-instance-is-never-inherited]

## 11.1.2 Tagging [*output.every-line-is-tagged]

peinit reads output line by line and tags each line with:

- the origin,
- the stream — stdout or stderr,
- a `CLOCK_REALTIME` timestamp,
- the job's identifier.

The origin is the service name for a main process. For a hook it is the
service name, the hook kind and its index — `jellyfin/ExecStartPre[0]`.
Reload commands are `<service>/ExecReload` and health checks
`<service>/HealthCheck`. A submitted job, which has no service, is
`jobs/<guid>`. [*output.the-origin-names-the-producer]

Health check output is captured, which is usually the only way to find
out why a health check failed. [*output.health-check-output-is-captured]

<!-- lint-disable-next-line line-length -->
## 11.1.3 The output sink [*output.a-submitted-jobs-output-is-recorded-unconditionally]

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. [*output.the-sink-receives-untagged-lines-in-order] 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. [*output.a-blocked-sink-write-drops-one-line-and-reports-once]
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.
[*output.the-sink-is-closed-when-the-pipes-are]

<!-- lint-disable-next-line line-length -->
## 11.1.4 Terminal-attached services [*output.a-terminal-attached-service-is-not-captured]

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**. [*output.the-terminal-is-opened-with-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_

> There is nowhere to send output until eventd binds its socket — what peinit buffers in memory, and why audit records are not logs.

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. [*buffer.output-before-eventd-is-held-in-memory] The
buffer is bounded, and drops the **oldest** entries when it fills.
[*buffer.the-buffer-drops-the-oldest-entries]

| Key | Default | Minimum | Meaning |
|---|---|---|---|
| `Machine\System\Init\PreEventdBuffer` | 1048576 | 4096 | Bytes of output retained before eventd exists. [*buffer.the-pre-eventd-buffer-key] |

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.
[*buffer.the-capacity-is-refreshed-on-reload] Lowering it takes effect
immediately, dropping the oldest entries until the contents fit — the
same end of the buffer a steady-state overrun drops.

Dropping the oldest rather than the newest is the right way round for
this buffer: the point of the window is the boot that is happening now,
and the most recent output is what explains where it got to.

> [!NOTE]
> In practice the only services that run before eventd are registryd,
> lpsd, authd and eudev. The first three are Peios-owned with controlled
> output. eudev is the real overrun risk, being verbose about device
> enumeration. A crash loop's output is bounded by the restart budget.

<!-- lint-disable-next-line line-length -->
## 11.2.1 Audit records are not logs [*buffer.audit-records-go-to-kmes-not-the-buffer]

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.
[*buffer.eventd-collects-earlier-events-when-it-attaches]

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_

> The three bounds that stop a noisy service starving the event loop, and where loss is allowed and where it is not.

A noisy service cannot be allowed to starve the event loop. Three bounds
apply.

| Key | Default | Minimum | Meaning |
|---|---|---|---|
| `Machine\System\Init\MaxLogLineLength` | 8192 | 256 | Bytes per line before truncation. [*flood.the-max-log-line-length-key] |
| `Machine\System\Init\MaxLogBufferPerService` | 65536 | 4096 | Bytes buffered per service pipe before backpressure. [*flood.the-max-log-buffer-per-service-key] |
| `Machine\System\Init\LogReadBytesPerEvent` | 16384 | 512 | Bytes drained from one pipe per readable event. [*flood.the-log-read-bytes-per-event-key] |

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.
[*flood.a-below-minimum-value-keeps-the-default-and-warns] 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.
[*flood.an-overlong-line-is-truncated-to-exactly-the-limit] Everything
up to the next newline is then suppressed rather than emitted as a
second line. [*flood.the-remainder-of-a-truncated-line-is-suppressed]

`MaxLogBufferPerService` is applied as the pipe's own capacity through
`F_SETPIPE_SZ` [*flood.the-per-service-bound-is-the-pipes-own-capacity],
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. [*flood.the-read-budget-bounds-one-readable-event] A turn
with several ready pipes reads up to the budget from each, bounded
overall by how many events one epoll wait returns.

<!-- lint-disable-next-line line-length -->
## 11.3.1 Where loss is allowed and where it is not [*flood.nothing-is-dropped-at-the-pipe]

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.
[*flood.delivery-downstream-of-the-pipe-is-loss-tolerant]

Audit events are exempt from all of it. They go through KMES.

## 11.3.2 Event loop fairness [*flood.signals-are-handled-at-the-highest-priority]

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
[*flood.the-power-button-shares-the-top-priority], 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_

> Switching from buffering to forwarding when eventd reaches Active — the record format, lossy delivery, and what happens when eventd goes away.

When eventd reaches Active, peinit switches from buffering to
forwarding. [*eventd.forwarding-begins-when-eventd-reaches-active]

1. Start sending to eventd's log datagram socket, at the path from
   `Machine\System\eventd\LogSocketPath`.
   [*eventd.the-socket-path-comes-from-the-registry]
2. Replay the pre-eventd buffer, oldest first, preserving each line's
   timestamp and metadata. [*eventd.the-buffer-is-replayed-oldest-first]
   The replay is best-effort: these are
   datagrams on a loss-tolerant socket, so some can be dropped, and
   peinit does not block waiting to deliver them.
3. Switch to real-time forwarding — new output sent as it arrives.
   [*eventd.new-output-is-forwarded-as-it-arrives]
4. Clear the buffer.

From there peinit is a relay: read from the pipes, tag each line,
forward. Audit events continue to flow as KMES events, entirely
separately.

<!-- lint-disable-next-line line-length -->
## 11.4.1 Broker authentication [*eventd.the-log-socket-denies-the-service-group-before-allowing-system]

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.
[*eventd.peinit-is-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.

<!-- lint-disable-next-line line-length -->
## 11.4.2 Datagram framing and the record [*eventd.a-datagram-holds-a-msgpack-array-of-records]

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.
[*eventd.a-batch-is-the-largest-prefix-fitting-the-portable-ceiling] 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. [*eventd.a-failed-datagram-advances-the-replay-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 [*eventd.the-record-fields]:

| 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. [*eventd.the-job-id-is-omitted-when-there-is-none]

PSPU §3.7
requires PCDS GUID layout:
Data1, Data2, and Data3 are little-endian; the final eight bytes (Data4)
retain their byte order. The payload is still exactly 16 bytes.

> [!NOTE]
> [peinit 0.0.12
>
> source](https://github.com/peios/peinit/blob/0e20fef16f3c170d8fba0e3a169b617e7b4da3aa/src/logging/msgpack.rs#L69-L82)
> sends RFC-order UUID bytes instead. The PCDS layout above requires the
> [log job-ID encoding fix](https://github.com/peios/peinit/pull/1); check the
> installed peinit revision before relying on that encoding.

## 11.4.3 Lossy delivery [*eventd.the-log-socket-is-a-non-blocking-datagram-socket]

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. [*eventd.peinit-never-blocks-on-a-send]

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. [*eventd.one-socket-is-created-and-reused] When
eventd becomes inactive, the connection is
discarded so the next Active transition connects to the newly bound
socket. [*eventd.the-connection-is-discarded-when-eventd-goes-inactive]

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.
[*eventd.a-drop-leaves-the-connection-standing] 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.
[*eventd.a-drop-during-replay-waits-rather-than-loses]

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.
[*eventd.a-transport-failure-rebuffers-and-replays]

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 [*eventd.an-eventd-exit-re-enables-the-buffer]

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.
[*eventd.the-handoff-repeats-when-eventd-comes-back]

There is a log gap between eventd crashing and restarting, bounded by
the buffer size. [*eventd.the-gap-is-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 the console and never a service's output — the line format, the stage banner, severity, and the quiet setting.

peinit writes its own operational messages to `/dev/console`
[*console.peinit-writes-its-own-messages-to-the-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.
[*console.service-output-is-never-echoed] 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 [*console.a-line-is-a-tag-then-a-component-then-a-message]

Every line carries a fixed-width outcome tag, then the component name,
then the message:

```text
[      ] 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.

| Tag | Means |
|---|---|
| `[      ]` | Progress with no outcome yet. Holds the column while receding. [*console.the-blank-tag-is-progress-with-no-outcome] |
| `[  OK  ]` | It worked. [*console.the-ok-tag-means-it-worked] |
| `[ SKIP ]` | Deliberately not done. [*console.the-skip-tag-means-deliberately-not-done] |
| `[ WARN ]` | Wrong, but the boot continues. [*console.the-warn-tag-means-the-boot-continues] |
| `[FAILED]` | It did not work. [*console.the-failed-tag-means-it-did-not-work] |
| `[ CRIT ]` | The machine is about to be lost. [*console.the-crit-tag-means-the-machine-is-about-to-be-lost] |

An `[  OK  ]` line reads "mounted", never "mounting": the tag already
claims the outcome, so the verb has to agree with it.

### 11.5.1.1 Tag and severity are different axes

The tag is *presentation*. [Severity](#severity-and-quiet) 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.

<!-- lint-disable-next-line spelling -->
### 11.5.1.2 Color [*console.tags-are-coloured-with-sgr-escapes]

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`.**
<!-- lint-disable-next-line spelling -->
[*console.colour-is-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.
<!-- lint-disable-next-line spelling -->
[*console.colour-never-changes-the-layout]

### 11.5.1.3 The stage banner [*console.a-banner-precedes-phase-1]

Before Phase 1 does any work, peinit prints a banner naming the stage and
the boot mode:

```text
  ══════════════════════════════════════════════════════════════
   peinit · real root · PID 1 · Full boot                 v0.0.1
  ══════════════════════════════════════════════════════════════
```

It is punctuation rather than decoration.
[prelude](/peios/reference/peinit/boot/the-initramfs-contract.md)
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`. [*console.the-banner-names-the-mode-the-boot-starts-in]
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. [*console.a-later-downgrade-does-not-reprint-the-banner]

Naming the mode is why the kernel command line is read at the very top of
`run_init`, before any Phase 1 work.
[*console.the-command-line-is-read-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.
[*console.the-banner-carries-status-severity]

### 11.5.1.4 Who else writes to this console

The format is shared by **specification**, not by shared code. peinit,
[prelude](/peios/reference/peinit/boot/the-initramfs-contract.md) 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
[*console.autorun-output-is-relayed-under-the-scripts-file-name]:

```text
[      ] 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.
[*console.a-relayed-line-carries-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 `?`.
  [*console.a-control-character-in-a-relayed-line-becomes-a-question-mark]
- A line is cut at 512 characters.
  [*console.a-relayed-line-is-cut-at-512-characters]
- A producer is capped at 200 lines, with the remainder counted.
  [*console.a-producer-is-capped-at-200-relayed-lines]

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.
[*console.only-firmware-and-a-terminal-owner-write-outside-the-format]

## 11.5.2 Severity and quiet

Each message carries a severity, and `peios.quiet` (§2.6) decides what
that means:

- At `0`, everything is written.
- At `1`, the default, peinit stays out of a terminal held as the
  controlling terminal of a running service, except to announce loss of
  the system. Terminals are matched by device rather than by path, since
  `/dev/console` and `/dev/ttyS<n>` can be the same device; where the
  device cannot be determined peinit assumes the terminal is held.
- At `2`, ordinary progress is dropped everywhere while errors still
  get through.

Suppressed messages are discarded rather than buffered for later.

Shutdown progress carries ordinary status severity, so `peios.quiet=2`
suppresses it along with every other kind of progress.
[*console.shutdown-progress-carries-status-severity]

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
[*console.a-phase-1-registryd-failure-is-relayed-to-the-console]:

```text
[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.
[*console.on-a-normal-boot-registryds-output-goes-to-eventd-alone]

The drain is safe to run from PID 1 because the read ends are
non-blocking: a registryd that is alive and silent yields `EAGAIN` rather
than hanging the boot.

> [!NOTE]
> `peios.quiet` governs peinit only. What the **kernel** prints is
> governed separately by `loglevel`, which shipped images set to `4`. See
> [Boot and boot modes](/peios/using-peios/boot/boot-and-boot-modes.md).

---

# 11.6 Terminal Ownership

_Peios / Reference / peinit / Output Handling_

> A TTYPath has one owner at a time — how peinit picks it, what happens to the losers, and how a terminal is handed on when it comes free.

A `TTYPath` (§3.2) names a device that has exactly one owner at a time.
[*terminal.a-terminal-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.

<!-- lint-disable-next-line line-length spelling -->
## 11.6.1 Who is holding it [*terminal.a-service-holds-its-terminal-while-it-may-have-a-process-on-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.** [*terminal.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** [*terminal.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.

<!-- lint-disable-next-line line-length -->
## 11.6.2 Losing the terminal [*terminal.every-start-path-asks-first-whether-the-terminal-is-free]

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.
[*terminal.a-held-terminal-skips-the-start-with-ttyunavailable]

Skipped rather than Failed, because nothing is wrong. Nothing is written
to the console about it either [*terminal.a-terminal-skip-is-not-announced]
— 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.
[*terminal.the-terminal-check-precedes-conditions-and-asserts]

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 [*terminal.higher-tty-precedence-wins]

`TTYPrecedence` decides who wins when several services want the same
device at the same moment. Higher wins; equal precedence breaks on
service name [*terminal.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.
[*terminal.the-default-precedence-is-zero]

Precedence is consulted among *simultaneous* candidates only. A service
that already holds a terminal is never preempted by a higher-precedence
latecomer [*terminal.a-holder-is-never-preempted]: 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.
[*terminal.deferred-starts-are-dispatched-highest-precedence-first]
Handovers, below, pick one winner outright.

Within the Phase 2 boot plan the order is the dependency graph's, not
precedence's [*terminal.the-boot-plan-orders-by-the-graph-not-precedence]
— a boot-plan terminal service is being written over by
peinit's own progress output anyway, which is what `boot:settled`
exists to avoid.

<!-- lint-disable-next-line line-length -->
## 11.6.4 Handing it on [*terminal.a-tty-released-waiter-is-started-when-the-terminal-comes-free]

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
[*terminal.every-exit-from-a-holding-state-frees-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.
[*terminal.the-released-terminal-is-recorded-on-the-transition] 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.
[*terminal.one-winner-per-release] 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.**
  [*terminal.the-service-whose-exit-freed-the-terminal-is-not-offered-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.
  [*terminal.a-service-with-a-removed-definition-is-not-offered-it]

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.
[*terminal.the-handover-starts-the-waiter-as-an-explicit-start-would]

## 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_

> Capture, early buffering, flow control,  and eventd forwarding behind the operator log view.

These notes collect the output-flow explanation behind [finding service
logs](/peios/using-peios/services-and-jobs/output-and-logging.md). 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](/peios/using-peios/services-and-jobs/execution-environment.md).)
It reads output **line by line** and tags each line with:

- the **service name**,
- the **stream** (stdout or stderr),
- a **timestamp**,
- the **[job](/peios/using-peios/services-and-jobs/jobs-and-operations.md) 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](/peios/using-peios/services-and-jobs/jobs-and-operations.md)'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](/peios/using-peios/services-and-jobs/supervision.md) 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.** `LogReadBytesPerEvent` bounds the bytes
  drained from one pipe per readable event. A loop turn with several ready
  pipes can read up to that budget from each; see §11.3.
- **Back-pressure, not dropping.** If a service writes faster than peinit
  reads, the kernel pipe buffer fills and the service's own `write()` calls
  block. This is deliberate: the service slows down. While reading the pipe,
  peinit does **not** drop output — the no-silent-drop guarantee covers
  *reading the pipe*. It is only *downstream* (the pre-eventd buffer, and
  eventd's datagram socket) that delivery becomes lossy.

> [!NOTE]
> Signals are never starved. In every loop iteration, child reaping (SIGCHLD)
> and shutdown handling take priority over all other event sources, including
> log reading. A flood of service output can never delay peinit noticing that
> a service died or that the system is shutting down.

## 11.7.4 The eventd handoff

When eventd reaches Active, peinit switches from buffering to forwarding:

1. It begins sending to eventd's log datagram socket (path from
   `Machine\System\eventd\LogSocketPath`).
2. It **replays the pre-eventd buffer**, oldest first, preserving each line's
   timestamp and metadata. This replay is best-effort — the records are
   datagrams on a loss-tolerant socket and some can be dropped under load;
   peinit never blocks waiting to deliver them.
3. It switches to real-time forwarding — new output goes out as it arrives.
4. It clears the buffer.

From then on peinit is a pipe relay: read lines, tag them, and forward the
largest ordered batch that fits the smaller of the portable 262144-byte
ceiling and the log socket's send buffer. peinit does not read eventd's larger
local ceiling; see §11.4. It keeps one connected socket and reuses its
encoding buffer, so normal forwarding does not create a socket or output
allocation for every line. The log socket is **non-blocking and
loss-tolerant** — if eventd cannot drain it fast enough the kernel drops
further datagrams silently, because sign ingestion must never exert
back-pressure on the whole system through PID 1. peinit keeps no unbounded
outbound buffer and never blocks on a send to eventd.

If eventd itself crashes after starting, peinit (which supervises it like any
service) notices, **re-enables the pre-eventd buffer**, and repeats the
handoff when eventd comes back. There can be a log gap across the restart,
bounded by the output buffer. Structured events use the independent KMES ring;
eventd can resume reading the events that remain there. The ring can overwrite
old events and does not survive reboot, so eventd supplies persistence rather
than KMES. See [KMES failure
modes](/kernel/internals/kmes/failure-modes.md).

---

# 12.1 Triggers

_Peios / Reference / peinit / Shutdown_

> The four paths that initiate a shutdown — the control socket, signals, the power button,  and a Critical service failure.

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):
[*sdtrig.a-shutdown-command-names-poweroff-reboot-or-halt]

| 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 [*sdtrig.sigint-reboots-and-sigterm-and-sigpwr-power-off]

| 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.
[*sdtrig.three-sigints-in-five-seconds-force-an-immediate-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.
[*sdtrig.three-presses-force-even-after-a-graceful-shutdown-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`.
[*sdtrig.a-power-button-press-is-a-graceful-poweroff] Only a press —
value 1 — initiates. Releases, key repeats, other keys, and other event
types are ignored. [*sdtrig.only-a-key-press-initiates]

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.
[*sdtrig.the-power-button-path-is-fail-soft] 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.
[*sdtrig.a-critical-service-out-of-restart-budget-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_

> The ordered steps of a graceful shutdown, from entering the shutdown state to the final power action.

## 12.2.1 Step 1: Enter the shutdown state

peinit sets an internal flag. While it is set, no new service starts.
[*graceful.no-new-service-starts-once-the-flag-is-set] 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. [*graceful.every-live-submitted-job-is-stopped-at-once]
A job still queued for launch is canceled with the same
<!-- lint-disable-next-line spelling -->
cause. [*graceful.a-queued-job-is-cancelled-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`.
[*graceful.submit-is-refused-while-the-other-job-commands-keep-answering]

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.
[*graceful.a-timer-firing-during-shutdown-is-a-no-op]

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.
[*graceful.a-critical-failure-during-shutdown-does-not-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. [*graceful.completed-services-are-transitioned-to-inactive]

The rest are classified for stop eligibility:

- **Active and Reloading** are graceful-stop eligible and enter the
  waves. [*graceful.active-and-reloading-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.
  [*graceful.a-stopping-service-joins-the-waves-without-another-sigterm]
- **Starting** services are not eligible. peinit cancels the startup,
  SIGKILLs the service cgroup if one exists, and transitions them to
  Failed with cause `ShutdownWave` while post-kill verification is
  pending. [*graceful.a-starting-service-is-killed-and-failed]
  A cgroup still populated after the post-kill timeout takes
  the service to Abandoned with cause `ProcessUnkillable` and the cgroup
  is leaked.
  [*graceful.a-cgroup-that-survives-the-post-kill-timeout-is-abandoned]
  A Starting service whose job never forked skips the check
  and goes straight to Failed.
  [*graceful.an-unforked-starting-job-goes-straight-to-failed]
- **Inactive, Failed, Skipped, Backoff, and Abandoned** do not
  participate. [*graceful.five-states-do-not-participate]
  Abandoned cgroups stay leaked and shutdown continues.

<!-- lint-disable-next-line line-length -->
## 12.2.4 Step 4: Stop in reverse dependency order [*graceful.no-service-stops-until-its-dependents-have]

peinit builds the reverse dependency graph over hard dependencies and
stops in waves:
<!-- lint-disable-next-line line-length -->
[*graceful.each-eligible-service-gets-sigterm-then-a-cgroup-sigkill-at-stoptimeout]

1. Each eligible service receives SIGTERM. Already-stopping ones do not.
2. Each has `StopTimeout` to exit.
3. On expiry, SIGKILL to the service's entire cgroup.
4. No service is stopped until everything depending on it has stopped.

The compiled-in Phase 1 service, registryd, stops in a wave of its own
after every other participant, though no definition declares a
dependency on it. [*graceful.registryd-stops-after-every-other-service]
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.
[*graceful.a-participant-gone-from-the-table-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. [*graceful.a-service-that-sent-stopping-gets-no-sigterm]
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.
[*graceful.shutdown-stop-observations-follow-the-waves]

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.
[*graceful.an-already-stopping-services-clock-is-not-reset] It uses the
timing evidence retained from the stop path that put the service in
Stopping:

- If a Stop operation, or a Restart executing its stop leg, is in
  flight, that operation's retained timing governs.
- Otherwise peinit uses service-level evidence, which carries the cause
  that initiated the transition — `ExplicitStop`, `ShutdownWave`,
  `ConflictEviction`, or `BindsToPropagation`.

peinit requires the evidence to be present, to belong to a service
actually in Stopping, to carry a cause matching the service's current
cause, to name one of those four causes, and not to describe a deadline
earlier than its own start.
[*graceful.the-retained-evidence-must-meet-five-conditions]

Evidence that is missing, stale, or ambiguous **fails closed** rather
than being guessed at. [*graceful.unsubstantiable-evidence-fails-closed]
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.
[*graceful.failing-closed-costs-only-that-participant] 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:
[*graceful.an-unsubstantiated-deadline-kills-without-a-graceful-period]

```text
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.
[*graceful.a-pending-operations-expiry-does-not-signal-the-service-early]
Shutdown owns the signaling; the operation object is
an observation of it.

<!-- lint-disable-next-line line-length -->
## 12.2.5 Step 5: Global timeout [*graceful.shutdowntimeout-and-postkilltimeout-bound-the-sequence]

| 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.
[*graceful.on-the-global-timeout-everything-remaining-is-killed]
Live submitted jobs
are killed in the same sweep, whatever phase their stop had reached,
and abandoned on the same terms.
[*graceful.the-global-timeout-sweep-kills-live-jobs-too]

The global timeout fires once. [*graceful.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.
[*graceful.the-console-names-what-the-global-timeout-waited-for]

```text
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.
[*graceful.step-6-waits-for-every-live-submitted-job] 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. [*graceful.a-512-byte-seed-is-written-before-any-unmount]

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.
[*graceful.the-seed-write-is-a-flush-and-atomic-rename] 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 [*graceful.every-non-root-mount-is-unmounted-deepest-first]

1. Snapshot the mount table first, from `/proc/self/mountinfo`.
2. Attempt to unmount every remaining non-root mount in the namespace —
   not only what peinit mounted, so the Phase 1 set is covered by
   construction.
3. Process in descending path depth, so children go before parents.
4. A mount point already gone is a successful no-op.
   [*graceful.a-mount-point-already-gone-is-a-no-op]
5. On failure, attempt a read-only remount. If that fails too, record it
   and continue.
   [*graceful.a-failed-unmount-falls-back-to-a-read-only-remount]
6. The root is never unmounted, but is remounted read-only at the end.
   [*graceful.the-root-is-remounted-read-only-never-unmounted] A
   failure there is recorded and does not stop step 8.

## 12.2.8 Step 8: Sync and the final action

This step is irreversible. Cleanup failures retained from steps 6 and 7
affect diagnostics only and never block it.

1. `sync()`. Called on all three paths — graceful, forced, and
   Critical reboot. [*graceful.sync-is-called-on-all-three-paths]
2. `reboot(2)` with `RB_POWER_OFF`, `RB_AUTOBOOT`, or `RB_HALT_SYSTEM`.
   [*graceful.the-final-action-is-reboot2-with-the-kinds-command]
3. If `reboot(2)` returns, the final action failed. peinit enters a
   minimal failed-shutdown state, keeps PID 1 alive, records the
   failure, and retries the same action no more than once a second. It
   does not restart services and does not enter recovery mode —
   finalization has begun and there is nothing to go back to.

## 12.2.9 Shutdown during boot

A shutdown requested while Phase 2 is still running takes effect
immediately, through the same classification: Starting services are
SIGKILLed, services that reached Active are stopped gracefully, and the
boot is abandoned.
[*graceful.a-shutdown-during-phase-2-takes-effect-immediately]

---

# 12.3 Signals

_Peios / Reference / peinit / Shutdown_

> Every signal is blocked and read through a signalfd from the event loop — the setup, the signals handled, and reaping.

PID 1 handles every signal through a signalfd. All signals are blocked
and read from the event loop.
[*signal.every-signal-is-blocked-and-read-through-a-signalfd] So peinit
installs no signal handlers of its own, and nothing peinit writes has to
be async-signal-safe.
[*signal.peinit-installs-no-signal-handlers-of-its-own]

`/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. [*signal.the-two-caught-signals-are-the-runtimes-guard]

## 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. [*signal.the-mask-is-every-blockable-signal] It then creates the
descriptor with `signalfd4(-1, mask, ...)`,
using the same mask, with `SFD_CLOEXEC | SFD_NONBLOCK`.
[*signal.the-signalfd-carries-the-same-mask-and-is-cloexec-nonblocking]

If any part of that fails — blocking, creating the descriptor,
retaining it, registering it with the event loop — peinit fails closed.
[*signal.a-signalfd-setup-failure-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.sighup-and-sigpipe-are-ignored]

| 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.
[*signal.every-other-signal-is-ignored-and-none-can-kill-pid-1]

## 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:
<!-- lint-disable-next-line spelling -->
[*signal.the-wait-status-is-normalised-before-policy-sees-it]

- An exited child carries its exact exit code, 0–255.
  [*signal.an-exited-child-carries-its-exact-exit-code]
- A signaled child carries the terminating signal number and whether
  the core-dump bit was set.
<!-- lint-disable-next-line spelling -->
  [*signal.a-signalled-child-carries-the-signal-and-the-core-dump-bit]
- A stopped or continued status is invalid on this path, because peinit
  never asks for them. Observing one **fails closed** rather than being
  interpreted. [*signal.a-stopped-or-continued-status-fails-closed]

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.
[*signal.orphans-reparented-to-pid-1-are-reaped-as-untracked]

---

# 12.4 Finalization

_Peios / Reference / peinit / Shutdown_

> The three shutdown paths that reach the kernel and how much work each does on the way, including what survives a failure.

Three shutdown paths reach the kernel, and they do different amounts of
work on the way. [*final.the-three-paths-do-different-amounts-of-work]

| 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.
[*final.the-abrupt-paths-skip-the-seed-and-the-unmounts] 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.
[*final.a-cleanup-failure-never-blocks-the-final-action] 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:
[*final.a-returning-final-action-enters-a-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.
  [*final.the-failed-action-is-retried-at-most-once-a-second]
- Services are not restarted, and recovery mode is not entered.
  [*final.a-failed-final-action-does-not-restart-services-or-enter-recovery]

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.
[*final.rb-halt-system-does-not-return-either]

## 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. [*final.proc-is-unmounted-before-run-and-sys]
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_

> The two boundaries peinit sits at — the kernel handing it a SYSTEM token, and peinit handing identity to services.

peinit sits at two.

## 13.1.1 Kernel to peinit [*trust.the-kernel-hands-peinit-the-system-token]

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
[*trust.descriptor-enforcement-has-no-bypass], 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, and the much narrower set it actually exercises.

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
[*privilege.the-required-privileges-are-verified-at-startup]:

```text
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. [*privilege.se-impersonate-is-not-required] peinit
passes the peer's token descriptor to AccessCheck directly rather than
impersonating the caller and evaluating as them, so the privilege that
would be needed to impersonate is not needed at all. The same holds on
the jobs socket: peinit never impersonates a submitter, and the identity
a job runs as is one the kernel already verified the submitter could
convey.

For non-platform services peinit creates no tokens. It installs the ones
authd minted. It mints only for the SYSTEM platform services it starts
during bootstrap, before authd is available.

> [!NOTE]
> Minting is interim. The intended model derives a service's token from
> peinit's own handle through a KACS duplicate-with-additions operation
> — kernel-attested as a descendant of peinit's real token, and needing
> no minting privilege. That would let peinit drop
> `SeCreateTokenPrivilege` entirely, which is the point: the privilege
> to mint arbitrary tokens is the strongest thing peinit holds and the
> one it has the least use for.

---

# 13.3 The Attack Surface

_Peios / Reference / peinit / Security_

> What the socket descriptors mean in practice, and what the autorun directory exposes.

| 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.
[*surface.a-refused-connect-never-reaches-peinit]

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_

> The properties peinit does not violate, and the code paths that make each of them structural.

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.** [*invariant.the-descriptors-are-the-only-policy-inputs]
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.
[*invariant.peinit-never-installs-a-token-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 the same way again — what losing it does in each phase and at runtime.

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.
[*lostreg.a-phase-1-registryd-failure-still-increments-the-counter]

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.
[*lostreg.registryd-going-away-does-not-stop-supervision] Services keep
running, restarts keep working, the control socket keeps answering, and
timers keep firing.
[*lostreg.services-restarts-and-timers-keep-working-without-registryd]

What stops working is anything that needs new configuration:
reload-config fails. [*lostreg.reload-config-fails-without-registryd]
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.
[*lostreg.a-timer-last-run-timestamp-cannot-be-written-without-registryd]

registryd itself is a Critical service
[*lostreg.registryd-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_

> What breaks when authd or eventd is unavailable, and what a bound dependency that never becomes satisfying does.

## 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 [*lostdep.authd-is-a-critical-service], 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.
[*lostdep.eventd-is-a-critical-service] 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.
[*lostdep.a-blocked-dependent-fails-when-its-operation-lifetime-expires]
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
[*lostdep.the-start-timeout-runs-from-when-the-operation-was-created] —
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 sleep ignores SIGKILL — what Abandoned means, and the generational escape that lets peinit move on.

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.
[*unkillable.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
[*unkillable.the-stop-that-gave-up-stays-failed], and the console
reports the exit:

```text
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_

> Descriptors, processes, memory,  and disk running out — how each reaches single-threaded PID 1, and what the OOM killer does.

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.
[*exhaust.the-descriptors-peinit-holds] 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.
<!-- lint-disable-next-line line-length -->
[*exhaust.a-descriptor-exhaustion-at-launch-is-a-restart-eligible-parentsetupfailure]

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.
[*exhaust.a-filesystem-condition-leaks-no-descriptors]

## 14.4.2 Processes

`EAGAIN` from `clone3` — the PID limit — is also `ParentSetupFailure`
and restart-eligible.
[*exhaust.a-pid-limit-at-launch-is-a-restart-eligible-parentsetupfailure]

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).
[*exhaust.the-timer-last-run-write-is-the-only-fork-outside-the-launch-path]
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.
<!-- lint-disable-next-line line-length -->
[*exhaust.a-memory-exhaustion-at-launch-is-a-restart-eligible-parentsetupfailure]

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.
[*exhaust.graph-execution-contexts-are-retired] 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.
[*exhaust.an-onfailure-chain-entry-is-cleared-once-the-handler-holds]

## 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.
<!-- lint-disable-next-line line-length -->
[*exhaust.an-unsaveable-random-seed-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_

> The three things peinit writes and how each is made to survive a power loss — plus damaged files, timers, and an interrupted shutdown.

## 14.5.1 What peinit writes

Three things, and all three are written to survive an unexpected loss of
power: [*powerloss.the-three-things-peinit-writes]

| 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.
[*powerloss.the-seed-and-the-machine-id-are-never-seen-half-written]

## 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.
[*powerloss.no-service-state-is-written-to-the-registry] 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).
[*powerloss.the-last-run-timestamp-is-written-when-the-start-is-initiated]
A power loss mid-run therefore does not re-trigger on the next boot — the
run was attempted, not missed.
[*powerloss.a-power-loss-mid-run-does-not-re-trigger]

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. [*powerloss.a-power-loss-before-the-write-does-re-trigger]

## 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.
[*powerloss.after-step-7-the-root-is-read-only-and-nothing-is-outstanding]

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.
[*powerloss.only-a-boot-that-never-succeeded-leaves-the-counter-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 — service definitions, boot configuration, operational parameters,  and the watches it holds.

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_

> Every value compiled into peinit that no registry key changes — paths, timeouts, limits, environment,  and the descriptors it applies.

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 is the local registry source; it holds hives in SQLite and serves them to the kernel over RSI. Where it sits, and what this manual covers.

**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).
[*overview.loregd-holds-hives-in-sqlite-and-serves-them-over-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.
[*overview.any-process-implementing-rsi-can-be-a-registry-source]

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.
[*overview.loregd-provides-the-machine-and-users-hives-at-boot]

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`.
[*overview.the-loregd-package-installs-the-daemon-and-its-role-provider]

peinit owns the compiled-in Phase-1 service definition, so loregd does not
ship a second service seed that could compete with it.
[*overview.loregd-ships-no-service-seed-of-its-own]

## 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.
[*overview.the-registry-is-split-across-a-trust-boundary]
 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.
[*overview.loregd-stores-it-does-not-decide]
- **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.
[*overview.guids-come-from-the-kernel]
- **Sequence numbers come from the kernel.** loregd stores them and
  reports the maximum it holds at registration, but never allocates one.
[*overview.sequence-numbers-come-from-the-kernel]

## 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](/kernel/internals/lcs/start-here/overview.md)
describes namespaces, layers, watches, and access control. The
[kernel source interface](/kernel/internals/lcs/sources/overview.md) 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 vocabulary this manual borrows from the kernel-side documentation, and the terms loregd adds.

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.
[*term.each-hive-has-its-own-database-file]

**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).
[*term.the-volatile-database-is-transient-tmpfs-storage]

**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).
[*term.a-folded-name-is-used-for-all-case-insensitive-comparison]

**Write connection.** The single SQLite connection per hive through which
every mutation passes. Its uniqueness is what serializes writes (§4.1).
[*term.every-mutation-passes-through-the-single-write-connection]

**Read pool.** The fixed set of connections serving reads that are not
part of a transaction, selected round-robin (§4.1).
[*term.the-read-pool-serves-non-transactional-reads-round-robin]

**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).
[*term.a-snapshot-connection-pins-a-point-in-time-view]

**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).
[*term.an-orphan-is-a-key-record-no-path-entry-points-at]

---

# 2.1 Command Line

_Peios / Reference / loregd / Startup_

> loregd is configured entirely by its argument vector; the hive declarations it takes, and how they are validated.

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:
[*cmdline.an-argument-declares-a-hive-and-the-database-that-backs-it]

```text
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 `=`.
[*cmdline.an-argument-is-split-at-its-first-equals-sign]

Every declared hive is registered with the kernel at startup (§2.2).
[*cmdline.every-declared-hive-is-registered-with-the-kernel]

## 2.1.1 Argument validation
[*cmdline.an-invalid-invocation-is-rejected-with-a-non-zero-exit]

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

[*cmdline.at-least-one-hive-argument-is-required]
[*cmdline.an-argument-without-an-equals-sign-is-rejected]
[*cmdline.an-empty-hive-name-or-path-is-rejected]
[*cmdline.a-database-path-must-be-absolute]
<!-- lint-disable-next-line spelling -->
[*cmdline.a-hive-name-may-not-contain-a-separator-or-nul]
[*cmdline.the-hive-name-currentuser-is-reserved]
[*cmdline.duplicate-hive-names-are-detected-on-the-folded-name]


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.
[*cmdline.hive-name-comparison-is-case-insensitive-but-the-case-is-preserved]

## 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](/peios/reference/loregd/startup/startup-sequence.md#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.
[*cmdline.there-is-no-configuration-file-or-registry-configuration]
 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).
<!-- lint-disable-next-line spelling -->
[*cmdline.behaviour-comes-from-arguments-databases-and-compiled-in-constants]

`NOTIFY_SOCKET` is the one environment variable loregd consults, and it
carries no behavioral setting.
[*cmdline.notify-socket-is-the-only-environment-variable-consulted]
 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.
[*cmdline.readiness-is-sent-as-ready-equals-1-before-the-request-loop]
When it is unset, the step is skipped.
[*cmdline.readiness-is-skipped-when-notify-socket-is-unset]

loregd writes ordinary progress to standard output and faults to standard
error.
[*cmdline.progress-goes-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_

> Preparing databases, registering hives, and notifying the service manager before dispatch begins.

Startup runs to completion before loregd accepts a single request.
[*startup.startup-completes-before-any-request-is-accepted]
 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.
[*startup.any-startup-failure-is-fatal-and-exits-non-zero]

## 2.2.1 1. parse and validate arguments
[*startup.arguments-are-parsed-and-validated-first]

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
[*startup.each-declared-hives-database-is-opened-or-created]

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:

```text
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.
[*startup.missing-directories-receive-their-descriptor-at-creation]

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.
[*startup.existing-directories-are-preserved-and-other-types-are-rejected]

ppk packages contain only `/usr`. loregd needs its storage before it can
serve the registry, so it prepares these directories itself; registry-backed
path provisioning runs too late for this Phase 1 service.

Four pieces of connection state are established immediately:

- `PRAGMA journal_mode=wal`. The result is read back and checked; if the
  database does not report `wal`, the open fails.
[*startup.wal-mode-is-verified-and-the-open-fails-without-it]
 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.
[*startup.foreign-keys-are-enabled]
- `PRAGMA busy_timeout=0`; SQL lock conflicts return busy immediately (§4.4).
[*startup.the-busy-timeout-is-twenty-five-seconds]
- The volatile database is attached (§3.3).

Each `database/sql` handle is limited to a single underlying connection.
[*startup.each-sql-handle-is-limited-to-one-underlying-connection]

## 2.2.3 3. attach the volatile store
[*startup.the-volatile-store-is-attached-as-schema-volatile]

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.
[*startup.volatile-stores-are-fresh-and-use-tmpfs-wal]

## 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.
[*startup.a-new-database-gets-its-schema-created-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).
[*startup.a-schema-version-mismatch-in-either-direction-aborts-startup]

## 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.
[*startup.a-hive-with-no-parentless-key-gets-a-generated-root-key]

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.
[*startup.the-default-hive-root-descriptor]

## 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.
[*startup.wal-recovery-is-sqlites-own-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.
[*startup.an-orphaned-key-is-one-no-path-entry-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.
[*startup.orphaned-keys-are-deleted-values-then-tombstones-then-records]

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.
[*startup.orphan-detection-skips-keys-with-a-null-parent]

## 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.
[*startup.the-maximum-sequence-is-taken-across-every-table-and-every-hive]
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
[*startup.the-registry-device-is-opened-at-dev-pkm-registry]

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.
[*startup.the-kernel-not-loregd-enforces-setcbprivilege]

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.
[*startup.lifetime-protocol-is-negotiated-before-registration]

## 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.
<!-- lint-disable-next-line line-length -->
[*startup.registration-sends-every-hive-name-root-guid-and-the-maximum-sequence]
The registration flags are zero: loregd registers global hives only and
never private ones.
[*startup.the-registration-flags-are-zero-so-hives-are-global]

## 2.2.10 10. signal readiness and serve
[*startup.readiness-then-the-signal-handler-then-the-request-loop]

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](/kernel/internals/lcs/backup-and-restore/backup.md)
is a separate operation.

The [command-line interface](/peios/reference/loregd/startup/command-line.md#unsupported-recovery-switches)
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_

> What ends the loregd process, what pointedly does not, and what happens to the data in each case.

The daemon distinguishes process failures from errors returned for individual
requests.


## 2.3.1 What ends the process

loregd exits when any of the following happens:

- **The kernel closes the registry device.** Reading from
  `/dev/pkm_registry` returns end-of-file, the request loop returns, and
  loregd shuts down cleanly with status 0.
[*exit.device-eof-shuts-down-cleanly-with-status-zero]
 This is the
  normal path when the registry subsystem goes away.
- **A termination signal arrives.** `SIGTERM` and `SIGINT` are trapped.
  The handler closes the device, which unblocks the read loop and
  produces the same clean shutdown as above.
[*exit.sigterm-and-sigint-close-the-device-for-a-clean-shutdown]
 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.
[*exit.an-unframeable-request-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.
[*exit.a-startup-failure-is-fatal]

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.
[*exit.in-flight-requests-are-drained-and-every-connection-closed-on-shutdown]

## 2.3.2 What does not end the process
[*exit.a-storage-failure-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.
[*exit.sqlite-errors-become-an-rsi-storage-error-response]
 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.
[*exit.there-is-no-corruption-or-disk-full-detector]

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.
<!-- lint-disable-next-line spelling -->
[*exit.committed-data-is-durable-and-wal-state-is-finalised-at-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).
[*exit.volatile-data-does-not-survive-the-process]

When the kernel observes the source disconnect, it marks every hive
loregd served as unavailable.
[*exit.the-kernel-marks-every-served-hive-unavailable-on-disconnect]

---

# 3.1 Schema Version

_Peios / Reference / loregd / Storage_

> The single-row table every hive database carries, the current version, and how a version mismatch is handled.

Every hive database carries a schema version in a single-row table
[*schema.every-hive-database-carries-a-schema-version]
:

```sql
CREATE TABLE schema_version (
    version INTEGER NOT NULL
);
```

The supported schema version is 1.
[*schema.the-current-version-is-one]

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

[*schema.a-new-database-is-created-and-stamped-in-one-transaction]
[*schema.version-one-starts-normally]
[*schema.a-newer-version-fails-startup]
[*schema.a-version-below-one-fails-startup]


**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.
[*schema.there-are-no-migrations]
 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.
[*schema.a-second-version-row-is-not-detected]

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.
[*schema.a-database-without-a-version-table-is-stamped-unvalidated]

---

# 3.2 Persistent Tables

_Peios / Reference / loregd / Storage_

> The four data tables every hive database has; keys, path entries, values, and blanket tombstones; and their columns.

Each hive is one SQLite database, and every hive database has the same
four data tables.
[*tables.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.
[*tables.no-table-records-a-derived-view-of-kernel-data]

## 3.2.1 `keys`
[*tables.the-keys-table]

```sql
CREATE TABLE keys (
    guid           BLOB NOT NULL PRIMARY KEY,
    name           TEXT NOT NULL,
    name_folded    TEXT NOT NULL,
    parent_guid    BLOB,
    sd             BLOB NOT NULL,
    volatile       INTEGER NOT NULL DEFAULT 0,
    symlink        INTEGER NOT NULL DEFAULT 0,
    last_write_time INTEGER NOT NULL
);
```

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

[*tables.a-key-name-is-stored-with-its-case-preserved]
[*tables.the-hive-root-is-the-key-with-a-null-parent]
[*tables.the-persistent-keys-table-always-stores-volatile-zero]


## 3.2.2 path_entries
[*tables.the-path-entries-table]

```sql
CREATE TABLE path_entries (
    parent_guid       BLOB NOT NULL,
    child_name        TEXT NOT NULL,
    child_name_folded TEXT NOT NULL,
    layer             TEXT NOT NULL,
    target_type       INTEGER NOT NULL,
    target_guid       BLOB,
    sequence          INTEGER NOT NULL,
    PRIMARY KEY (parent_guid, child_name_folded, layer)
);

CREATE INDEX idx_path_entries_target
    ON path_entries (target_guid)
    WHERE target_type = 0;
```

A path entry is one layer's opinion about one child name under one
parent.
[*tables.a-path-entry-is-one-layers-opinion-about-one-child-name]
Several layers can hold entries for the same name; resolving between them
is the kernel's job, not loregd's.
[*tables.loregd-does-not-resolve-between-layers]

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

[*tables.a-child-name-collides-case-insensitively-within-a-layer]
[*tables.layer-names-are-compared-as-binary]
[*tables.target-type-one-is-a-hidden-tombstone]


The partial index on `target_guid` covers only non-HIDDEN rows.
[*tables.the-target-guid-index-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`
[*tables.the-values-table]

```sql
CREATE TABLE [values] (
    key_guid       BLOB NOT NULL,
    name           TEXT NOT NULL,
    name_folded    TEXT NOT NULL,
    layer          TEXT NOT NULL,
    type           INTEGER NOT NULL,
    data           BLOB,
    sequence       INTEGER NOT NULL,
    PRIMARY KEY (key_guid, name_folded, layer)
);
```

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

[*tables.the-empty-value-name-is-the-keys-default-value]
[*tables.reg-tombstone-marks-a-per-value-tombstone]


`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
[*tables.the-blanket-tombstones-table]

```sql
CREATE TABLE blanket_tombstones (
    key_guid       BLOB NOT NULL,
    layer          TEXT NOT NULL,
    sequence       INTEGER NOT NULL,
    PRIMARY KEY (key_guid, layer)
);
```

A blanket tombstone hides every value a key holds in the layers beneath
it, rather than naming one value the way a `REG_TOMBSTONE` entry does.
One row per key per layer.

---

# 3.3 The Volatile Store

_Peios / Reference / loregd / Storage_

> Volatile keys never reach the hive file, so each hive attaches a second tmpfs-backed WAL database mirroring the persistent schema.

Volatile keys never reach the persistent hive file.
[*volatile.volatile-keys-never-reach-the-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>/`.
[*volatile.each-hive-gets-a-private-tmpfs-wal-database]

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.
[*volatile.runtime-storage-is-protected-and-exclusively-owned]

## 3.3.1 A mirror of the persistent schema
[*volatile.the-schema-mirrors-the-persistent-one]

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.
[*volatile.the-volatile-column-defaults-to-one]
 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:

```sql
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.a-transaction-across-both-stores-commits-or-rolls-back-as-one-unit]

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.
[*volatile.volatile-writes-are-invisible-until-commit-and-vanish-on-rollback]

## 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.
[*volatile.connections-share-only-their-hives-store]

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.
[*volatile.crash-residue-is-removed-before-fresh-stores-are-created]
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.
[*volatile.the-volatile-tables-are-always-empty-at-startup]

## 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.
[*volatile.a-single-key-operation-follows-the-keys-own-store]

`RSI_CREATE_KEY` is the exception, because the key does not exist yet
the volatile flag in the request decides which database receives it.
[*volatile.create-key-is-routed-by-the-requests-volatile-flag]

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.
[*volatile.lookup-and-enum-children-consult-both-stores]
 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.
[*volatile.a-volatile-keys-whole-subtree-is-volatile]

---

# 3.4 Case Folding

_Peios / Reference / loregd / Storage_

> Names are case-insensitive but case-preserving, implemented by storing both the written form and a folded one.

Key names and value names are case-insensitive but case-preserving.
[*fold.key-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.
[*fold.both-the-written-and-folded-forms-are-stored]

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.
[*fold.the-folded-form-is-computed-once-and-is-what-every-comparison-uses]
Lookups are therefore plain binary comparisons
[*fold.lookups-are-plain-binary-comparisons]
:

```sql
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.
[*fold.no-custom-sqlite-collation-is-registered]

The canonical name is what comes back in responses, so callers see the
case they originally supplied while storage compares the folded form.
[*fold.responses-return-the-case-the-caller-supplied]

Hive names are folded too, though not stored
[*fold.hive-names-are-folded-but-never-stored]
: routing a request to a
hive and rejecting duplicate hive declarations (§2.1) both compare folded
names.
[*fold.hive-routing-and-duplicate-rejection-compare-folded-names]

Layer names are **not** folded. They are compared as binary, so layer
names are case-sensitive.
[*fold.layer-names-are-not-folded]

## 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.
[*fold.folding-is-unicode-simple-case-folding-status-c-and-s]
 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.
[*fold.loregd-must-fold-byte-identically-to-the-kernel]

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.
[*fold.the-fold-is-not-derived-from-the-go-standard-library]
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.
[*fold.the-table-is-generated-by-the-kernels-own-generator]
 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.
[*fold.columns-written-before-september-2026-used-lowercasing]

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; what each carries, and which one an operation runs on.

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

[*conn.every-mutation-runs-on-the-hives-single-write-connection]
[*conn.reads-outside-a-transaction-use-the-round-robin-read-pool]
[*conn.each-read-only-transaction-gets-its-own-snapshot-connection]


The pool size is compiled in and cannot be configured; loregd reads no
configuration (§2.1).
[*conn.the-pool-size-is-compiled-in-and-cannot-be-configured]

## 4.1.1 One connection per handle
[*conn.every-handle-is-limited-to-one-underlying-connection]

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).
<!-- lint-disable-next-line line-length -->
[*conn.a-second-writer-declines-while-a-transaction-holds-the-write-connection]

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.
[*conn.a-snapshot-connection-never-consumes-a-read-pool-slot]

## 4.1.2 What every connection carries
[*conn.connection-state-is-established-once-when-the-connection-is-opened]

Connection state is established on **every physical connection**, including
one that replaces a connection discarded after cancellation:

- `journal_mode=wal` on both databases, verified after being set.
- `foreign_keys=ON`.
- `busy_timeout=0`; SQL lock conflicts return busy immediately (§4.4).
- The hive's tmpfs database attached as `volatile` (§3.3).

Both stores have private-cache WAL readers. The volatile tables are created
on the write connection; other connections attach the same file. A read-only
transaction pins a snapshot of both stores before a commit can publish.
[*conn.both-stores-use-wal-and-snapshots-pin-both-together]

## 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`.
<!-- lint-disable-next-line line-length -->
[*conn.nine-mutating-operations-route-through-the-transaction-aware-write-path]

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`.
[*conn.four-read-operations-route-to-the-read-pool-or-the-bound-transaction]

`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.
[*conn.delete-layer-and-flush-take-the-write-connection-directly]
 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.
[*conn.neither-delete-layer-nor-flush-can-join-a-callers-transaction]

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.
<!-- lint-disable-next-line line-length -->
[*conn.delete-layer-and-flush-decline-a-read-only-transaction-with-rsi-invalid]
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.
[*conn.delete-layer-declines-with-rsi-txn-busy-rather-than-blocking]

---

# 4.2 Request Dispatch

_Peios / Reference / loregd / Concurrency_

> RSI requests arrive multiplexed on one descriptor; identifying the target hive, and the operations that resolve differently.

RSI requests arrive multiplexed on the `/dev/pkm_registry` file
descriptor. Each carries a request id and a transaction id in its header.
[*dispatch.every-request-header-carries-a-request-id-and-a-transaction-id]

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.
<!-- lint-disable-next-line line-length -->
[*dispatch.every-request-is-served-by-its-own-goroutine-with-no-cap-on-concurrency]

Responses are serialized by a mutex, because one write to the device
corresponds to exactly one response.
[*dispatch.one-device-write-carries-exactly-one-response]

On shutdown the in-flight goroutines are drained before the process
exits.
[*dispatch.in-flight-requests-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:
[*dispatch.the-guid-cache-is-seeded-at-startup-with-every-hives-root-guid]

- `RSI_CREATE_KEY` stores the new GUID **immediately**, before the
  transaction that created it commits, and registers an abort hook to
  evict it if that transaction rolls back.
[*dispatch.a-created-guid-is-cached-before-commit-and-evicted-on-rollback]
  This makes the key immediately routable within the transaction. Cache
  misses also consult an existing transaction binding so a snapshot does
  not lose access to keys deleted after its first read.
- `RSI_DROP_KEY` evicts immediately outside a transaction, or through a
  commit hook inside one.
<!-- lint-disable-next-line line-length -->
[*dispatch.a-dropped-guid-is-evicted-immediately-or-on-commit-inside-a-transaction]
- `RSI_DELETE_LAYER` evicts the GUIDs its deletion orphaned.
[*dispatch.delete-layer-evicts-the-guids-its-deletion-orphaned]

On a miss, loregd probes each hive in turn:
[*dispatch.a-cache-miss-probes-every-hive-in-turn]

```sql
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.
[*dispatch.only-hits-are-cached-so-an-unknown-guid-is-re-probed-every-time]
The cache has no size bound; it shrinks only through the three eviction
paths above.
[*dispatch.the-guid-cache-has-no-size-bound]

A GUID that resolves to no hive produces `RSI_NOT_FOUND` for most
operations.
[*dispatch.a-guid-that-resolves-to-no-hive-produces-rsi-not-found]
`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.
[*dispatch.flush-resolves-its-hive-by-folded-name-case-insensitively]

`RSI_DELETE_LAYER` does not resolve a hive at all: it applies to every
registered hive and concatenates the orphan sets (§5.6).
[*dispatch.delete-layer-applies-to-every-registered-hive]

---

# 4.3 Transactions

_Peios / Reference / loregd / Concurrency_

> Transaction ids are allocated by the kernel and bound to connections lazily; beginning, read-write against read-only, committing, and aborting.

Transaction identifiers are allocated by the kernel and carried on every
request.
<!-- lint-disable-next-line line-length -->
[*txn.transaction-ids-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.
[*txn.begin-records-the-id-as-pending-and-returns-rsi-ok-immediately]
 No
connection is taken and no SQLite transaction is opened.
[*txn.begin-takes-no-connection-and-opens-no-sqlite-transaction]

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`.
[*txn.loregd-never-returns-rsi-txn-not-supported]

Re-using a transaction id that is already active returns `RSI_INVALID`.
[*txn.re-using-an-active-transaction-id-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.
[*txn.malformed-mode-is-rejected-without-recording-a-transaction]
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.
[*txn.a-read-write-transaction-binds-on-its-first-mutating-operation]
If SQLite reports `SQLITE_BUSY` at that point, the operation returns
`RSI_TXN_BUSY`.
[*txn.a-busy-database-at-bind-time-returns-rsi-txn-busy]

Once bound, every subsequent operation with that transaction id; reads
included; runs on the same connection.
<!-- lint-disable-next-line line-length -->
[*txn.once-bound-every-operation-on-the-transaction-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.
[*txn.a-transaction-sees-its-own-uncommitted-writes]
 Reads issued
before the transaction binds go to the read pool instead, since there
is nothing uncommitted to see.
[*txn.a-read-issued-before-binding-goes-to-the-read-pool]

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.
[*txn.publication-is-coordinated-across-both-stores]

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).
[*txn.crash-recovery-never-replays-the-volatile-side]

An operation whose GUID belongs to a different hive than the transaction
is bound to is rejected with `RSI_STORAGE_ERROR`.
[*txn.an-operation-on-another-hive-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**.
[*txn.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`.
<!-- lint-disable-next-line line-length -->
[*txn.a-read-only-transaction-gets-a-dedicated-connection-outside-the-read-pool]
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.
[*txn.every-read-in-a-read-only-transaction-observes-the-same-snapshot]

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.
[*txn.the-snapshot-covers-both-persistent-and-volatile-data]

A mutating operation carrying a read-only transaction id is rejected with
`RSI_INVALID` before any state changes.
<!-- lint-disable-next-line line-length -->
[*txn.a-mutation-in-a-read-only-transaction-is-rejected-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`.
[*txn.commit-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`.
[*txn.a-failed-commit-leaves-the-transaction-open-for-retry-or-abort]
Committing an unknown transaction id returns `RSI_STORAGE_ERROR`.
[*txn.committing-an-unknown-transaction-id-returns-rsi-storage-error]

Committing a read-only transaction releases the snapshot and returns
`RSI_OK`.
[*txn.committing-a-read-only-transaction-releases-the-snapshot]

`RSI_ABORT_TRANSACTION` issues `ROLLBACK`, closes the connection, releases
any snapshot, runs the transaction's abort hooks,
[*txn.abort-rolls-back-closes-the-connection-and-runs-the-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.
[*txn.abort-always-returns-rsi-ok-including-for-an-unknown-transaction-id]
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).
<!-- lint-disable-next-line line-length -->
[*txn.lcs-owns-transaction-expiry-and-shutdown-releases-remaining-transactions]

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.
[*txn.interrupted-transactions-require-abort]

---

# 4.4 Waiting and Contention

_Peios / Reference / loregd / Concurrency_

> Bounded request waits, nonblocking transaction admission, and independent WAL readers.

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.
[*contend.request-waits-have-a-bounded-context]

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.
[*contend.request-deadlines-come-from-the-negotiated-kernel-context]

## 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.
[*contend.competing-writes-decline-while-a-transaction-owns-the-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.
[*contend.readers-and-backups-do-not-wait-for-open-write-transactions]

## 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.
[*contend.cancellation-does-not-return-live-transactions-to-the-pool]

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.
[*contend.interrupted-bound-transactions-cannot-silently-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.
[*contend.transaction-expiry-is-owned-by-lcs]

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.
<!-- lint-disable-next-line line-length -->
[*contend.leases-reclaim-abandoned-state-without-reviving-expired-transactions]

---

# 5.1 Store Routing

_Peios / Reference / loregd / Request Handling_

> Persistent data in the main schema and volatile data in the attached one; how an operation picks, and the ones that span both.

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
[*route.an-operation-naming-one-key-routes-on-the-keys-store]

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.
[*route.a-guid-in-neither-store-produces-not-found]

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.
[*route.routing-follows-the-source-table-despite-contradictory-metadata]
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.
[*route.create-key-routes-on-the-requests-volatile-flag]

`RSI_CREATE_ENTRY` routes to the store containing the **child** key the
entry points at.
[*route.create-entry-routes-on-the-child-keys-store]
 When that
child GUID is present in neither store, the entry is written to the
persistent table.
[*route.an-entry-with-an-unknown-child-guid-goes-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.
[*route.hide-entry-routes-on-the-parent-key]

## 5.1.2 Operations spanning both stores
[*route.the-operations-that-span-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.
[*route.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.
[*route.a-triple-present-in-both-stores-appears-twice-in-the-response]
 The
same holds for value entries keyed on `(key_guid, name_folded, layer)`.
[*route.value-entries-are-not-de-duplicated-either]

The deletions; `RSI_DELETE_ENTRY`, `RSI_DELETE_VALUE_ENTRY`, and
`RSI_DROP_KEY`; do not route at all. They delete from both schemas
unconditionally.
[*route.the-deletions-do-not-route-and-delete-from-both-schemas]

---

# 5.2 Response Ordering

_Peios / Reference / loregd / Request Handling_

> Canonical ordering of child names, layers, values, and GUIDs in RSI responses.

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.
[*order.the-underlying-query-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:
[*order.every-affected-array-is-sorted-into-a-canonical-order]

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

[*order.lookup-path-entries-sort-by-layer-then-sequence]
[*order.enum-children-sorts-children-by-folded-name]
[*order.enum-children-per-child-entries-sort-by-layer-then-sequence]
[*order.query-values-entries-sort-by-folded-name-then-layer-then-sequence]
<!-- lint-disable-next-line line-length -->
[*order.query-values-blanket-tombstones-sort-by-folded-layer-name-then-sequence]
[*order.delete-layer-orphan-guids-sort-by-ascending-guid]
[*order.key-metadata-blocks-sort-by-ascending-guid]


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.
[*order.the-ordering-is-a-wire-stability-guarantee-only]

## 5.2.1 Arrays assembled outside one query
<!-- lint-disable-next-line spelling -->
[*order.two-arrays-are-assembled-first-and-sorted-afterwards]

Two of those arrays are not a single query's result set. They are
assembled first and sorted afterward:

- The **blanket-tombstone array** in an `RSI_QUERY_VALUES` response comes
  from its own `UNION ALL`, separate from the value entries it travels
  beside, and takes the same order they do.
[*order.the-blanket-tombstone-array-takes-the-same-order-as-the-value-entries]
- The **orphan-GUID array** in an `RSI_DELETE_LAYER` response is the
  concatenation of every registered hive's orphan set. That walk ranges a
  Go map, whose iteration order is randomized, so the array is sorted
  bytewise before it is encoded.
[*order.the-orphan-guid-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.
[*order.enum-children-emits-one-child-block-per-folded-name]

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.
[*order.the-display-name-is-the-bytewise-lower-of-the-stored-cases]
 Both
the order of children and the case of the name reported for each are
therefore stable across calls.
[*order.child-order-and-reported-case-are-both-stable-across-calls]

---

# 5.3 Key Operations

_Peios / Reference / loregd / Request Handling_

> The four key operations and the SQL behind each; create, read, write, and drop.

Four RSI operations create, read, update, and remove key records.


## 5.3.1 RSI_CREATE_KEY
[*key.create-key-inserts-a-new-key-row]

The request's volatile flag selects the target table (§5.1). For a
persistent key:

```sql
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.
[*key.last-write-time-is-set-by-loregd-at-insertion]

Uniqueness comes from the target table's primary key on `guid`, surfaced
as `RSI_ALREADY_EXISTS`.
[*key.a-duplicate-guid-in-the-target-table-returns-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.
[*key.a-guid-held-by-the-other-store-also-returns-already-exists]
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).
[*key.the-new-guid-is-cached-before-commit-and-dropped-on-rollback]

An unresolvable parent GUID returns `RSI_NOT_FOUND`, after a fallback
check of the registered hives' root GUIDs.
[*key.an-unresolvable-parent-guid-returns-not-found]

## 5.3.2 RSI_READ_KEY
[*key.read-key-returns-the-stored-key-metadata]

```sql
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,
[*key.read-key-returns-not-found-for-a-guid-in-neither-store]
 and likewise
if it resolves to no hive.
[*key.read-key-returns-not-found-when-the-guid-resolves-to-no-hive]
 The
`volatile` field in the response is the stored column value.
[*key.the-volatile-field-returned-is-the-stored-column-value]

## 5.3.3 RSI_WRITE_KEY
[*key.write-key-updates-the-two-mutable-fields]

Updates the two mutable fields of a key, selected by a field mask:

| Bit | Value | Field |
|---|---|---|
| 0 | `0x01` | `sd` |
| 1 | `0x02` | `last_write_time` |

[*key.mask-bit-0-selects-the-security-descriptor]
[*key.mask-bit-1-selects-the-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.
[*key.a-mask-with-any-other-bit-set-returns-invalid]

loregd builds one `UPDATE` from the mask, setting only the named fields:
[*key.the-update-sets-only-the-fields-the-mask-names]

```sql
-- 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`.
[*key.a-zero-mask-acts-as-an-existence-check]
 An update that matches no
row also returns `RSI_NOT_FOUND`.
[*key.an-update-matching-no-row-returns-not-found]

Outside a transaction the update is a single auto-committed statement.
[*key.write-key-outside-a-transaction-is-one-auto-committed-statement]
Inside one it runs on the transaction's connection.
[*key.write-key-inside-a-transaction-uses-its-connection]

## 5.3.4 RSI_DROP_KEY
[*key.drop-key-purges-a-guid-from-four-tables-in-each-schema]

Purges every trace of a GUID from both stores; four tables in each
schema:

```sql
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.
[*key.drop-key-outside-a-transaction-wraps-the-purge-in-begin-immediate]
Inside one, they run on the transaction's connection.
[*key.drop-key-inside-a-transaction-uses-its-connection]

Dropping a GUID that does not exist returns `RSI_OK`;
[*key.dropping-a-guid-that-does-not-exist-returns-ok]
 so does one that
resolves to no hive.
[*key.dropping-a-guid-that-resolves-to-no-hive-returns-ok]
 The operation
is idempotent.
[*key.drop-key-is-idempotent]
 The GUID is evicted from the
hive cache (§4.2).
[*key.drop-key-evicts-the-guid-from-the-hive-cache]

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_

> Lookup, create, hide, delete, and enumerate; the operations over the per-layer entries that give a key its names.

Path entry operations store layer-specific names, targets, and hiding markers.


## 5.4.1 RSI_LOOKUP
[*entry.lookup-returns-every-layers-entry-for-one-child-name]

Returns every layer's entry for one child name under one parent, together
with metadata for the keys those entries point at.

```sql
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.
[*entry.lookup-returns-hidden-entries-with-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).
[*entry.lookup-emits-one-metadata-block-per-distinct-target-guid]

loregd does no layer filtering and no resolution: every entry it holds is
returned, and choosing between them is the kernel's job.
[*entry.lookup-does-no-layer-filtering-and-no-resolution]

An unresolvable parent GUID returns `RSI_NOT_FOUND`.
[*entry.lookup-on-an-unresolvable-parent-returns-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.
[*entry.lookup-drops-an-entry-whose-key-record-is-missing]
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
[*entry.create-entry-inserts-one-layers-entry-for-a-child-name]

```sql
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).
[*entry.create-entry-targets-the-child-keys-store]
A child GUID in neither store lands in the persistent table.
[*entry.create-entry-for-an-unknown-child-guid-lands-in-the-persistent-store]

`RSI_ALREADY_EXISTS` comes from the target table's primary key on
`(parent_guid, child_name_folded, layer)`.
[*entry.create-entry-refuses-a-duplicate-parent-name-layer-triple]
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.
[*entry.create-entry-checks-both-stores-for-a-duplicate-triple]
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`.
[*entry.create-entry-on-an-unresolvable-parent-returns-not-found]

## 5.4.3 RSI_HIDE_ENTRY
[*entry.hide-entry-writes-a-tombstone-masking-lower-layers]

Writes a tombstone that masks the same name in lower layers:

```sql
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.
[*entry.a-hide-entry-tombstone-has-type-one-and-a-null-target]
The target table follows the store containing the **parent** key, because a
volatile parent's entire subtree is volatile.
[*entry.hide-entry-targets-the-parent-keys-store]
A parent GUID in neither store returns `RSI_NOT_FOUND`.
[*entry.hide-entry-on-an-unresolvable-parent-returns-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
[*entry.delete-entry-removes-one-layers-entry-from-both-stores]

Removes one layer's entry for one name, from both stores:

```sql
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.
[*entry.deleting-an-absent-entry-succeeds]
A parent GUID that resolves to no hive returns
`RSI_NOT_FOUND` rather than succeeding.
[*entry.delete-entry-on-an-unresolvable-parent-returns-not-found]

## 5.4.5 RSI_ENUM_CHILDREN
[*entry.enum-children-returns-every-layers-entry-for-every-child]

Returns every layer's entry for every child under a parent:

```sql
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.
[*entry.enum-children-groups-rows-into-one-block-per-folded-child-name]
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.
[*entry.enum-children-drops-a-child-left-holding-no-entries]
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.
[*entry.enum-children-omits-the-metadata-block-of-a-dropped-entry]

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_

> Querying, setting and deleting value entries, conditional writes, and setting a blanket tombstone.

Value operations preserve every layer entry and its kernel-assigned sequence.


## 5.5.1 RSI_QUERY_VALUES
[*value.query-values-returns-one-value-or-all-of-a-keys-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:

```sql
-- 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:
[*value.query-values-also-returns-the-blanket-tombstone-state]

```sql
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).
[*value.query-values-sorts-value-entries-and-blanket-tombstones]

An unresolvable GUID returns `RSI_NOT_FOUND`.
[*value.query-values-on-an-unresolvable-guid-returns-not-found]
An existing key with no values returns `RSI_OK` with empty arrays.
[*value.query-values-on-a-key-with-no-values-returns-empty-arrays]

## 5.5.2 RSI_SET_VALUE
[*value.set-value-writes-one-layers-entry-for-a-value]

The store containing the key selects the target table (§5.1).
[*value.set-value-targets-the-keys-store]
A key GUID in neither store returns `RSI_NOT_FOUND`.
[*value.set-value-on-an-unknown-key-guid-returns-not-found]

```sql
INSERT OR REPLACE INTO [values]
    (key_guid, name, name_folded, layer, type, data, sequence)
VALUES (?, ?, ?, ?, ?, ?, ?)
```

### 5.5.2.1 Conditional writes
[*value.a-non-zero-expected-sequence-makes-the-write-a-compare-and-swap]

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:

```sql
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.
[*value.a-failed-compare-and-swap-returns-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.
[*value.an-unbound-conditional-write-wraps-itself-in-begin-immediate]
If that transaction cannot begin because the database is busy, the
operation returns `RSI_TXN_BUSY`.
<!-- lint-disable-next-line line-length -->
[*value.a-conditional-write-that-cannot-begin-its-transaction-returns-txn-busy]
Inside a transaction, the caller's transaction already provides the
isolation.
<!-- lint-disable-next-line line-length -->
[*value.a-conditional-write-inside-a-transaction-relies-on-the-callers-isolation]

## 5.5.3 RSI_DELETE_VALUE_ENTRY
[*value.delete-value-entry-removes-one-layers-entry-from-both-stores]

Removes one layer's entry for one value, from both stores:

```sql
DELETE FROM [values]
WHERE key_guid = ? AND name_folded = ? AND layer = ?
```

No rows-affected check, so deleting an absent entry succeeds.
[*value.deleting-an-absent-value-entry-succeeds]
A GUID that resolves to no hive returns `RSI_NOT_FOUND`.
[*value.delete-value-entry-on-an-unresolvable-guid-returns-not-found]

## 5.5.4 RSI_SET_BLANKET_TOMBSTONE
[*value.a-blanket-tombstone-masks-every-value-in-lower-layers]

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).
[*value.set-blanket-tombstone-targets-the-keys-store]
A GUID in neither returns `RSI_NOT_FOUND`.
[*value.set-blanket-tombstone-on-an-unknown-key-guid-returns-not-found]

```sql
-- 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_

> Delete-layer and flush; the two operations that check the request's transaction id but cannot join it, taking the write connection directly.

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.
[*layer.both-operations-check-the-transaction-id-but-cannot-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).
<!-- lint-disable-next-line line-length -->
[*layer.both-operations-take-the-write-connection-directly-and-commit-their-own-work]

## 5.6.1 RSI_DELETE_LAYER
[*layer.delete-layer-removes-every-entry-of-one-layer-and-reports-the-orphans]

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.
[*layer.delete-layer-is-applied-to-every-registered-hive]

For each hive, inside one `BEGIN IMMEDIATE` transaction, loregd first
computes the orphan set and then deletes:

```sql
-- 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.
[*layer.an-orphan-is-a-guid-referenced-only-by-the-layer-being-deleted]

The deletion statements run against each schema:

```sql
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.
[*layer.the-orphan-computation-and-the-deletions-share-one-transaction]
The orphaned GUIDs are evicted from the hive cache (§4.2)
and returned to the caller.
[*layer.orphaned-guids-are-evicted-from-the-hive-cache-and-returned]

The response array is sorted into ascending byte order (§5.2).
[*layer.delete-layer-returns-the-orphan-set-in-ascending-byte-order]

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.
[*layer.delete-layer-reports-a-contended-write-as-txn-busy]
Other failures are `RSI_STORAGE_ERROR`.
[*layer.delete-layer-reports-other-failures-as-storage-error]

## 5.6.2 RSI_FLUSH
[*layer.flush-checkpoints-the-write-ahead-log-for-durability]

Checkpoints the hive's main write-ahead log and requests truncation after
all frames are checkpointed:

```sql
PRAGMA wal_checkpoint(TRUNCATE)
```

The request carries a hive **name** rather than a GUID.
[*layer.flush-identifies-its-hive-by-name-rather-than-guid]
It is matched case-insensitively against the registered hives by folded
name (§3.4).
[*layer.flush-matches-the-hive-name-case-insensitively-by-folded-name]
A name matching none returns `RSI_INVALID`.
[*layer.flush-on-an-unregistered-hive-name-returns-invalid]

Two conditions return `RSI_TXN_BUSY` instead of checkpointing:

- A read-write transaction is bound to the hive.
[*layer.flush-declines-while-a-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.
[*layer.flush-returns-txn-busy-when-the-checkpoint-reports-the-database-busy]

The volatile store has no durability and is unaffected: nothing is
flushed, and nothing needs to be.
[*layer.flush-leaves-the-volatile-store-untouched]

## 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_

> The seven RSI status codes loregd returns, and the three the interface defines that it never produces.

loregd returns seven of the RSI status codes:
[*status.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. |

[*status.ok-is-returned-on-success-and-by-an-idempotent-deletion]
[*status.not-found-is-returned-for-an-unknown-guid-or-unresolvable-hive]
[*status.already-exists-is-returned-for-a-duplicate-key-guid-or-path-entry]
[*status.no-value-operation-returns-already-exists]
<!-- lint-disable-next-line line-length -->
[*status.storage-error-is-returned-for-a-sqlite-failure-or-a-transaction-mismatch]
[*status.txn-busy-is-returned-when-a-write-cannot-take-the-database]
[*status.invalid-is-returned-for-a-malformed-or-unacceptable-request]
[*status.cas-failed-is-returned-when-a-conditional-set-value-does-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).
[*status.three-interface-codes-are-never-produced-by-loregd]

`RSI_TXN_NOT_SUPPORTED` is never needed because loregd supports both
transaction modes (§4.3).
[*status.txn-not-supported-is-never-returned]

`RSI_TOO_LARGE` is never returned because an oversized or malformed frame
is not answered at all.
[*status.too-large-is-never-returned-because-a-bad-frame-ends-the-connection]
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 is specified against SQLite rather than an abstract store; how it relates to SQLite, the Windows hive format, and RSI.

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.
[*priorart.loregd-is-specified-against-sqlite-not-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.
[*priorart.no-regf-file-can-be-read-or-written-by-loregd]

## A.3 The registry source interface

loregd implements the RSI. The
[kernel source interface](/kernel/internals/lcs/sources/overview.md) 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.
[*priorart.the-rsi-specification-wins-over-this-manual]

---

# 1.1 Overview

_Peios / Reference / eventd / Introduction_

> eventd is the single persistent sink for everything a Peios system records about itself — the shape of the daemon, and what it is not.

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.
[*overview.eventd-stores-and-answers-queries-for-events-logs-and-metrics]

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.
<!-- lint-disable-next-line line-length -->
[*overview.eventd-is-a-boot-started-critical-platform-daemon-signed-at-tcb-level]

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.
[*overview.eventd-stores-log-lines-without-parsing-them]

**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).
[*overview.eventd-reads-no-proc-scrapes-no-endpoint-and-polls-no-service]
External producers measure and push their own samples.

**It is not a tracing system.** Distributed tracing is out of scope
entirely. [*overview.eventd-implements-no-distributed-tracing]

**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.
[*overview.eventd-costs-a-batch-commit-interval-of-latency-over-kmes]

**It is not the only KMES consumer**, and holds no privileged position
among them.
[*overview.eventd-holds-no-privileged-position-among-kmes-consumers]

---

# 1.2 What This Manual Is

_Peios / Reference / eventd / Introduction_

> The implementation scope, interface authorities, and limits of the eventd technical reference manual.

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 this manual borrows unchanged from elsewhere in the corpus, and the ones it introduces.

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).
[*term.there-is-exactly-one-drain-thread-per-cpu]

**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).
[*term.each-shard-has-exactly-one-writer-thread-and-no-other-writer]

**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).
[*term.the-query-path-treats-every-shard-as-one-store]

**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).
<!-- lint-disable-next-line line-length -->
[*term.a-historical-shard-takes-no-new-events-is-still-queried-and-is-written-only-by-retention]

**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).
<!-- lint-disable-next-line line-length -->
[*term.the-handoff-channel-is-bounded-by-slots-and-bytes-independently-of-batch-size]

**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).
[*term.synthetic-events-bypass-kmes-and-carry-no-stamps-or-sequence-numbers]

**Gap record**: the `eventd.events.lost` synthetic event recording that
events were lost on one CPU, and which sequence numbers went missing
(§2.5).
[*term.a-gap-record-names-the-cpu-and-the-missing-sequence-numbers]

**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).
<!-- lint-disable-next-line line-length -->
[*term.the-metadata-database-is-not-a-shard-and-survives-shard-reconfiguration]

**Desired index set**: the global, priority-ordered list of fields eventd
aims to have indexed across all shards.
[*term.the-desired-index-set-is-one-global-priority-ordered-list]

**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).
[*term.material-indexes-converge-when-quiet-and-diverge-under-pressure]

**Shedding**: dropping secondary indexes to protect write throughput
(§3.4). [*term.shedding-drops-secondary-indexes]

**Rollup**: a disposable, pre-computed metric-window result whose freshness is
proved against authoritative raw samples before reuse (§5.6).
<!-- lint-disable-next-line line-length -->
[*term.a-rollup-is-reused-only-after-its-freshness-is-proved-against-raw-samples]

**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).
<!-- lint-disable-next-line line-length -->
[*term.the-series-cache-is-a-bounded-in-memory-map-from-series-identity-to-row]

**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).
[*term.retention-is-enforced-against-logical-live-size-not-file-size]

**Quarantine**: renaming a database SQLite has reported corrupt, aside
from the path eventd uses, and creating an empty one in its place
(§3.3).
[*term.quarantine-renames-a-corrupt-database-aside-and-creates-an-empty-one]

---

# 1.4 Component Boundaries

_Peios / Reference / eventd / Introduction_

> The responsibilities eventd owns and the interfaces it shares with kernel, service-management, and configuration components.

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.
[*priorart.eventd-stores-in-sqlite-not-a-proprietary-binary-format]
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_

> The four stages from shared memory to a committed row, why the ring buffers are the only buffer, and how sharding scales writes.

eventd is the primary consumer of the KMES ring buffers. Events travel
from shared memory to a committed database row in four stages.
<!-- lint-disable-next-line line-length -->
[*pipeline.events-travel-from-the-ring-buffers-to-a-committed-row-in-four-stages]

1. **Drain.** One thread per CPU reads events from that CPU's ring
   buffer, following the lock-free read protocol PSPK specifies (§2.2).
2. **Detect.** The drain thread compares each event's sequence number
   against the last it saw for that CPU. A jump means events were lost,
   and the loss becomes a gap record (§2.5).
3. **Hand off.** The drain thread copies the event out of the mapped
   region and passes it to the writer thread that owns the shard it
   routes to (§2.3).
4. **Write.** The writer thread accumulates events into a transaction
   and commits, sizing the batch to whatever throughput allows (§2.4).

Two principles govern the whole pipeline, and most of its behavior
follows from them rather than from anything specific to a stage.

## 2.1.1 The ring buffers are the only buffer

[*pipeline.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.
<!-- lint-disable-next-line line-length -->
[*pipeline.backpressure-propagates-from-the-writer-through-the-channel-to-the-ring-buffer]

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**.
<!-- lint-disable-next-line line-length -->
[*pipeline.a-full-ring-buffer-loses-events-visibly-rather-than-buffering-without-bound]

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.
[*pipeline.each-shard-has-its-own-file-wal-and-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.
[*pipeline.shards-share-no-write-path-state-or-coordination-point]

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_

> Discovering CPUs and attaching to their rings, the drain threads, copying, generation changes and sequence tracking.

## 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.
[*kmes.startup-queries-the-slot-count-and-tries-every-slot-below-it] 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.
[*kmes.an-einval-slot-is-a-hole-and-enumeration-continues] Each
successful descriptor is mapped at the size derived from the returned
`capacity`, exactly as PSPK §2.3 defines.
[*kmes.each-descriptor-is-mapped-at-the-size-derived-from-its-capacity]

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.
<!-- lint-disable-next-line line-length -->
[*kmes.sparse-cpus-get-dense-ordinals-internally-but-keep-their-logical-cpu-id-externally]

Attachment requires SeSecurityPrivilege in the effective token, which is
the privilege that grants an unfiltered view of every event on the
system. [*kmes.attachment-requires-sesecurityprivilege] 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).
[*kmes.discovering-zero-cpus-is-a-startup-failure] There is no
configuration for the CPU count and no way to attach to a subset.
[*kmes.every-attachable-cpu-is-attached-with-no-way-to-choose-a-subset]

## 2.2.2 Drain threads

There is one drain thread per CPU, and each reads exactly one ring
buffer. [*kmes.one-drain-thread-per-cpu-reads-exactly-one-ring-buffer]
A drain thread never reads another CPU's buffer, which is what
makes per-CPU sequence tracking a thread-local variable rather than
shared state.

Each thread follows the read protocol PSPK specifies:

- `read_pos` starts at `tail_pos` on first attachment, so eventd begins
  at the oldest surviving event rather than at the newest.
  [*kmes.first-attachment-starts-reading-at-the-oldest-surviving-event]
- The drain loop loads `write_pos` with acquire ordering, checks
  `tail_pos` for lapping, validates the event's structural integrity,
  and advances `read_pos` by `event_size`.
<!-- lint-disable-next-line line-length -->
  [*kmes.the-drain-loop-checks-lapping-validates-each-event-and-advances-by-event-size]
- After reading an event it re-reads `tail_pos` — the torn-read check —
  to detect that KMES overwrote the event while it was being copied.
  [*kmes.tail-pos-is-re-read-after-each-event-to-detect-a-torn-read]
- With nothing to read it uses the notification protocol, setting
  `need_wake` and waiting on the futex, rather than spinning.
  [*kmes.an-empty-buffer-is-waited-on-through-the-futex-not-by-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`.
[*kmes.a-slot-and-the-events-bytes-are-reserved-before-copying-and-advancing]
If either reservation is unavailable, it leaves the event in KMES and
waits; it does not copy or advance first (§2.3).
[*kmes.without-both-reservations-the-event-stays-in-kmes-and-the-drain-waits]

Nothing derived from the mapped region ever reaches a writer thread.
[*kmes.nothing-derived-from-the-mapped-region-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.
[*kmes.the-copy-is-bounded-by-the-events-own-event-size]

## 2.2.4 Generation changes
<!-- lint-disable-next-line line-length -->
[*kmes.a-drain-thread-checks-the-generation-after-each-cycle-and-follows-a-change]

An administrator changing the ring buffer capacity causes KMES to
replace the buffers, which it signals by changing the `generation`
field. A drain thread checks it after each drain cycle, and on a change:

1. Records the sequence number of the last event it has successfully
   handed off.
   [*kmes.generation-change-records-the-last-handed-off-sequence]
2. Finishes draining the old buffer to its now-frozen `write_pos`,
   updating that sequence number as it goes.
   [*kmes.generation-change-drains-the-old-buffer-to-its-frozen-write-pos]
3. Calls `kmes_attach` again for the same logical CPU, obtains the
   replacement descriptor, and maps it while the old mapping remains
   valid.
<!-- lint-disable-next-line line-length -->
   [*kmes.generation-change-reattaches-and-maps-the-replacement-while-the-old-mapping-is-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.
[*kmes.generation-change-resumes-at-the-first-sequence-after-the-last-drained]
5. Closes and unmaps the old buffer only after that scan succeeds.
[*kmes.generation-change-unmaps-the-old-buffer-only-after-the-scan-succeeds]
6. Resumes draining from the new buffer.
   [*kmes.generation-change-resumes-draining-from-the-new-buffer]

Each drain thread handles this independently.
[*kmes.each-drain-thread-handles-a-generation-change-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.
[*kmes.survivors-discarded-by-a-shrink-appear-as-an-ordinary-gap]

## 2.2.5 Sequence tracking

During an uninterrupted run, each drain thread holds the last sequence
number it saw for its logical CPU.
[*kmes.each-drain-thread-holds-the-last-sequence-seen-for-its-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).
<!-- lint-disable-next-line line-length -->
[*kmes.restart-resumes-from-the-union-of-committed-receipt-ranges-not-one-number]

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.
[*kmes.restart-skips-covered-survivors-and-re-ingests-uncovered-ones] It
emits a gap only for a sequence that is covered by neither a committed
receipt nor a surviving ring record (§8.5).
[*kmes.restart-emits-a-gap-only-for-sequences-neither-receipted-nor-surviving]
With no receipt for a CPU, coverage begins before sequence 1, so
an overwritten prefix is detected correctly.
[*kmes.with-no-receipt-for-a-cpu-coverage-begins-before-sequence-1]

The metadata database's sequence checkpoints and the shutdown event are
diagnostic only (§3.5, §8.4). Neither participates in recovery.
[*kmes.sequence-checkpoints-and-the-shutdown-event-take-no-part-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.
[*kmes.a-sequence-regression-under-the-same-boot-id-stops-eventd]

---

# 2.3 Sharding

_Peios / Reference / eventd / Event Ingestion_

> Event writes distributed across independent databases — the count, descriptor budget, assignment, writer threads, and handoff.

## 2.3.1 The shard count

Event writes are distributed across independent SQLite databases.
An explicit `StorageShards` count (§A) is between one and 256.
[*shard.there-are-between-1-and-256-event-shards] Zero means "as many
shards as there are successfully attached KMES buffers", and is the
default; that automatic count is not capped at 256.
<!-- lint-disable-next-line line-length -->
[*shard.storage-shards-zero-is-the-default-and-means-one-shard-per-attached-buffer]

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.
[*shard.eventd-neither-raises-its-descriptor-limit-nor-caps-the-shard-count]
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).
[*shard.a-high-storage-shards-needs-a-raised-descriptor-limit]

The packaged value uses this conservative planning allowance:

```text
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.
[*shard.neither-a-power-of-two-nor-a-multiple-of-the-buffer-count-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.
<!-- lint-disable-next-line line-length -->
[*shard.assignment-is-computed-once-at-startup-and-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`.
<!-- lint-disable-next-line line-length -->
[*shard.ordinal-c-is-assigned-every-shard-j-where-j-mod-attached-count-equals-c]
If that produces nothing — which happens when there are fewer shards
than attached buffers — ordinal `c` is instead assigned
`c % shard_count`.
[*shard.an-ordinal-with-no-shard-is-assigned-c-mod-shard-count] Every
drain thread ends with at least one write path.
[*shard.every-drain-thread-has-at-least-one-shard] Logical `cpu_id`, not
the ordinal, is stored. [*shard.the-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 |

[*shard.equal-counts-give-one-shard-per-cpu]
[*shard.fewer-shards-than-cpus-means-cpus-share-shards]
[*shard.more-shards-than-cpus-means-a-cpu-owns-several]

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.
<!-- lint-disable-next-line line-length -->
[*shard.a-multi-shard-drain-thread-sends-fixed-length-contiguous-stripes-to-its-shards-in-turn]
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).
[*shard.the-stripe-length-is-chosen-at-startup-and-not-persisted]

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.
[*shard.uneven-counts-leave-an-imbalance-of-at-most-one-shard-or-cpu] 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

[*shard.the-query-path-assumes-no-relationship-between-a-shard-and-a-cpu]

Assignment is not persisted. [*shard.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.
[*shard.each-shard-has-exactly-one-writer-thread-and-no-other-writer] 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.
[*shard.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.
[*shard.the-handoff-channel-is-multi-producer-single-consumer]

## 2.3.5 The handoff channel

Each writer thread has one bounded channel through which drain threads
submit events. [*shard.each-writer-thread-has-one-bounded-handoff-channel]
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.
<!-- lint-disable-next-line line-length -->
[*shard.channel-capacity-is-fixed-at-startup-in-slots-and-bytes-independent-of-max-batch-size]
Both are internal implementation limits selected by performance testing,
not live registry settings.
[*shard.the-channel-bounds-are-not-registry-settings]

When either bound would be exceeded the drain thread **stops reading
from the ring buffer** and waits.
<!-- lint-disable-next-line line-length -->
[*shard.a-drain-thread-stops-reading-when-either-channel-bound-would-be-exceeded]
It reserves capacity before copying or advancing `read_pos` (§2.2), does
not drop events to relieve pressure, and does not grow the channel.
[*shard.channel-pressure-never-drops-events-or-grows-the-channel] Events
accumulate in the ring buffer instead, which is the designed path
(§2.1):

```text
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.
[*shard.the-drain-thread-resumes-as-soon-as-the-channel-has-room]

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.
<!-- lint-disable-next-line spelling -->
[*shard.a-transaction-may-hold-more-events-than-the-channel-can-at-once]
Changing `MaxBatchSize` changes only the writer's next commit threshold
and never resizes or replaces a live channel (§8.3).
[*shard.changing-max-batch-size-never-resizes-or-replaces-a-live-channel]

## 2.3.6 Lifecycle and reconfiguration

Shard databases are created in the event store directory on first use.
[*shard.shard-databases-are-created-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).
[*shard.shards-left-by-a-previous-configuration-are-kept-and-still-read]

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.a-storage-shards-change-is-deferred-to-the-next-restart]

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_

> How each writer thread commits — explicit transactions, adaptive batch sizing, WAL checkpointing, and prepared statements.

## 2.4.1 Transactions

Each writer thread writes to its shard with explicit transactions: a
`BEGIN`, one `INSERT` per event, a `COMMIT`.
[*batch.a-batch-is-an-explicit-transaction-with-one-insert-per-event]
The commit is the durability boundary.
[*batch.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).
<!-- lint-disable-next-line line-length -->
[*batch.each-maximal-contiguous-sequence-run-in-a-transaction-gets-a-receipt-row]
Events, gaps, and their receipts commit together: there is no second
durability operation and no global receipt writer.
[*batch.events-gaps-and-their-receipts-commit-in-the-same-transaction]

The database runs in WAL mode with `synchronous = FULL`, so every commit
fsyncs the write-ahead log.
<!-- lint-disable-next-line line-length -->
[*batch.shards-run-in-wal-mode-with-synchronous-full] This is the strictest of the three stores'
settings, and the only one where per-transaction durability is bought at
per-transaction cost — because an event can be an audit record and
losing the last second of them to a power cut is a real loss.

## 2.4.2 Adaptive batch sizing

The writer sizes each batch to balance throughput against how much sits
uncommitted at any moment.

**Throughput is always the priority.** If eventd falls behind the
emission rate, ring buffers fill and events are overwritten, which is
irrecoverable; a shorter power-loss window is not worth that trade. The
algorithm maximizes resilience *within* the constraint that throughput
is maintained, never against it.

1. When the first event is available, the writer opens a transaction and
   records the start time.
<!-- lint-disable-next-line line-length -->
   [*batch.the-first-available-event-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
[*batch.a-batch-commits-when-no-assigned-drain-thread-has-an-event-available]
   - the batch holds `MaxBatchSize` events
     [*batch.a-batch-commits-when-it-holds-max-batch-size-events]
   - `MaxBatchLatencyMs` has elapsed since the first event entered it
<!-- lint-disable-next-line line-length -->
     [*batch.a-batch-commits-once-max-batch-latency-ms-has-elapsed-since-its-first-event]
4. Otherwise it keeps reading and inserting.
5. With nothing available and an empty batch, it sleeps until a producer
   wakes it. [*batch.an-idle-writer-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.
[*batch.an-insert-group-never-takes-a-batch-past-either-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.
[*batch.the-default-caps-are-10000-events-and-100-milliseconds]

## 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.
<!-- lint-disable-next-line line-length -->
[*batch.a-passive-checkpoint-is-triggered-when-the-wal-reaches-wal-checkpoint-pages]
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.
<!-- lint-disable-next-line line-length -->
[*batch.a-stalled-checkpoint-never-blocks-the-writer-and-is-retried-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.
[*batch.checkpointing-runs-on-the-writer-thread] 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. [*batch.the-event-insert-is-prepared-once-at-startup-and-reused]

The receipt insert and new-event-type catalog insert are prepared and
reused too.
<!-- lint-disable-next-line spelling -->
[*batch.the-receipt-and-catalogue-inserts-are-prepared-and-reused] 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).
<!-- lint-disable-next-line line-length spelling -->
[*batch.only-a-new-event-type-is-catalogued-in-the-transaction-of-its-first-event]

## 2.4.5 Maintenance commands

The writer owns the shard's only read-write connection.
[*batch.the-writer-owns-the-shards-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.
[*batch.maintenance-reaches-a-shard-only-as-bounded-commands-to-its-writer]

The writer considers low-priority maintenance only at transaction
boundaries and rechecks ingestion pressure after one bounded action.
<!-- lint-disable-next-line line-length -->
[*batch.low-priority-maintenance-runs-at-transaction-boundaries-one-bounded-action-at-a-time]
A size-urgent retention delete can be included in an existing ingestion
transaction so it adds no second commit.
<!-- lint-disable-next-line spelling -->
[*batch.a-size-urgent-retention-delete-may-join-an-ingestion-transaction]
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.
[*batch.ingestion-takes-priority-over-maintenance-under-sustained-pressure]

---

# 2.5 Gap Detection

_Peios / Reference / eventd / Event Ingestion_

> Per-CPU sequence numbers are the whole mechanism — what causes a gap, what a gap record holds, and how lapping is detected.

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.
[*gap.a-sequence-beyond-the-expected-next-one-reveals-a-gap]

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. [*gap.a-ring-buffer-overrun-is-recorded-as-a-gap]
- **Structural drops.** KMES declined to write an event that exceeded
  its size limits. [*gap.a-structural-drop-is-recorded-as-a-gap]
- **Downtime.** Events emitted while eventd was not running.
  [*gap.events-lost-while-eventd-was-not-running-are-recorded-as-a-gap]

All three appear identically at the consumer, which is why the record
says what was lost rather than why.
[*gap.a-gap-record-says-what-was-lost-not-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 [*gap.a-gap-record-carries-the-cpu-identifier]
- the first missing sequence number, the last seen plus one
  [*gap.the-first-missing-sequence-is-the-last-seen-plus-one]
- the last missing sequence number, the revealing event's minus one
  [*gap.the-last-missing-sequence-is-the-revealing-events-minus-one]
- the count of missing events
  [*gap.a-gap-record-carries-the-count-of-missing-events]
- the timestamp of the last event successfully processed on this CPU,
  where one is known
  [*gap.a-gap-record-carries-the-last-processed-timestamp-where-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.
[*gap.a-gap-records-time-is-the-revealing-events-timestamp]

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.
[*gap.a-gap-record-is-committed-through-the-normal-write-path] 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).
<!-- lint-disable-next-line line-length -->
[*gap.a-gaps-receipt-range-covers-the-missing-interval-so-a-restart-never-repeats-it]
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. [*gap.a-gap-record-is-never-emitted-through-kmes]

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.
<!-- lint-disable-next-line line-length -->
[*gap.gap-details-are-a-messagepack-payload-and-gaps-are-queryable-like-any-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).
[*gap.a-gap-record-sets-cpu-id-and-leaves-the-other-header-columns-null]

`cpu_id` is populated deliberately, and it is the one place a synthetic
event carries a header field.
[*gap.gap-records-are-the-only-synthetic-events-with-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`.
[*gap.a-lapped-reader-is-advanced-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.
[*gap.lapping-is-recorded-by-ordinary-gap-detection] The
lapping case and the restart case produce the same record by the same
path.

---

# 2.6 Synthetic Events

_Peios / Reference / eventd / Event Ingestion_

> Records eventd generates about itself, written straight to a shard and never through KMES — when, where and in what order.

Synthetic events are records eventd generates about itself. They are
written straight to a shard database and never touch KMES.
<!-- lint-disable-next-line line-length -->
[*synthetic.synthetic-events-are-written-straight-to-a-shard-and-never-touch-kmes]

They carry no KMES header: no identity stamps, no sequence number, no
origin class. [*synthetic.synthetic-events-carry-no-kmes-header] 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).
[*synthetic.a-synthetic-event-has-a-timestamp-and-one-of-five-eventd-types]
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` |

[*synthetic.lost-events-on-a-cpu-emit-eventd-events-lost]
[*synthetic.starting-and-attaching-to-kmes-emits-eventd-daemon-started]
[*synthetic.graceful-shutdown-emits-eventd-daemon-stopped]
<!-- lint-disable-next-line line-length -->
[*synthetic.a-store-found-corrupt-and-quarantined-emits-eventd-store-quarantined]
[*synthetic.a-runtime-configuration-change-emits-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.
[*synthetic.all-five-types-are-essential-and-no-emission-policy-applies]
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.
[*synthetic.malformed-ingestion-input-emits-no-synthetic-event]
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.
[*synthetic.a-gap-record-goes-to-a-shard-of-the-cpu-that-generated-it] 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.
<!-- lint-disable-next-line line-length -->
[*synthetic.daemon-wide-events-go-to-shard-0-else-the-lowest-numbered-writable-active-shard]
If no shard is writable at all the event is skipped, with the failure
logged to standard error.
<!-- lint-disable-next-line line-length -->
[*synthetic.with-no-writable-shard-a-daemon-wide-event-is-skipped-and-logged-to-stderr]

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.
<!-- lint-disable-next-line line-length -->
[*synthetic.a-storage-error-skips-the-failing-shard-unless-it-is-writable-again]

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.
<!-- lint-disable-next-line line-length -->
[*synthetic.synthetic-events-share-the-shards-batching-retention-and-queries-of-kmes-events]
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.
[*synthetic.access-to-synthetic-events-is-governed-by-the-eventd-events-keys]

They are ordered by their timestamp and take no part in per-CPU sequence
numbering.
<!-- lint-disable-next-line line-length -->
[*synthetic.synthetic-events-are-ordered-by-timestamp-and-take-no-sequence-number]

For the four daemon-wide types that timestamp is when eventd
**noticed**, not when the condition occurred.
[*synthetic.a-daemon-wide-records-timestamp-is-when-eventd-noticed]
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.
<!-- lint-disable-next-line line-length -->
[*synthetic.a-gap-records-timestamp-is-the-revealing-events-not-the-detection-time]

## 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.
[*synthetic.exactly-the-five-types-are-reserved-not-the-eventd-root]

---

# 3.1 The Event Shard Schema

_Peios / Reference / eventd / Event Storage_

> Event rows, committed sequence receipts, the event-type catalog, and the write-time index in every shard.

Every shard database holds one `events` table.
[*events.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. |

[*events.id-is-a-rowid-monotonic-within-the-shard]
[*events.boot-id-is-a-16-byte-guid-in-pcds-binary-layout]
[*events.timestamp-is-epoch-nanoseconds-from-the-header-or-eventds-clock]
<!-- lint-disable-next-line line-length -->
[*events.cpu-id-is-null-for-daemon-wide-synthetic-events-but-set-for-gap-records]
<!-- lint-disable-next-line line-length -->
[*events.sequence-is-the-per-cpu-per-boot-header-sequence-and-null-for-synthetics]
<!-- lint-disable-next-line line-length -->
[*events.origin-class-is-0-userspace-1-kmes-2-kacs-3-lcs-and-null-for-synthetics]
[*events.event-type-is-the-header-type-or-one-of-the-five-eventd-types]
[*events.effective-token-guid-is-the-effective-token-at-emission]
[*events.true-token-guid-is-the-primary-token-and-null-for-synthetics]
[*events.process-guid-is-the-emitting-process-and-null-for-synthetics]
[*events.payload-is-the-raw-kmes-bytes-a-synthetic-map-or-null]

## 3.1.1 Header fields are columns

Every KMES header field is extracted into its own column rather than
left inside the payload blob.
<!-- lint-disable-next-line line-length -->
[*events.every-kmes-header-field-is-extracted-into-its-own-column] 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. [*events.event-type-alone-distinguishes-real-from-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.
<!-- lint-disable-next-line line-length -->
[*events.a-kmes-event-typed-as-one-of-the-five-eventd-types-is-counted-and-not-stored]
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. [*events.a-kmes-payload-is-stored-exactly-as-delivered]
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.
[*events.the-write-path-never-decodes-re-encodes-or-validates-a-payload]

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.
[*events.payloads-are-decoded-and-flattened-only-on-the-read-path]

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.
<!-- lint-disable-next-line line-length -->
[*events.a-payload-field-colliding-with-a-header-name-is-suppressed-but-kept-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. |

[*events.event-types-lists-each-concrete-type-committed-to-the-shard]

The writer loads this small set into an in-memory intern table at
<!-- lint-disable-next-line spelling -->
startup. [*events.the-writer-loads-the-type-catalogue-into-memory-at-startup]
A known type adds no catalog statement to an event insert.
<!-- lint-disable-next-line spelling -->
[*events.a-known-type-adds-no-catalogue-statement-to-an-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.
<!-- lint-disable-next-line line-length spelling -->
[*events.a-new-type-is-catalogued-with-its-first-event-and-interned-after-commit]
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.
<!-- lint-disable-next-line line-length spelling -->
[*events.a-pending-set-stops-repeat-catalogue-inserts-in-a-batch-and-rollback-discards-it]

Query planning unions these catalogs across relevant active and
historical shards to discover concrete identifiers for access checks
(§6.1).
<!-- lint-disable-next-line spelling -->
[*events.planning-unions-type-catalogues-across-active-and-historical-shards]
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).
[*events.planning-never-scans-the-events-table-for-distinct-types]

Retention records the distinct types touched by each delete batch and
offers orphan checks as low-priority maintenance.
[*events.retention-offers-orphan-type-checks-for-types-its-deletes-touched]
The writer rechecks
`NOT EXISTS` in the deletion transaction, and removes the type from its
in-memory set only after that deletion commits.
<!-- lint-disable-next-line line-length -->
[*events.an-orphan-type-is-rechecked-in-the-deletion-transaction-and-uninterned-after-commit]
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.
<!-- lint-disable-next-line line-length -->
[*events.an-unindexed-or-interrupted-orphan-check-is-skipped-rather-than-delaying-ingestion]
Catalog pages count toward the store's logical
live size (§3.6), preventing unique-name abuse from escaping the
store-wide size accounting.
<!-- lint-disable-next-line spelling -->
[*events.catalogue-pages-count-toward-the-logical-live-size]

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

[*events.a-receipt-range-records-the-16-byte-kernel-boot-id]
[*events.a-receipt-range-records-the-logical-kmes-cpu]
[*events.a-receipt-range-first-sequence-is-inclusive]
[*events.a-receipt-range-last-sequence-is-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`.
<!-- lint-disable-next-line line-length -->
[*events.receipt-ranges-are-keyed-on-all-four-columns-and-must-be-positive-and-ordered]

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.
<!-- lint-disable-next-line line-length -->
[*events.a-receipt-commits-in-the-transaction-that-stores-its-rows-or-gap-record]
Receipt rows survive event retention.
[*events.receipt-rows-survive-event-retention]

Startup unions and merges overlapping or adjacent ranges across every
readable shard (§2.2, §8.5).
<!-- lint-disable-next-line line-length -->
[*events.startup-merges-overlapping-and-adjacent-receipt-ranges-across-readable-shards]
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.
<!-- lint-disable-next-line line-length -->
[*events.receipt-compaction-inserts-the-merged-range-before-deleting-what-it-subsumes]
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.
[*events.receipt-compaction-only-piggybacks-on-writer-commits]
Startup
merge correctness never depends on physical compaction.
[*events.startup-merge-correctness-never-depends-on-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. [*events.a-null-effective-token-guid-means-a-synthetic-record]
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.
<!-- lint-disable-next-line line-length -->
[*events.a-null-guid-effective-token-means-a-real-event-emitted-without-identity]

The distinction matters for audit: "eventd wrote this" and "the kernel
emitted this and could not attribute it" are different facts.

## 3.1.6 Write-time indexes

One index is created with the table:

- `idx_events_timestamp` on `events(timestamp)`
  [*events.idx-events-timestamp-is-the-one-index-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. |

[*events.shard-metadata-key-is-the-text-primary-key]
[*events.shard-metadata-value-is-non-null-text]

with two required entries: `schema_version`, and `created_at` as a UTC
timestamp formatted `YYYY-MM-DDTHH:MM:SSZ`.
<!-- lint-disable-next-line line-length -->
[*events.shard-metadata-requires-schema-version-and-a-utc-created-at] The current version is in
§B.

eventd checks the version at startup and applies the lifecycle rules of
§3.3. It does not migrate: an unrecognized version is a startup failure
for an active shard and an exclusion for a historical one.
[*events.a-shard-schema-is-never-migrated] 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_

> The MessagePack payload of each of the five event types eventd writes about itself, field by field, in the catalog's names.

Each of the five synthetic event types (§2.6) carries a MessagePack map
in `payload`, with the schema below.
[*payload.every-synthetic-event-carries-a-messagepack-map] 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.
[*payload.fields-are-nested-by-path-and-queried-by-their-dotted-names]

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.
[*payload.no-field-is-ever-nil-an-absent-value-is-left-out]

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` [*payload.the-eventd-daemon-started-payload-schema]

| Field | Type | Contents |
|---|---|---|
| `store.restarted` | bool | True when committed rows or receipts for this boot already existed at startup; false on the boot's first successful eventd start. |
| `store.shard-count` | unsigned integer | Active shard count after resolving `StorageShards`. |
| `store.resume.cpus` | array of unsigned integer | One entry per logical CPU, in ascending order. |
| `store.resume.sequences` | array of unsigned integer | Parallel to `store.resume.cpus`: for the CPU at the same index, the highest sequence contiguously accounted for after receipt/ring reconciliation, or 0. |
[*payload.startup-restart-is-true-when-the-boot-already-had-committed-rows-or-receipts]
[*payload.startup-shard-count-is-the-resolved-active-shard-count]
[*payload.startup-resume-cpus-and-sequences-give-each-cpus-highest-contiguous-sequence-in-cpu-order]

There is no boot ID in the payload: the record's own `event.boot.guid`
is the boot it describes.
[*payload.daemon-started-carries-no-boot-id-the-boot-is-event-boot-guid]

`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` [*payload.the-eventd-daemon-stopped-payload-schema]

| Field | Type | Contents |
|---|---|---|
| `store.committed.cpus` | array of unsigned integer | One entry per logical CPU, in ascending order. |
| `store.committed.sequences` | array of unsigned integer | Parallel to `store.committed.cpus`: the highest sequence contiguously covered by committed receipts for that CPU this boot, or 0 if none was. |
[*payload.shutdown-committed-cpus-and-sequences-give-each-cpus-highest-contiguous-receipted-sequence]

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.
[*payload.shutdown-leaves-both-arrays-out-when-coverage-cannot-be-read]

Diagnostic only. Startup derives recovery coverage from committed
receipt ranges, never from this payload (§2.2).
[*payload.startup-never-derives-recovery-coverage-from-the-shutdown-payload]

## 3.2.3 `eventd.events.lost` [*payload.the-eventd-events-lost-payload-schema]

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

[*payload.gap-buffer-cpu-is-the-ring-the-gap-was-found-on]
[*payload.gap-loss-sequence-is-the-first-missing-sequence]
[*payload.gap-loss-sequence-last-is-the-last-missing-sequence]
[*payload.gap-loss-count-is-how-many-sequences-are-missing]
[*payload.gap-loss-preceding-time-is-the-last-event-before-the-gap-or-absent]

The time of the event that revealed the gap is not a payload field: it
is the record's own `event.time` (§2.5).
[*payload.gap-event-time-is-the-revealing-events-timestamp]

The CPU appears both here, as `buffer.cpu`, and in the `cpu_id` column
(§2.5).
[*payload.a-gap-carries-its-cpu-as-buffer-cpu-and-in-the-column] 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.
<!-- lint-disable-next-line line-length -->
[*payload.an-event-cpu-predicate-matches-the-column-and-buffer-cpu-the-payload-field]

## 3.2.4 `eventd.config.changed` [*payload.the-eventd-config-changed-payload-schema]

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

[*payload.config-change-key-path-is-always-the-eventd-configuration-key]
[*payload.config-change-name-is-the-value-name-under-the-key-path]
[*payload.config-change-type-previous-is-the-reg-type-number-or-absent]
[*payload.config-change-value-previous-is-absent-when-no-value-was-stored]
[*payload.config-change-type-is-the-reg-type-number-or-absent]
[*payload.config-change-value-is-absent-when-the-change-removed-the-value]

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.
[*payload.config-values-are-integers]

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.
<!-- lint-disable-next-line line-length -->
[*payload.a-wrong-typed-value-reports-the-expected-type-and-the-integer-in-force]

## 3.2.5 `eventd.store.quarantined`

[*payload.the-eventd-store-quarantined-payload-schema]

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

[*payload.quarantine-store-kind-is-event-log-or-metric]
[*payload.quarantine-store-shard-is-present-only-for-the-event-store]
[*payload.quarantine-outcome-detail-is-a-human-readable-description]

`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_

> The event store directory — naming, creation, opening an active shard, quarantine and historical shards.

## 3.3.1 The event store directory

Every shard database and the metadata database live in one directory,
named by `EventStorePath` (§A).
<!-- lint-disable-next-line line-length -->
[*eventdb.shards-and-the-metadata-database-live-in-the-eventstorepath-directory]
There is no compiled-in default: a
missing or invalid value is a startup failure, and eventd writes event
databases nowhere else.
<!-- lint-disable-next-line line-length -->
[*eventdb.eventstorepath-has-no-default-and-a-missing-or-invalid-value-fails-startup]

The standard path is `/var/state/eventd/events/`.
<!-- lint-disable-next-line line-length -->
[*eventdb.the-standard-event-store-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.
<!-- lint-disable-next-line line-length -->
[*eventdb.the-state-directory-and-three-store-directories-are-required-peinit-provisioned-directories]
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:
<!-- lint-disable-next-line line-length -->
[*eventdb.store-directories-grant-full-control-only-to-system-administrators-and-eventds-service-sid]

```text
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.
<!-- lint-disable-next-line line-length -->
[*eventdb.eventd-never-creates-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.
<!-- lint-disable-next-line line-length -->
[*eventdb.store-files-are-handled-relative-to-a-directory-descriptor-opened-without-following-symlinks]
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.
<!-- lint-disable-next-line line-length -->
[*eventdb.a-missing-non-directory-symlinked-or-weakly-protected-store-path-fails-startup]
SQLite's database, `-wal`, and `-shm` files inherit the directory's
protection.
[*eventdb.database-wal-and-shm-files-inherit-the-directory-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).
[*eventdb.active-shards-are-named-by-a-four-digit-zero-padded-shard-index]

Starting with more shards than exist creates the new ones.
<!-- lint-disable-next-line line-length -->
[*eventdb.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.
<!-- lint-disable-next-line line-length -->
[*eventdb.starting-with-fewer-shards-keeps-the-excess-as-queryable-historical-shards]

## 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:
[*eventdb.a-shard-with-no-schema-is-created-as-new]

1. WAL mode, `PRAGMA journal_mode=WAL`
   [*eventdb.a-new-shard-is-created-in-wal-mode]
2. `PRAGMA synchronous=FULL`
   [*eventdb.a-new-shard-is-created-with-synchronous-full]
3. the `events`, `event_types`, `receipt_ranges`, and `metadata` tables
   (§3.1) [*eventdb.a-new-shard-is-created-with-all-four-tables]
4. the `idx_events_timestamp` index
   [*eventdb.a-new-shard-is-created-with-the-timestamp-index]
5. the `schema_version` and `created_at` entries
[*eventdb.a-new-shard-is-created-with-schema-version-and-created-at-entries]

## 3.3.4 Opening an active shard

1. Open in WAL mode. [*eventdb.an-active-shard-is-opened-in-wal-mode]
2. Set synchronous to FULL.
   [*eventdb.an-active-shard-is-opened-with-synchronous-full]
3. Read and verify `schema_version`. Missing or unrecognized is a
   **startup failure**. No migration is attempted.
[*eventdb.a-missing-or-unrecognised-active-shard-schema-version-fails-startup]
4. Verify structural integrity — the required tables and write-time
   indexes exist. Failing this, with SQLite reporting no corruption, is
   a **startup failure**.
   [*eventdb.an-active-shard-missing-required-tables-or-indexes-fails-startup]
5. If SQLite reports corruption while opening or verifying, quarantine
   and replace (below).
<!-- lint-disable-next-line line-length -->
   [*eventdb.corruption-reported-while-opening-an-active-shard-quarantines-and-replaces-it]
   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.
   [*eventdb.unrecognised-contents-are-quarantined]

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.
[*eventdb.a-corrupt-required-store-is-renamed-aside-and-replaced-at-its-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.
<!-- lint-disable-next-line line-length -->
[*eventdb.quarantine-gives-the-database-wal-and-shm-one-shared-corrupt-timestamp-suffix]

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.
<!-- lint-disable-next-line line-length -->
[*eventdb.a-taken-quarantine-name-gets-the-lowest-free-positive-integer-suffix]

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.
[*eventdb.a-corrupt-store-is-never-deleted-or-automatically-repaired]

The corruption is logged and an `eventd.store.quarantined` event is
emitted once a shard is available to write it to (§9.2).
<!-- lint-disable-next-line line-length -->
[*eventdb.quarantine-is-logged-and-emits-a-storage-error-event-once-a-shard-is-writable]

## 3.3.6 Historical shards

A historical shard is never required for startup.
<!-- lint-disable-next-line line-length -->
[*eventdb.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.
<!-- lint-disable-next-line line-length -->
[*eventdb.a-bad-historical-shard-is-logged-and-excluded-without-failing-startup-or-quarantine]

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.
[*eventdb.the-query-path-opens-every-valid-shard-file-whatever-their-number]

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.
[*eventdb.the-query-path-ignores-files-not-matching-the-shard-name-pattern]

Each is opened with a read-only connection.
<!-- lint-disable-next-line line-length -->
[*eventdb.the-query-path-opens-shards-with-read-only-connections] 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.
<!-- lint-disable-next-line line-length -->
[*eventdb.each-shard-has-exactly-one-read-write-connection-owned-by-its-writer]
WAL mode permits concurrent readers alongside one writer without
blocking either.

Writer threads never share connections.
<!-- lint-disable-next-line line-length -->
[*eventdb.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.
[*eventdb.a-writer-creates-and-owns-its-connection-for-the-process-lifetime]

---

# 3.4 Adaptive Indexing

_Peios / Reference / eventd / Event Storage_

> Which secondary indexes are worth their write cost depends on what a deployment queries — how eventd decides, converges, and sheds.

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.
<!-- lint-disable-next-line line-length -->
[*index.a-field-in-a-where-predicate-increments-its-counter-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.
<!-- lint-disable-next-line line-length -->
[*index.counters-are-flushed-periodically-to-the-metadata-database-never-a-shard]

**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.
<!-- lint-disable-next-line line-length -->
[*index.the-policy-computes-the-desired-set-as-fields-in-priority-order] 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.
<!-- lint-disable-next-line line-length -->
[*index.the-policy-runs-every-policy-interval-and-is-the-only-desired-set-writer]

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.
[*index.a-policy-run-reads-current-configuration-after-waking]

**Shard convergence.** Writer threads read the desired set and move
their material indexes toward it.
[*index.writer-threads-move-their-material-indexes-toward-the-desired-set]
They never read the counters and never
write the desired set.
[*index.writer-threads-never-read-counters-or-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.
[*index.the-desired-set-is-one-global-list-for-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).
<!-- lint-disable-next-line line-length -->
[*index.a-shard-is-quiet-with-no-pending-events-and-no-large-batch-in-the-shedding-window]
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.
[*index.an-idle-writer-takes-one-convergence-action-then-rechecks-pressure]

Creation uses `CREATE INDEX IF NOT EXISTS`; removal uses
`DROP INDEX IF EXISTS`.
<!-- lint-disable-next-line line-length -->
[*index.indexes-are-created-if-not-exists-and-dropped-if-exists] Both run on the shard's writer thread, which is
the only thread permitted to write that database (§2.3).
[*index.index-creation-and-removal-run-on-the-shards-writer-thread]

**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.
<!-- lint-disable-next-line line-length -->
[*index.rising-write-pressure-cancels-an-index-build-and-the-writer-returns-to-batches]
The abandoned build
is retried at the next quiet period.
<!-- lint-disable-next-line spelling -->
[*index.a-cancelled-index-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.
[*index.a-progress-handler-checks-for-cancellation-every-thousand-opcodes]

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.
<!-- lint-disable-next-line spelling -->
[*index.a-shard-under-sustained-pressure-may-lag-the-desired-set-indefinitely]

## 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.
[*index.too-many-large-batches-in-the-window-sheds-the-lowest-priority-index]
If pressure persists, the next-lowest goes, and so on.
<!-- lint-disable-next-line line-length -->
[*index.persistent-pressure-sheds-the-next-lowest-index-in-turn] The check runs
once per batch commit.
[*index.the-graduated-shedding-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.
<!-- lint-disable-next-line line-length -->
[*index.emergency-shedding-drops-every-secondary-index-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.
<!-- lint-disable-next-line line-length -->
[*index.ring-fill-above-emergency-shedding-buffer-percent-raises-the-pressure-signal]
It
is a distinct signal from the index-build cancellation one: this
triggers shedding whether or not a build is in progress.
[*index.emergency-shedding-triggers-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.
[*index.the-timestamp-index-is-never-shed]

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.
<!-- lint-disable-next-line line-length -->
[*index.shed-indexes-are-rebuilt-highest-priority-first-once-pressure-subsides]

## 3.4.4 Candidates

Any field that can appear in a `WHERE` predicate is a candidate.
[*index.any-field-usable-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.
[*index.the-candidate-header-columns]
`timestamp`, the column of `event.time`, is always indexed and is not
adaptively managed; a predicate on `event.time` is not counted.
[*index.the-timestamp-column-is-not-adaptively-managed]

**Payload fields.** Any queryable flattened path that appears in a
predicate is a candidate for an expression index.
[*index.a-queryable-flattened-payload-path-is-an-expression-index-candidate]
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.
[*index.a-suppressed-payload-path-never-receives-an-index]
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.
[*index.the-raw-payload-column-never-receives-a-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.
<!-- lint-disable-next-line line-length -->
[*index.a-payload-index-keys-each-row-on-a-deterministic-extraction-of-the-field]
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).
<!-- lint-disable-next-line line-length -->
[*index.payload-indexes-resolve-fields-as-the-query-language-does-and-otherwise-only-narrow-candidates]

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.
[*index.sqlite-comparison-never-substitutes-for-query-language-comparison]
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.
<!-- lint-disable-next-line line-length -->
[*index.rows-lacking-a-queryable-field-index-as-null-or-are-excluded-preserving-semantics]

Payload indexes are otherwise ordinary members of the desired set, with
the same priority ordering, shedding and convergence.
[*index.payload-indexes-are-ordinary-desired-set-members]

## 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`.
[*index.header-column-indexes-are-named-idx-events-column]

Payload expression indexes are named from the field GUID (§7.3), to
avoid both collisions and characters SQLite will not accept in an
identifier:

```text
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.
<!-- lint-disable-next-line line-length -->
[*index.payload-indexes-are-named-by-the-32-lowercase-hex-digit-field-guid] 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_

> The one database in the store that is not a shard — its tables, its concurrency, and why recovering it is cheap.

One database in the event store directory is not a shard:
`eventd-meta.db`.
<!-- lint-disable-next-line line-length -->
[*meta.eventd-meta-db-is-the-one-non-shard-database-in-the-event-store-directory]
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.
[*meta.the-metadata-database-survives-shard-reconfiguration-untouched]

It is created on first startup if absent or holding no schema, opened in WAL
mode with
`synchronous=NORMAL`.
[*meta.created-if-absent-and-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.
<!-- lint-disable-next-line line-length -->
[*meta.written-at-each-policy-run-including-config-changes-and-shutdown-and-read-at-startup]

The query path excludes it explicitly, since it is in the same directory
as the shards (§3.3).
[*meta.the-query-path-excludes-the-metadata-database]

## 3.5.1 Tables

**`index_counters`** — query frequency per field (§3.4).
[*meta.the-index-counters-table-holds-query-frequency-per-field]

| Column | Type | Contents |
|---|---|---|
| `field_path` | TEXT PRIMARY KEY | Header field or payload path: `event.type`, `access.granted`, `source.name`. A header field's column name written by an earlier eventd is read back as its path (§3.4). |
| `query_count` | INTEGER NOT NULL | Queries filtering on it within the current window. |
| `window_start` | INTEGER NOT NULL | When the window started, nanoseconds since the epoch. |
[*meta.index-counters-field-path-is-a-text-primary-key-naming-a-field-or-payload-path]
[*meta.index-counters-query-count-is-queries-filtering-on-the-field-in-the-current-window]
[*meta.index-counters-window-start-is-nanoseconds-since-the-epoch]

**`desired_indexes`** — the computed desired index set.
[*meta.the-desired-indexes-table-holds-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. |

[*meta.desired-indexes-field-path-is-a-text-primary-key]
[*meta.desired-indexes-priority-ranks-lower-values-as-higher-priority]
<!-- lint-disable-next-line line-length -->
[*meta.desired-indexes-is-expression-is-1-for-a-payload-expression-index-and-0-for-a-column-index]

**`sequence_checkpoints`** — diagnostic only.
[*meta.the-sequence-checkpoints-table-is-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. |

[*meta.sequence-checkpoints-boot-id-is-the-boot-the-checkpoint-applies-to]
[*meta.sequence-checkpoints-cpu-id-is-the-cpu-identifier]
<!-- lint-disable-next-line line-length -->
[*meta.sequence-checkpoints-sequence-is-the-last-committed-sequence-when-written]
[*meta.sequence-checkpoints-updated-at-is-when-the-checkpoint-was-written]

Primary key `(boot_id, cpu_id)`.
[*meta.sequence-checkpoints-primary-key-is-boot-id-and-cpu-id]
Startup recovery uses committed receipt
ranges and never this table (§2.2).
<!-- lint-disable-next-line line-length -->
[*meta.startup-recovery-never-uses-sequence-checkpoints] The table exists so that an operator
can see what eventd believed at shutdown and compare it with receipt
coverage — the two disagreeing is itself diagnostic.

**`meta`** — key-value. [*meta.the-meta-table-is-a-key-value-store]

| Column | Type | Contents |
|---|---|---|
| `key` | TEXT PRIMARY KEY | Metadata key. |
| `value` | BLOB NOT NULL | Strings as UTF-8 bytes, binary as raw bytes. |

[*meta.meta-key-is-a-text-primary-key]
[*meta.meta-values-store-strings-as-utf-8-and-binary-as-raw-bytes]

with two required entries: `schema_version` (§B) and `created_at` as a
UTC `YYYY-MM-DDTHH:MM:SSZ` string.
[*meta.meta-requires-schema-version-and-a-utc-created-at-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.
[*meta.no-access-control-state-is-stored-in-the-metadata-database]

## 3.5.2 Concurrency

One writer connection, owned by the index policy thread. No
other thread opens the database read-write.
[*meta.only-the-index-policy-thread-opens-the-database-read-write]

Query handlers write only to the in-memory counters; the policy thread
flushes them at each interval.
<!-- lint-disable-next-line line-length -->
[*meta.query-handlers-update-in-memory-counters-and-the-policy-thread-flushes-them-each-interval]
Writer threads and query handlers read
the desired sets from memory, never from the database.
<!-- lint-disable-next-line line-length -->
[*meta.writers-and-query-handlers-read-desired-sets-from-memory-not-the-database]

Graceful shutdown
writes `sequence_checkpoints` through the same connection, after policy
activity has stopped (§8.4).
<!-- lint-disable-next-line line-length -->
[*meta.graceful-shutdown-writes-sequence-checkpoints-after-policy-activity-stops]

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).
<!-- lint-disable-next-line line-length -->
[*meta.the-policy-thread-checkpoints-passively-at-walcheckpointpages-without-blocking]

## 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**.
[*meta.an-invalid-metadata-database-is-logged-and-recreated-from-defaults]

This is the opposite of the rule for a shard, which fails startup
(§3.3), and the difference is what is at stake. A shard holds the only
copy of audit data. This database holds an optimization policy and some
diagnostics — all of it reconstructible, none of it irreplaceable.
Losing it costs the adaptation eventd had accumulated, and the counters
begin refilling immediately. Security policy is unaffected because it
lives in the registry.

## 3.5.4 Startup

1. Open `eventd-meta.db`, creating it if absent.
   [*meta.startup-opens-eventd-meta-db-creating-it-if-absent]
2. Verify the schema version and required `meta` entries; recreate from
   defaults on failure.
   [*meta.startup-verifies-the-schema-version-and-required-meta-entries]
3. Load `index_counters` into memory.
   [*meta.startup-loads-index-counters-into-memory]
4. Load `desired_indexes` into memory.
   [*meta.startup-loads-desired-indexes-into-memory]
5. Load `sequence_checkpoints`, for diagnostics only.
   [*meta.startup-loads-sequence-checkpoints-for-diagnostics-only]
6. Discover the material indexes in each shard from its schema and
   compare against the desired set.
<!-- lint-disable-next-line line-length -->
   [*meta.startup-discovers-each-shards-material-indexes-and-compares-them-with-the-desired-set]

eventd resumes convergence from wherever each shard happens to be.
[*meta.index-convergence-resumes-from-each-shards-current-state] 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.
[*meta.no-index-is-dropped-or-rebuilt-at-startup]

---

# 3.6 Retention

_Peios / Reference / eventd / Event Storage_

> Bounding disk growth on two axes, age and size, with both enforced — how the pass runs and how space is reclaimed.

Retention bounds disk growth. eventd deletes on two axes, age and size,
and enforces both — an event goes when it exceeds either threshold.
<!-- lint-disable-next-line line-length -->
[*eventretain.an-event-is-deleted-when-it-exceeds-either-the-age-or-size-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.
<!-- lint-disable-next-line line-length -->
[*eventretain.events-older-than-eventretentiondays-by-the-wall-clock-are-deleted]
Each shard is processed independently, and the rule covers KMES
events, synthetic events and gap records alike.
<!-- lint-disable-next-line line-length -->
[*eventretain.age-retention-runs-per-shard-and-covers-kmes-synthetic-and-gap-records-alike]

## 3.6.2 Size

Size is measured as **logical live size**, not file size:

```text
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.
<!-- lint-disable-next-line line-length -->
[*eventretain.size-is-logical-live-size-measured-after-a-passive-checkpoint-attempt]
The event store's total is the sum across every shard.
[*eventretain.the-event-store-size-is-the-sum-across-every-shard]

Pages freed by retention do not count, because they are reusable by
future inserts.
[*eventretain.pages-freed-by-retention-do-not-count-toward-size]
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:
<!-- lint-disable-next-line line-length -->
[*eventretain.size-retention-runs-only-when-eventretentionmaxbytes-is-non-zero-and-exceeded]

1. Identify every non-current boot ID present in the shards.
<!-- lint-disable-next-line line-length -->
   [*eventretain.size-retention-considers-every-non-current-boot-id-in-the-shards]
2. Order them by their newest event timestamp, oldest boot first.
<!-- lint-disable-next-line line-length -->
   [*eventretain.non-current-boots-are-ordered-by-newest-event-timestamp-oldest-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.
<!-- lint-disable-next-line line-length -->
   [*eventretain.whole-non-current-boots-are-deleted-one-at-a-time-across-all-shards]
4. If still over, delete the oldest events of the **current** boot by
   timestamp, across all shards, until within the limit.
   [*eventretain.only-then-are-the-current-boots-oldest-events-deleted]

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).
[*eventretain.the-coordinator-processes-events-then-logs-then-metrics]
Each store is processed whether or not the one before it failed, and the
pass reports every store that did.
[*eventretain.a-store-whose-retention-fails-does-not-stop-the-others]
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.
[*eventretain.the-coordinator-runs-every-retentioncheckintervalminutes]
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.
[*eventretain.after-a-failed-pass-requested-passes-back-off]
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.
<!-- lint-disable-next-line line-length -->
[*eventretain.the-coordinator-measures-read-only-and-owns-read-write-connections-only-to-historical-shards]

Every other database has exactly one read-write connection, owned by its
ingestion writer.
<!-- lint-disable-next-line line-length -->
[*eventretain.every-database-but-a-historical-shard-has-one-read-write-connection-owned-by-its-ingestion-writer]
The coordinator submits low-priority maintenance
commands to that owner.
<!-- lint-disable-next-line line-length -->
[*eventretain.the-coordinator-submits-low-priority-commands-to-the-owning-writer]
A command runs only at a transaction boundary,
deletes at most `RetentionDeleteBatchRows`, and yields to ingestion
before another command runs.
<!-- lint-disable-next-line line-length -->
[*eventretain.a-command-runs-at-a-transaction-boundary-deletes-at-most-retentiondeletebatchrows-and-yields]
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.
<!-- lint-disable-next-line line-length spelling -->
[*eventretain.under-urgent-size-pressure-one-bounded-delete-may-join-an-open-ingestion-transaction]

The passive checkpoint attempted before a size measurement is also a
writer-owned command.
[*eventretain.the-pre-measurement-checkpoint-is-a-writer-owned-command]
The coordinator requests it, then reads the page
and freelist counts through its read-only connection.
<!-- lint-disable-next-line line-length -->
[*eventretain.the-coordinator-requests-the-checkpoint-then-reads-page-counts-read-only]
It never tries to
checkpoint through that connection or temporarily promotes it.
<!-- lint-disable-next-line line-length -->
[*eventretain.the-coordinator-never-checkpoints-through-or-promotes-its-read-only-connection]

There is no retention writer mutex and no second SQLite writer.
[*eventretain.there-is-no-retention-writer-mutex-and-no-second-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.
[*eventretain.eventd-never-runs-vacuum-automatically]
Reclamation is an explicit
administrative operation.
[*eventretain.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 stored record carries a boot_id — what it is for, where it is stored, how uniqueness is assured, and how a boundary is detected.

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.
<!-- lint-disable-next-line line-length -->
[*bootpart.every-stored-event-log-line-and-raw-metric-sample-carries-a-boot-id]
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.
<!-- lint-disable-next-line line-length -->
[*bootpart.the-boot-id-is-read-from-proc-at-startup-validated-and-stored-as-a-pcds-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 |

[*bootpart.every-events-row-carries-a-boot-id]
[*bootpart.every-logs-row-carries-a-boot-id]
[*bootpart.every-samples-row-carries-a-boot-id]

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).
<!-- lint-disable-next-line line-length -->
[*bootpart.the-boot-id-is-recorded-per-sample-but-is-not-part-of-series-identity]
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)`.
[*bootpart.cpu-id-and-sequence-identify-an-event-within-one-boot]
Across boots, `boot_id` supplies the
disambiguating dimension, and the triple
`(boot_id, cpu_id, sequence)` is globally unique.
[*bootpart.the-boot-id-cpu-id-and-sequence-triple-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.
<!-- lint-disable-next-line line-length -->
[*bootpart.startup-searches-every-readable-shard-including-historical-ones-for-the-current-boot-id]

**No committed rows or receipts for this boot.** This is the boot's
first successful eventd start.
[*bootpart.no-committed-rows-or-receipts-for-the-boot-means-a-first-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.
<!-- lint-disable-next-line line-length -->
[*bootpart.a-first-start-covers-from-before-sequence-1-writes-the-new-boot-id-and-emits-restart-false]

**Committed rows or receipts exist.** eventd was previously ready in the
same boot.
[*bootpart.committed-rows-or-receipts-for-the-boot-mean-a-restart]
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.
<!-- lint-disable-next-line line-length -->
[*bootpart.a-restart-merges-and-reconciles-coverage-keeps-the-boot-id-and-emits-restart-true]

The two cases are distinguished by the data itself rather than by any
flag eventd persisted.
<!-- lint-disable-next-line line-length -->
[*bootpart.first-start-and-restart-are-distinguished-by-stored-data-not-a-persisted-flag]
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.
[*bootpart.committed-receipt-ranges-are-the-sequence-authority]
Committed event
rows still establish that eventd previously ran when no receipt was yet
needed.
[*bootpart.committed-event-rows-alone-establish-a-previous-run]
The metadata database's sequence checkpoints and the previous
`eventd.daemon.stopped` payload are diagnostic — neither is consulted for
recovery (§2.2, §3.5).
<!-- lint-disable-next-line line-length -->
[*bootpart.sequence-checkpoints-and-the-previous-shutdown-payload-are-not-consulted-for-recovery]

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 the log socket and writes the store, independent of the event path — batching, durability and what it adds to a record.

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.
<!-- lint-disable-next-line line-length -->
[*logwriter.the-log-thread-is-independent-of-the-event-drain-and-writer-threads]

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

[*logwriter.one-thread-does-both-the-socket-reads-and-the-sqlite-writes]

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.
[*logwriter.the-socket-is-not-drained-during-a-batch-commit]
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.
<!-- lint-disable-next-line line-length -->
[*logwriter.a-full-receive-queue-of-max-dgram-qlen-datagrams-refuses-further-sends]
eventd sets `SO_RCVBUF` to four times the datagram ceiling,
[*logwriter.so-rcvbuf-is-sized-at-four-times-the-datagram-ceiling]
but for this socket type the kernel charges a queued datagram to its
sender's send buffer, and the receive buffer bounds nothing.

> [!NOTE]
> Linux's default `net.unix.max_dgram_qlen` is ten, and the kernel
> refuses a send only once more than that many are queued, so the queue
> holds eleven datagrams. A batch commit takes one to ten milliseconds,
> and those eleven are the only thing absorbing arrivals in the window. A
service dumping a stack trace
> through non-blocking sends will have datagrams refused, which is the
> intended degradation for a loss-tolerant path (PSPU §3.4): whatever is
> lost is lost in the sender, and eventd neither buffers beyond the
> queue nor learns of the refusal.

Splitting into a reader and a writer with a bounded handoff — the shape
the event path uses (§2.3) — would decouple them. It is not done, and
the reasoning is that log loss is tolerable by design (PSPU §3.4), log
volume is normally well below event volume, and the single-thread model
avoids a handoff channel and its backpressure semantics entirely.

Where log throughput does become the constraint, sharding the log store
the way the event store is sharded is the larger lever; splitting the
thread only moves the stall.

## 4.1.2 Batching

The writer batches on the same adaptive principle as the event writer
(§2.4), with the socket receive queue as its input. A transaction opens
when the first valid record is available and commits when any of these
holds:
<!-- lint-disable-next-line line-length -->
[*logwriter.a-transaction-opens-at-the-first-valid-record-and-commits-on-any-of-three-conditions]

- no further datagram is immediately available in the receive queue
[*logwriter.a-batch-commits-when-no-further-datagram-is-immediately-available]
- the batch holds `LogMaxBatchSize` records
  [*logwriter.a-batch-commits-when-it-holds-logmaxbatchsize-records]
- `LogMaxBatchLatencyMs` has elapsed since the first record entered it
<!-- lint-disable-next-line line-length -->
  [*logwriter.a-batch-commits-when-logmaxbatchlatencyms-has-elapsed-since-its-first-record]

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.
<!-- lint-disable-next-line line-length -->
[*logwriter.a-datagram-that-overflows-the-batch-continues-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.
<!-- lint-disable-next-line line-length -->
[*logwriter.a-transaction-never-exceeds-the-size-cap-or-outlives-the-latency-cap]

The defaults (§A) are 5000 records and 500 milliseconds.
[*logwriter.the-batch-defaults-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.
[*logwriter.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).
<!-- lint-disable-next-line line-length -->
[*logwriter.a-new-origin-is-inserted-into-log-origins-in-the-same-transaction-as-its-first-row]

A transaction-local pending set ensures that insert runs only once per
new origin in a batch.
[*logwriter.the-origin-insert-runs-once-per-new-origin-per-batch]
The main in-memory set is updated only after
commit and the pending set is discarded on rollback.
<!-- lint-disable-next-line line-length -->
[*logwriter.the-origin-cache-is-updated-only-after-commit-and-pending-origins-are-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.
[*logwriter.the-log-store-runs-in-wal-mode-with-synchronous-normal]

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.
<!-- lint-disable-next-line line-length -->
[*logwriter.log-commits-survive-a-process-crash-but-not-necessarily-a-power-loss]

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.
<!-- lint-disable-next-line line-length -->
[*logwriter.eventd-supplies-the-boot-id-and-a-receipt-timestamp-when-none-was-given]
Everything else is stored as
given — `message` byte for byte (PSPU §3.8).
[*logwriter.everything-else-is-stored-as-given-with-message-byte-for-byte]

## 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.
<!-- lint-disable-next-line line-length -->
[*logwriter.a-record-with-an-invalid-origin-is-discarded-before-it-joins-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`.
<!-- lint-disable-next-line line-length -->
[*logwriter.discards-are-counted-and-the-last-rejected-origin-is-kept-escaped-and-truncated-to-64-characters]

It also writes one line to standard error on the first discard and at
most one a minute after that.
<!-- lint-disable-next-line line-length -->
[*logwriter.a-discard-is-reported-on-stderr-at-the-first-occurrence-then-at-most-once-a-minute]
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.
<!-- lint-disable-next-line line-length -->
[*logwriter.the-stderr-report-is-stored-as-a-log-record-under-the-origin-eventd]

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_

> A single database rather than a directory of shards, its schema, its write-time indexes, and why there is no adaptive indexing here.

The log store is a single SQLite database — not a directory of shards.
[*logs.the-log-store-is-a-single-unsharded-database]
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.
[*logs.the-log-store-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. |

[*logs.id-is-a-monotonic-rowid-primary-key]
[*logs.boot-id-is-a-16-byte-guid-in-pcds-binary-layout]
<!-- lint-disable-next-line line-length -->
[*logs.timestamp-is-epoch-nanoseconds-from-the-producer-or-eventds-receipt-clock]
[*logs.origin-is-the-producer-peinit-associated-with-the-output-pipe]
[*logs.is-error-is-1-for-standard-error-or-an-explicitly-marked-error]
[*logs.message-is-the-non-null-log-text]
[*logs.job-id-is-a-16-byte-correlation-guid-or-null]

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.
[*logs.a-log-record-has-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).
<!-- lint-disable-next-line line-length -->
[*logs.origin-is-broker-attested-because-the-log-socket-admits-peinit-and-excludes-service-logon-tokens]
The optional correlation key is not an identity.

## 4.2.1 What an origin looks like [*logs.the-origin-grammar]

An origin is one or two components (PSPU §3.7):

```text
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.
[*logs.a-one-component-origin-names-a-service-and-its-main-process]
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).
[*logs.a-two-component-origin-names-a-producer-within-a-service]
The bracketed
index appears only after a slash, and there is never more than one
slash.
<!-- lint-disable-next-line line-length -->
[*logs.a-bracketed-index-appears-only-after-the-slash-and-there-is-at-most-one-slash]

Ingestion discards a record whose origin is anything else, before the
record reaches a batch (§4.1).
[*logs.a-record-whose-origin-is-outside-the-grammar-is-discarded]
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).
[*logs.an-origin-never-accepts-a-wildcard-backslash-quote-or-whitespace]

A program needing more structure than this emits events.

## 4.2.2 The origin catalog

`log_origins` has one column, `origin TEXT PRIMARY KEY`.
[*logs.log-origins-has-a-single-origin-text-primary-key-column]
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.
[*logs.every-committed-log-row-is-discoverable-immediately]

Query planning enumerates origins from this compact catalog rather than
running `DISTINCT origin` over the retained log rows (§6.1).
<!-- lint-disable-next-line spelling -->
[*logs.query-planning-enumerates-origins-from-the-catalogue-not-the-log-rows]

Catalog entries deliberately survive ordinary retention.
<!-- lint-disable-next-line spelling -->
[*logs.catalogue-entries-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.
<!-- lint-disable-next-line spelling -->
[*logs.maintenance-may-remove-an-unreferenced-origin-through-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.
<!-- lint-disable-next-line line-length -->
[*logs.origin-removal-rechecks-not-exists-and-updates-the-cache-only-after-commit]

Catalog pages count toward logical live size.
<!-- lint-disable-next-line spelling -->
[*logs.catalogue-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).
[*logs.is-error-is-queried-as-a-boolean-accepting-true-or-1]
`ERROR ONLY` is sugar for the first.
[*logs.error-only-is-sugar-for-is-error-equals-true]

## 4.2.4 Write-time indexes

Three indexes are created with the table:
[*logs.three-write-time-indexes-are-created-with-the-table]

- `idx_logs_timestamp` on `logs(timestamp)` — time-range filtering, as
  everywhere.
  [*logs.idx-logs-timestamp-indexes-the-timestamp]
- `idx_logs_origin` on `logs(origin)` — "show me logs from X", which is
  the dominant log query.
  [*logs.idx-logs-origin-indexes-the-origin]
- `idx_logs_job_id` on `logs(job_id) WHERE job_id IS NOT NULL` — a
  partial index for "show me logs for job X".
  [*logs.idx-logs-job-id-is-a-partial-index-on-non-null-job-ids]
  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

[*logs.the-log-store-does-not-participate-in-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).
[*logs.log-queries-do-not-increment-query-frequency-counters]

## 4.2.6 Schema version

The log store holds a `metadata` table with the same two-column
structure as a shard's (§3.1).
[*logs.the-log-store-metadata-table-has-a-shards-two-column-structure]
Schema version 1 comprises `logs`,
`log_origins`, and `metadata`; its version number is in §B.
[*logs.log-store-schema-version-1-comprises-logs-log-origins-and-metadata]

eventd checks it at startup and applies the lifecycle rules of §4.3,
and does not migrate.
[*logs.the-log-store-schema-is-checked-at-startup-and-never-migrated]

---

# 4.3 Database Lifecycle

_Peios / Reference / eventd / Log Storage_

> The log store directory and fixed database file — its creation, opening, concurrency, and checkpointing.

## 4.3.1 Path

`LogStorePath` (§A) names a provisioned directory, conventionally
`/var/state/eventd/logs`.
[*logdb.logstorepath-names-a-provisioned-directory]
The database itself has the fixed name
`logs.db` inside it.
[*logdb.the-log-database-file-is-named-logs-db]
A missing, invalid, or unsafe directory is a startup
failure.
[*logdb.a-missing-invalid-or-unsafe-log-store-directory-fails-startup]

The directory has the provisioning, descriptor, and path-resolution
requirements defined for the event store (§3.3).
[*logdb.the-log-store-directory-has-the-event-store-directory-requirements]
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.
<!-- lint-disable-next-line line-length -->
[*logdb.the-directory-is-never-created-symlinks-are-never-followed-and-the-database-is-opened-handle-relative]

## 4.3.2 Creation [*logdb.a-log-store-that-does-not-exist-is-created]

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:
[*logdb.a-log-store-with-no-schema-is-created-as-new]

1. WAL mode, `PRAGMA journal_mode=WAL`
   [*logdb.creation-sets-wal-journal-mode]
2. `PRAGMA synchronous=NORMAL`
   [*logdb.creation-sets-synchronous-normal]
3. the `logs`, `log_origins`, and `metadata` tables (§4.2)
   [*logdb.creation-creates-the-logs-log-origins-and-metadata-tables]
4. the `idx_logs_timestamp`, `idx_logs_origin`, and `idx_logs_job_id`
   indexes
   [*logdb.creation-creates-the-three-write-time-indexes]
5. the `schema_version` and `created_at` entries
   [*logdb.creation-writes-the-schema-version-and-created-at-entries]

## 4.3.3 Opening

1. Open in WAL mode.
   [*logdb.opening-uses-wal-mode]
2. Set synchronous to NORMAL.
   [*logdb.opening-sets-synchronous-normal]
3. Verify the schema version. Missing or unrecognized is a **startup
   failure**; no migration is attempted.
<!-- lint-disable-next-line line-length -->
   [*logdb.a-missing-or-unrecognised-schema-version-fails-startup-without-migration]
4. Verify structural integrity — required tables and indexes present.
   Failing this, with SQLite reporting no corruption, is a **startup
   failure**.
   [*logdb.missing-tables-or-indexes-without-reported-corruption-fail-startup]
5. On SQLite reporting corruption, quarantine and replace.
   [*logdb.a-corrupt-log-store-is-quarantined-and-replaced]
   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.
   [*logdb.unrecognised-contents-are-quarantined]

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.
<!-- lint-disable-next-line line-length -->
[*logdb.quarantine-renames-all-three-files-with-a-shared-corrupt-suffix-and-creates-a-fresh-store]

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.
[*logdb.the-log-store-is-required-and-eventd-never-runs-without-one]

## 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.
<!-- lint-disable-next-line line-length -->
[*logdb.one-read-write-connection-owned-by-the-log-writer-and-any-number-of-read-only-ones]
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).
<!-- lint-disable-next-line line-length spelling -->
[*logdb.retention-and-catalogue-cleanup-go-through-the-writer-and-never-open-a-read-write-connection]

## 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.
<!-- lint-disable-next-line line-length -->
[*logdb.the-log-writer-checkpoints-passively-at-walcheckpointpages-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, on the same thread, with a shorter default and its own reclamation.

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.
<!-- lint-disable-next-line line-length -->
[*logretain.log-retention-runs-on-the-retention-thread-after-events-and-before-metrics]
As there, the model is an early simplification and both
limits are enforced with the more aggressive one winning.
[*logretain.both-log-limits-are-enforced-and-the-more-aggressive-one-wins]

## 4.4.1 Age and size

Rows older than `LogRetentionDays` (§A) are deleted from `logs` until
none remain.
[*logretain.logs-older-than-logretentiondays-are-deleted]

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.
<!-- lint-disable-next-line line-length -->
[*logretain.over-a-non-zero-logretentionmaxbytes-the-oldest-logs-by-timestamp-are-deleted]
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.
<!-- lint-disable-next-line line-length -->
[*logretain.log-size-is-logical-live-size-after-a-passive-checkpoint-attempt-excluding-freed-pages]

There is no boot-boundary preference here.
[*logretain.log-size-retention-has-no-boot-boundary-preference]
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).
[*logretain.the-default-log-retention-is-fourteen-days]

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.
<!-- lint-disable-next-line line-length -->
[*logretain.log-retention-plans-read-only-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.
<!-- lint-disable-next-line line-length -->
[*logretain.each-log-retention-transaction-deletes-at-most-retentiondeletebatchrows-then-ingestion-is-rechecked]
Under urgent size pressure the writer can
append one bounded delete to a transaction already open.
<!-- lint-disable-next-line line-length spelling -->
[*logretain.under-urgent-size-pressure-one-bounded-delete-may-join-an-open-transaction]
Retention
never takes a writer mutex or opens a second read-write connection
(§3.6).
<!-- lint-disable-next-line line-length -->
[*logretain.log-retention-takes-no-writer-mutex-and-opens-no-second-read-write-connection]

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.
[*logretain.vacuum-is-never-run-automatically-on-the-log-store]
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 the metric socket and writes samples — processing a record, out-of-order samples, batching, and durability.

One thread reads datagrams from the metric socket and writes samples to
the metric store, independent of both the event and log paths.
<!-- lint-disable-next-line line-length -->
[*metricwriter.one-thread-reads-the-metric-socket-and-writes-samples-independently] It has
the same single-thread shape as the log writer, with the same
consequence during a commit (§4.1).

The wire contract is PSPU §3.9 to §3.13. The same thread also writes
eventd's own health samples, which skip step 1 below (§5.7).

## 5.1.1 Processing a record

For each valid record:

1. **Authorize the name.** The datagram's KACS token must hold
   `EVENTD_PUBLISH` on the resolved metric-name descriptor (§7.6).
<!-- lint-disable-next-line line-length -->
   [*metricwriter.the-token-must-hold-eventd-publish-on-the-metric-name-descriptor]
2. **Resolve the series** from name and labels — and, for a histogram,
   bucket boundaries — through the in-memory series cache (§5.3).
<!-- lint-disable-next-line line-length -->
   [*metricwriter.the-series-is-resolved-from-name-labels-and-histogram-boundaries] A
   series that does not exist is inserted into `series` with the
   record's type, and the cache is updated.
[*metricwriter.a-missing-series-is-inserted-with-the-records-type-and-cached]
3. **Check the type.** If the record's type differs from the resolved
   series' type, the record is dropped without replying to the producer.
   [*metricwriter.a-type-mismatch-drops-the-record-without-replying]
   The type is set at creation and is immutable; a series never changes
   type. [*metricwriter.a-series-type-is-fixed-at-creation-and-never-changes]
4. **Insert the sample** into `samples` with the resolved `series_id`,
   the timestamp and the value.
[*metricwriter.the-sample-is-inserted-with-its-series-id-timestamp-and-value]
   SQLite assigns `samples.id`, which is
   the deterministic tiebreaker among samples sharing a timestamp
   (§5.2).
   [*metricwriter.sqlite-assigns-the-sample-id-that-breaks-timestamp-ties] A
   histogram's data is encoded as the canonical MessagePack
   sample map and stored in `histogram_data`.
[*metricwriter.histogram-data-is-stored-as-a-canonical-messagepack-sample-map]

The transaction result counts step-3 failures and carries the most recent
conflict's metric name and expected and received types.
<!-- lint-disable-next-line line-length -->
[*metricwriter.the-transaction-result-counts-type-mismatches-and-carries-the-latest-conflict]
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.
<!-- lint-disable-next-line line-length -->
[*metricwriter.mismatches-accumulate-in-a-diagnostic-total-and-warn-at-most-once-per-minute]
`SIGQUIT` includes both the total and latest conflict (§8.5).
[*metricwriter.sigquit-reports-the-mismatch-total-and-latest-conflict]

There is still no response to the producer and no event per failure.
[*metricwriter.a-type-mismatch-produces-no-response-and-no-event]
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.
<!-- lint-disable-next-line line-length -->
[*metricwriter.a-mismatch-free-transaction-does-no-diagnostic-allocation-or-synchronization]

## 5.1.2 Out-of-order samples

[*metricwriter.a-sample-older-than-stored-samples-is-accepted]

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.
<!-- lint-disable-next-line line-length -->
[*metricwriter.batching-uses-the-shared-adaptive-algorithm-over-the-socket-receive-queue]
A transaction opens at the first
valid sample and commits when any of these holds:

- no further datagram is immediately available
  [*metricwriter.a-batch-commits-when-no-datagram-is-immediately-available]
- the batch holds `MetricMaxBatchSize` samples
  [*metricwriter.a-batch-commits-at-metricmaxbatchsize-samples]
- `MetricMaxBatchLatencyMs` has elapsed since the first sample entered
  it
<!-- lint-disable-next-line line-length -->
  [*metricwriter.a-batch-commits-when-metricmaxbatchlatencyms-has-elapsed-since-its-first-sample]

A datagram yielding more samples than fit is split across transactions,
the writer committing before continuing with the same datagram.
[*metricwriter.a-datagram-that-overflows-a-batch-is-split-across-transactions]
Neither
cap is ever exceeded. [*metricwriter.neither-batch-cap-is-ever-exceeded]

The defaults (§A) are 5000 samples and 1000 milliseconds — the longest
latency of the three writers.
[*metricwriter.the-batch-defaults-are-5000-samples-and-1000-milliseconds]
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).
[*metricwriter.metric-writes-use-wal-with-synchronous-normal] 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 organized around series rather than records — the series table, the canonical label string and the boundaries blob.

The metric store is a single SQLite database, and unlike the event and
log stores it is organized around **series** rather than records.
<!-- lint-disable-next-line spelling -->
[*series.the-metric-store-is-one-sqlite-database-organised-around-series]
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. |

[*series.series-id-is-the-integer-primary-key-samples-reference]
[*series.series-name-is-the-metric-name]
[*series.series-labels-is-the-canonical-label-string-empty-for-no-labels]
[*series.series-type-is-0-counter-1-gauge-2-histogram]
[*series.series-label-hash-hashes-the-canonical-label-string]
<!-- lint-disable-next-line line-length -->
[*series.series-boundaries-hash-hashes-the-boundary-blob-and-is-null-for-counters-and-gauges]
<!-- lint-disable-next-line line-length -->
[*series.series-boundaries-holds-the-boundary-blob-and-is-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`.
<!-- lint-disable-next-line line-length -->
[*series.canonical-labels-are-key-sorted-by-utf-8-bytes-and-comma-joined-as-key-value-pairs]
The empty label set is the empty string.
[*series.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).
[*series.the-canonical-label-string-is-not-escaped] That prohibition
exists precisely to make this encoding unambiguous, and it is the reason
the constraint binds the producer rather than being handled internally.

### 5.2.1.2 The boundaries blob

A fixed binary encoding, not MessagePack:

1. `boundary_count`, `u32` little-endian
   [*series.the-boundary-blob-starts-with-a-u32-little-endian-count]
2. that many IEEE-754 `f64` values, each little-endian, in the validated
   order the producer sent
<!-- lint-disable-next-line line-length -->
   [*series.the-boundary-blob-then-holds-little-endian-f64-values-in-producer-order]

It exists only to identify histogram series and to resolve hash
collisions, and is never returned in a query result.
[*series.the-boundary-blob-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`.
[*series.series-hashes-are-64-bit-fnv-1a-over-the-canonical-bytes]
The high bit is cleared
before storage, `hash & 0x7FFF_FFFF_FFFF_FFFF`, so the value always fits
SQLite's signed `INTEGER`.
[*series.the-hash-high-bit-is-cleared-before-storage]

A lookup always verifies the full `labels` string, and for a histogram
the full `boundaries` blob, after narrowing by hash.
<!-- lint-disable-next-line line-length -->
[*series.a-lookup-verifies-the-full-labels-and-boundaries-after-narrowing-by-hash]
A hash is an index
key, never an identity: two label sets that collide are still two
series. [*series.colliding-label-sets-are-still-distinct-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.
[*series.the-series-table-is-unique-on-name-labels-and-boundaries]

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.
<!-- lint-disable-next-line line-length -->
[*series.counter-and-gauge-uniqueness-rests-on-single-writer-resolution-not-the-constraint]
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.
[*series.type-is-not-part-of-series-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

| Column | Type | Contents |
|---|---|---|
| `id` | INTEGER PRIMARY KEY | Internal row identifier; the tiebreaker for samples sharing a series and timestamp. |
| `series_id` | INTEGER NOT NULL | References `series(id)`. |
| `boot_id` | BLOB NOT NULL | 16-byte boot ID GUID. |
| `timestamp` | INTEGER NOT NULL | Nanoseconds since the Unix epoch. |
| `value` | REAL NOT NULL | The raw value for counters and gauges. Stores 0 for histograms. |
| `histogram_data` | BLOB | Canonical MessagePack histogram sample map. Null for counters and gauges. |
[*series.samples-id-breaks-ties-between-samples-sharing-a-series-and-timestamp]
[*series.samples-series-id-references-series-id]
[*series.samples-boot-id-is-a-16-byte-boot-id-guid]
[*series.samples-timestamp-is-nanoseconds-since-the-unix-epoch]
[*series.samples-value-is-the-raw-value-or-0-for-histograms]
[*series.samples-histogram-data-is-the-sample-map-and-null-for-counters-and-gauges]

For a histogram, `histogram_data` is a canonical MessagePack map
(PSPU §3.5) with exactly four keys: `boundaries`, an array of `float64`
in the producer's order; `counts`, an array of unsigned integers;
`total_count`; and `sum`, a finite `float64`.
<!-- lint-disable-next-line line-length -->
[*series.the-histogram-sample-map-has-exactly-boundaries-counts-total-count-and-sum]

`value` is a placeholder for histogram rows and is never returned as a
metric query value.
[*series.a-histogram-rows-value-is-never-returned-as-a-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.
[*series.equal-histogram-samples-encode-to-identical-bytes]

`boot_id` is per sample and is not part of the series identity, so a
series stays continuous across a reboot (§3.7).
[*series.boot-id-is-per-sample-so-a-series-continues-across-reboots]

## 5.2.3 Ordering

Query execution order within a series is always `(timestamp, id)`
ascending, never insertion order alone.
[*series.samples-in-a-series-are-ordered-by-timestamp-then-id-ascending]
Duplicate timestamps are
permitted and `id` gives them a stable order.
[*series.duplicate-timestamps-are-permitted]

`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).
<!-- lint-disable-next-line line-length -->
[*series.the-sample-id-is-never-exposed-as-a-query-result-access-control-or-label-field]

## 5.2.4 Write-time indexes

- `idx_samples_series_timestamp` on `samples(series_id, timestamp, id)`
  — the dominant pattern is "samples for series X over range Y in
  deterministic order", and this one composite index serves the series
  lookup, the range filter and the `(timestamp, id)` ordering in a
  single scan.
  [*series.idx-samples-series-timestamp-indexes-series-id-timestamp-and-id]
- `idx_series_name` on `series(name)` — name lookups.
  [*series.idx-series-name-indexes-series-by-name]
- `idx_series_label_hash` on `series(label_hash)` — series resolution on
  the ingestion path.
  [*series.idx-series-label-hash-indexes-series-by-label-hash]
- `idx_series_boundaries_hash` on `series(boundaries_hash)` — narrowing
  a histogram's lookup by its boundary hash.
  [*series.idx-series-boundaries-hash-indexes-series-by-boundaries-hash]

## 5.2.5 Schema version

A `metadata` table with the same structure as the other stores' (§3.1).
[*series.the-metric-store-has-a-metadata-table-shaped-like-the-other-stores]
Version 1 comprises `series`, `samples`, and `metadata`.
[*series.schema-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. [*series.schema-version-2-adds-only-the-rollups-cache]
Version 3 changes only the series table's uniqueness, from the boundary
hash to the full boundary blob, and adds `idx_series_boundaries_hash`.
[*series.schema-version-3-makes-series-unique-on-the-full-boundary-blob]
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_

> Turning each arriving sample into a series_id once, on the single ingestion thread — the cache, and how to size it.

Every arriving sample must be turned into a `series_id` before it can be
inserted. [*resolve.every-sample-is-resolved-to-a-series-id-before-insertion]
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.
[*resolve.resolution-runs-once-per-sample-on-the-metric-ingestion-thread]

## 5.3.1 Resolving

1. Compute the canonical label string: sort by key in unsigned UTF-8
   byte order, encode each pair `key=value`, join with commas. The empty
   label set encodes as the empty string. No escaping — ingestion has
   already rejected the delimiters (§5.2).
   [*resolve.first-the-canonical-label-string-is-computed]
2. Hash it. [*resolve.then-the-canonical-label-string-is-hashed]
3. For a histogram, compute the canonical boundary blob and its hash
   from the **validated, producer-supplied order**.
[*resolve.a-histograms-boundary-blob-and-hash-use-the-producer-supplied-order]
   eventd never sorts
   boundaries. [*resolve.eventd-never-sorts-histogram-boundaries]
   For counters and gauges both are null.
   [*resolve.counters-and-gauges-have-a-null-boundary-blob-and-hash]
4. Look up `series` by `name`, `label_hash`, and for histograms
   `boundaries_hash`.
   [*resolve.lookup-is-by-name-label-hash-and-for-histograms-boundaries-hash]
5. On a match, verify the full `labels` string, and for histograms the
   full boundary blob.
[*resolve.a-hash-match-is-verified-against-the-full-labels-and-boundary-blob]
   If the record's type differs from the existing
   series' type, drop the record (§5.1).
   [*resolve.a-type-mismatch-with-the-matched-series-drops-the-record]
   Otherwise use the existing
   `series_id`. [*resolve.a-verified-match-reuses-the-existing-series-id]
6. On no match, insert a new `series` row and use the new identifier.
   [*resolve.no-match-inserts-a-new-series-row]

A histogram whose boundaries changed takes step 6: it is a new series
(PSPU §3.13).
[*resolve.a-histogram-with-changed-boundaries-is-a-new-series]
The old one keeps its historical samples and the new one
starts accumulating.
[*resolve.the-old-histogram-series-keeps-its-historical-samples]

## 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.
[*resolve.the-series-cache-maps-name-labels-and-boundaries-to-series-id]

A hit is a hash table lookup with no SQLite involvement.
[*resolve.a-cache-hit-does-not-touch-sqlite] A miss costs
one `SELECT` on `name` and `label_hash`, after which the result is
<!-- lint-disable-next-line spelling -->
inserted, evicting the least-recently-used entry if the cache is full.
[*resolve.a-cache-miss-costs-one-select-and-evicts-the-lru-entry-when-full]

The bound is `MetricSeriesCacheSize` (§A), default 50000, with LRU
eviction.
[*resolve.the-cache-is-bounded-by-metricseriescachesize-default-50000]
It bounds **memory**, not the number of series: the `series`
table is uncapped and a new series is always created in the database.
[*resolve.a-full-cache-never-prevents-series-creation]
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. [*resolve.the-cache-starts-empty-and-warms-on-demand]
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.
[*resolve.there-is-no-cache-pre-warming-pass]

## 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 `SELECT`s every cycle, permanently. A system with 55000 active
series and a 50000-entry cache incurs about 5000 cache misses every
fifteen seconds, indefinitely.
[*resolve.an-undersized-cache-reloads-the-overflow-every-collection-cycle]

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).
[*resolve.eventd-does-not-cap-series-creation] 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_

> The metric store file — its path, creation, opening, concurrency, and checkpointing.

## 5.4.1 Path

`MetricStorePath` (§A) names a provisioned directory, conventionally
`/var/state/eventd/metrics`.
[*metricdb.metricstorepath-names-the-metric-store-directory]
The database itself has the fixed name
`metrics.db` inside it. [*metricdb.the-database-file-is-named-metrics-db]
A missing, invalid, or unsafe directory is a
startup failure.
[*metricdb.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).
[*metricdb.the-directory-has-the-event-store-directory-requirements]
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.
<!-- lint-disable-next-line line-length -->
[*metricdb.the-directory-is-never-created-or-traversed-through-symlinks-and-the-database-opens-relative-to-its-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:
[*metricdb.a-metric-store-with-no-schema-is-created-as-new]

1. WAL mode. [*metricdb.a-new-store-is-created-in-wal-mode]
2. `PRAGMA synchronous=NORMAL` — the log store's reasoning, for the same
   reason: metric loss on power failure is acceptable (§4.1).
   [*metricdb.a-new-store-sets-synchronous-normal]
3. The `series`, `samples`, `rollups`, and `metadata` tables (§5.2, §5.6).
[*metricdb.a-new-store-creates-the-series-samples-rollups-and-metadata-tables]
4. Every write-time index.
   [*metricdb.a-new-store-creates-every-write-time-index]
5. The `schema_version` and `created_at` entries.
   [*metricdb.a-new-store-records-schema-version-and-created-at]

## 5.4.3 Opening

1. Open in WAL mode with synchronous NORMAL.
   [*metricdb.an-existing-store-opens-in-wal-mode-with-synchronous-normal]
2. Verify the schema version.
   [*metricdb.opening-verifies-the-schema-version]
   Version 1 is migrated transactionally to version
   2 by adding the adaptive-rollup cache.
   [*metricdb.a-version-1-store-is-migrated-transactionally-to-version-2]
   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.
   [*metricdb.a-version-2-store-is-migrated-transactionally-to-version-3]
   Missing or unrecognized versions are
   a **startup failure**.
   [*metricdb.a-missing-or-unrecognised-schema-version-is-a-startup-failure]
3. Verify structural integrity — required tables and indexes present.
   [*metricdb.opening-verifies-the-required-tables-and-indexes-are-present]
   Failing this, with SQLite reporting no corruption, is a **startup
   failure**.
<!-- lint-disable-next-line line-length -->
   [*metricdb.a-structural-failure-without-reported-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.
<!-- lint-disable-next-line line-length -->
   [*metricdb.a-corrupt-store-is-quarantined-and-replaced-with-a-fresh-empty-store]
   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.
   [*metricdb.unrecognised-contents-are-quarantined]

The metric store is a required store; there is no degraded mode without
one (§8.2).
[*metricdb.the-metric-store-is-required-and-has-no-degraded-mode]

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.
[*metricdb.exactly-one-read-write-connection-owned-by-the-metric-writer]
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).
<!-- lint-disable-next-line line-length -->
[*metricdb.retention-and-rollups-use-read-only-connections-and-submit-commands-to-the-writer]

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.
<!-- lint-disable-next-line line-length -->
[*metricdb.the-writer-checkpoints-passively-at-walcheckpointpages-without-blocking]

As with the log store, the checkpoint is the durability boundary under
`synchronous=NORMAL`, not merely space reclamation (§9.5).
[*metricdb.the-checkpoint-is-the-durability-boundary]

---

# 5.5 Retention

_Peios / Reference / eventd / Metric Storage_

> The metric retention pass, its long default, rollup invalidation, and how space is reclaimed.

Metric retention runs on the same background thread as the other two,
after the log store (§3.6, §4.4).
<!-- lint-disable-next-line line-length -->
[*metricretain.metric-retention-runs-on-the-shared-retention-thread-after-the-log-store]
Both limits are enforced and the more
aggressive wins.
[*metricretain.both-limits-are-enforced-and-the-more-aggressive-wins]

## 5.5.1 The pass

1. Delete rows from `samples` older than `MetricRetentionDays` (§A)
   until none remain.
   [*metricretain.samples-older-than-metricretentiondays-are-deleted]
2. If `MetricRetentionMaxBytes` is non-zero and the store's logical live
   size exceeds it, delete the oldest samples by timestamp until it is
   within the limit.
<!-- lint-disable-next-line line-length -->
   [*metricretain.over-the-byte-limit-the-oldest-samples-are-deleted-until-within-it]
   The mainline default is 1073741824 bytes (1 GiB);
   zero is an explicit opt-out rather than the default.
   [*metricretain.the-byte-limit-defaults-to-1-gib-and-zero-disables-it]
3. Track every `series_id` whose samples were deleted by either step.
   [*metricretain.every-series-that-lost-samples-is-tracked]
4. Before deleting a sample batch, delete all adaptive rollups belonging to
  any
   affected series (§5.6).
<!-- lint-disable-next-line line-length -->
   [*metricretain.an-affected-series-loses-its-rollups-before-its-samples-are-deleted]
5. Delete every `series` row with no remaining samples.
   [*metricretain.series-with-no-remaining-samples-are-deleted]

Logical live size is the same measure as §3.6.
[*metricretain.the-byte-limit-measures-logical-live-size-as-for-events]

Step 5 removes the definitions of series nobody produces any more, which
is the only mechanism that ever removes a `series` row.
[*metricretain.retention-is-the-only-mechanism-that-removes-a-series-row]
A series that
stopped receiving samples persists until its last sample is removed.
[*metricretain.an-idle-series-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).
[*metricretain.metric-retention-defaults-to-ninety-days]

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.
<!-- lint-disable-next-line line-length -->
[*metricretain.size-pressure-retires-old-samples-rather-than-refusing-new-series]
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.
[*metricretain.the-size-decision-is-made-only-by-the-retention-coordinator]
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. [*metricretain.retention-deletes-samples-without-downsampling]
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).
[*metricretain.rollups-never-answer-for-expired-samples]

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.
<!-- lint-disable-next-line line-length -->
[*metricretain.retention-plans-read-only-and-submits-low-priority-deletes-to-the-writer]
Each writer-owned
transaction deletes at most `RetentionDeleteBatchRows`, and ingestion is
rechecked before the next command.
[*metricretain.each-delete-transaction-is-capped-at-retentiondeletebatchrows]
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).
<!-- lint-disable-next-line line-length spelling -->
[*metricretain.urgent-size-pressure-may-add-one-bounded-delete-to-an-open-transaction]

`VACUUM` is never run automatically.
[*metricretain.vacuum-is-never-run-automatically]
Freed pages are recycled and are
excluded from the size measure.
[*metricretain.freed-pages-are-excluded-from-the-size-measure]

---

# 5.6 Adaptive Rollups

_Peios / Reference / eventd / Metric Storage_

> How repeated wide metric-window queries seed a bounded, self-validating cache without adding work to ingestion.

Raw rows in `samples` are always authoritative.
[*rollup.raw-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.
[*rollup.deleting-every-rollup-never-changes-a-query-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.
<!-- lint-disable-next-line line-length -->
[*rollup.a-miss-or-stale-row-is-answered-from-raw-samples-without-waiting-for-repair]

The design protects eventd's primary job. Metric ingestion does not inspect,
update, or coordinate with rollups.
[*rollup.metric-ingestion-never-touches-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.
[*rollup.queries-submit-candidates-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.
<!-- lint-disable-next-line line-length -->
[*rollup.the-writer-takes-at-most-one-rollup-command-and-only-when-idle-and-committed]
A full command channel, writer pressure, or any ordinary cache-write
failure drops the candidate rather than delaying ingestion.
[*rollup.a-full-channel-writer-pressure-or-write-failure-drops-the-candidate]

## 5.6.1 Eligible queries

A query can read or seed rollups only when all of these are true:

- it has `SINCE` and an explicit `AVG_OVER`, `MIN_OVER`, `MAX_OVER` or
  `SUM_OVER` function;
  [*rollup.eligibility-requires-since-and-an-explicit-window-function]
- the selected output is per series — the selector is bracketed, or it
  resolves
  to exactly one series;
  [*rollup.eligibility-requires-per-series-output]
- it has no `WHERE` predicate or cross-type filter; and
  [*rollup.eligibility-excludes-where-predicates-and-cross-type-filters]
- `AdaptiveRollupMaxRows` is non-zero.
  [*rollup.eligibility-requires-a-non-zero-adaptiverollupmaxrows]

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. [*rollup.only-complete-epoch-aligned-windows-are-cached]
Any partial window at either end of the requested range is always
read from raw samples.
[*rollup.partial-edge-windows-are-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.
<!-- lint-disable-next-line line-length -->
[*rollup.a-series-uses-the-cache-only-when-every-interior-window-has-a-valid-row]
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.
[*rollup.streaming-continuations-neither-use-nor-seed-rollups]
They preserve their normal
incremental raw-query semantics.

## 5.6.2 Schema and identity [*rollup.schema-version-2-defines-the-rollups-table]

Metric schema version 2 adds:

```sql
CREATE TABLE rollups (
    series_id INTEGER NOT NULL REFERENCES series(id) ON DELETE CASCADE,
    window_start INTEGER NOT NULL,
    window_width INTEGER NOT NULL CHECK (window_width > 0),
    transform INTEGER NOT NULL CHECK (transform IN (0, 1, 2, 50, 95, 99)),
    function INTEGER NOT NULL CHECK (function BETWEEN 0 AND 3),
    value REAL,
    overflow INTEGER NOT NULL CHECK (overflow IN (0, 1)),
    source_max_sample_id INTEGER NOT NULL CHECK (source_max_sample_id >= 0),
    source_baseline_sample_id INTEGER CHECK (source_baseline_sample_id > 0),
    CHECK (overflow = 0 OR value IS NULL),
    PRIMARY KEY
        (series_id, window_start, window_width, transform, function)
) WITHOUT ROWID;
```

`transform` distinguishes no transform, `RATE`, `DELTA`, `P50`, `P95`, and
`P99`. [*rollup.transform-distinguishes-none-rate-delta-p50-p95-and-p99]
`function` distinguishes `AVG_OVER`, `MIN_OVER`, `MAX_OVER`, and
`SUM_OVER`. [*rollup.function-distinguishes-the-four-window-functions]
`value` is null only for an empty window or a percentile overflow;
`overflow` distinguishes those cases.
[*rollup.value-is-null-only-for-an-empty-window-or-a-percentile-overflow]
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).
<!-- lint-disable-next-line line-length -->
[*rollup.a-version-1-store-gains-the-table-and-pruning-index-in-one-immediate-transaction]
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`.
[*rollup.a-row-records-the-greatest-sample-id-in-its-window]
Before serving it, the query engine proves that the same
series and window has no sample with a greater `id`.
[*rollup.a-row-is-served-only-if-its-window-has-no-greater-sample-id]
A later sample therefore
makes the row stale even when its timestamp was backfilled into an old window.
[*rollup.a-backfilled-sample-makes-its-windows-row-stale]
An empty window records zero, so its first raw sample also invalidates it.
[*rollup.an-empty-window-records-zero-and-its-first-sample-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.
[*rollup.rate-and-delta-rows-record-the-preceding-sample-id-as-their-baseline]
The query engine compares this with
the current immediately preceding sample. A new, changed, or deleted baseline
makes the row stale.
[*rollup.a-new-changed-or-deleted-baseline-makes-a-rate-or-delta-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.
[*rollup.the-query-time-validity-proof-is-always-performed]

Non-finite cached values are rejected.
<!-- lint-disable-next-line line-length -->
[*rollup.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.
[*rollup.seeding-requires-at-least-adaptiverollupminsamples-raw-inputs]
It enqueues no more than
`AdaptiveRollupBatchRows` missing windows, and submission uses `try_send` on a
fixed-capacity channel.
<!-- lint-disable-next-line line-length spelling -->
[*rollup.one-submission-carries-at-most-adaptiverollupbatchrows-windows-via-try-send]
Repeating a wide query gradually fills its cache in
bounded pieces without starting a background scanner.
[*rollup.there-is-no-background-rollup-scanner]

The writer upserts a candidate under the complete cache identity and prunes
the
oldest window starts until no more than `AdaptiveRollupMaxRows` remain.
<!-- lint-disable-next-line line-length -->
[*rollup.the-writer-upserts-then-prunes-oldest-windows-down-to-adaptiverollupmaxrows]
The cap
is global to the metric store.
[*rollup.the-row-cap-is-global-to-the-metric-store]
It limits this optional acceleration state; it
does not delete series or raw samples.
[*rollup.pruning-never-deletes-series-or-raw-samples]

All three controls are live (§A).
[*rollup.the-three-rollup-controls-take-effect-live]
Setting `AdaptiveRollupMaxRows` to zero
immediately disables cache reads and writes without changing query results.
[*rollup.a-zero-row-cap-disables-rollups-immediately-without-changing-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).
[*rollup.rollups-leave-raw-sample-retention-unchanged]

---

# 5.7 Health Metrics

_Peios / Reference / eventd / Metric Storage_

> The eventd.* metrics eventd records about itself — what each counts, how they are written, and what is deliberately left out.

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.
[*health.the-metric-thread-samples-every-health-series-each-interval]
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).
[*health.health-samples-bypass-the-metric-socket-and-publication-check]
An interval of 0 turns them off.
[*health.a-zero-interval-turns-health-metrics-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.
[*health.health-samples-respect-the-metric-transaction-size-cap]

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).
[*health.health-counters-restart-from-zero-with-eventd]

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

[*health.events-stored-counts-committed-events-per-shard]
[*health.events-lost-counts-the-sequences-committed-gap-records-name]
[*health.ring-fill-is-each-drains-last-observed-ring-occupancy]
[*health.index-sheds-count-indexes-dropped-by-reason]
[*health.store-bytes-is-bytes-on-disk-with-write-ahead-logs]
[*health.queries-refused-counts-each-slot-limit-separately]

`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.
[*health.the-default-eventd-metrics-descriptor-grants-read-and-no-publish]
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).
[*health.rejected-ingestion-input-is-not-among-the-health-metrics]

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.
[*health.kernel-socket-drops-are-not-among-the-health-metrics]

---

# 6.1 Parsing and Planning

_Peios / Reference / eventd / Query Execution_

> The four phases between a query string and an answer, what can only fail after planning, and when payloads are decoded.

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. [*plan.a-query-runs-parse-then-plan-then-authorize-then-execute]

## 6.1.1 Parsing

The string is parsed into a syntax tree. The parser:

1. Identifies the mode from the first token — `EVENTS`, `LOGS`, or
   `METRIC`. [*plan.the-mode-is-identified-from-the-first-token]
2. Extracts the primary selector: a type pattern, a `FROM` list, or a
   metric name with an optional label selector.
   [*plan.the-parser-extracts-the-primary-selector]
3. Collects every clause, in whatever order they appear.
   [*plan.clauses-are-collected-in-whatever-order-they-appear]
4. Validates that the clauses suit the mode — `CONTAINING` only in log
   mode, `RATE` only in metric mode, `SELECT` only where a result schema
   is not fixed.
   [*plan.clause-and-mode-compatibility-is-checked-at-parse-time]

Parse errors are returned immediately, before anything is opened, read
or authorized.
[*plan.parse-errors-return-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).
[*plan.store-dependent-failures-surface-at-planning-or-execution-not-parse]

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)
  [*plan.planning-resolves-the-concrete-identifiers-the-data-could-carry]
- which series a metric selector matches, and whether they are
  type-homogeneous
[*plan.planning-resolves-matched-series-and-checks-they-are-type-homogeneous]
- which fields the query references, for both authorization and
  frequency accounting (§6.5)
  [*plan.planning-collects-referenced-fields-for-authorization-and-accounting]
- which stores are involved, including any cross-type source
[*plan.planning-identifies-every-store-involved-including-cross-type-sources]

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).
<!-- lint-disable-next-line line-length spelling -->
[*plan.identifier-discovery-reads-the-event-types-log-origins-and-series-catalogues]
The primary selector filters that set before access checks.
<!-- lint-disable-next-line line-length -->
[*plan.the-primary-selector-filters-discovered-identifiers-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.
[*plan.discovery-never-scans-a-records-table-or-needs-an-adaptive-index]

Catalogs can conservatively contain a name whose final retained row was
<!-- lint-disable-next-line spelling -->
deleted. [*plan.a-catalogue-may-keep-a-name-whose-rows-were-all-deleted]
That safe superset can cause an extra access check but cannot
expose a row or omit a concrete identifier that committed successfully.
<!-- lint-disable-next-line line-length spelling -->
[*plan.a-stale-catalogue-name-never-exposes-a-row-or-omits-a-committed-identifier]
Low-priority cleanup is optional and is never query-critical.

## 6.1.5 Header literal types

[*plan.header-literal-coercions-are-scoped-to-the-query-namespace]

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.
[*plan.payloads-are-decoded-only-where-a-query-needs-them]

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. [*plan.queries-execute-on-read-only-sqlite-connections]
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.
[*plan.a-log-or-metric-query-opens-a-single-connection] 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.
<!-- lint-disable-next-line line-length -->
[*plan.an-admitted-query-that-cannot-get-resources-fails-rather-than-blocking-a-writer]

## 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_

> Making every result order total and deterministic so paging works — the tiebreakers, and why insertion order is never the answer.

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:
[*order.internal-tiebreaker-keys-are-appended-until-the-order-is-total]

| Mode | Appended, in order |
|---|---|
| Events | `timestamp`, the column of `event.time`, descending, shard index ascending, `events.id` descending |
| Logs | `timestamp` descending, `logs.id` descending |
| Metrics | `timestamp` ascending, metric name ascending, canonical labels ascending, and `samples.id` ascending where the row corresponds to a raw sample or a derived sample pair |
[*order.event-tiebreakers-are-timestamp-desc-then-shard-index-asc-then-id-desc]
[*order.log-tiebreakers-are-timestamp-desc-then-id-desc]
[*order.metric-tiebreakers-are-timestamp-name-labels-then-sample-id-all-ascending]

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).
[*order.tiebreaker-keys-never-appear-in-results-and-cannot-be-named]

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).
[*order.hidden-metric-labels-remain-in-the-internal-tiebreaker]

The **shard index** is the numeric identifier from the `shard-NNNN.db`
filename. [*order.the-shard-index-is-the-number-in-the-shard-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.
[*order.row-ids-only-break-ties-and-never-replace-timestamp-order]

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.
[*order.metric-computations-order-samples-by-timestamp-then-id-ascending]

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).
[*order.sorting-grouping-and-equality-never-use-sqlite-type-rules]

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). [*order.a-group-emits-its-smallest-member-not-its-first]

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_

> What the query language translates to directly, what does not translate, where access control sits, and how aggregation is handled.

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.
[*sql.clients-never-see-the-generated-sql]

## 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.
[*sql.an-event-header-predicate-becomes-a-sql-where-comparison]

**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.
[*sql.a-top-level-timestamp-comparison-narrows-the-range-read]

**Log fields** are all columns; log mode has no payload and its field
set is closed (§4.2). [*sql.every-log-field-is-a-column]

**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).
<!-- lint-disable-next-line line-length -->
[*sql.metric-selection-resolves-through-series-and-reads-samples-in-index-order]

## 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).
[*sql.a-payload-predicate-becomes-an-internal-extraction-predicate]

**`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.
[*sql.has-uses-no-index-and-tests-each-candidates-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.
<!-- lint-disable-next-line line-length -->
[*sql.sql-only-narrows-candidates-and-the-real-predicate-is-applied-after-loading]

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.
<!-- lint-disable-next-line line-length -->
[*sql.results-equal-filtering-first-including-aggregates-ordering-and-pagination]

## 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.
[*sql.aggregation-is-never-pushed-into-sql-and-rows-fold-in-eventd]

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 run against every database in the store, active and historical — how results merge, and the unbounded case.

Event queries execute against **every** database in the event store
directory — active shards and historical ones alike (§3.3).
[*fanout.an-event-query-runs-against-every-active-and-historical-shard]
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.
[*fanout.no-shard-is-skipped-even-for-a-cpu-id-predicate]

## 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.
[*fanout.non-aggregating-results-are-an-n-way-merge-of-sorted-shard-streams]
Each row that passes access control and every predicate is sent as soon
as it is taken.
[*fanout.merged-results-are-streamed-incrementally-not-materialised]
Once `SKIP + TAKE` rows have passed, the merge stops.
[*fanout.with-take-the-merge-stops-once-skip-plus-take-rows-have-passed]
What the query holds is one row per shard, the merge frontier, whatever
the size of its result.
[*fanout.a-default-order-query-holds-one-row-per-shard]

**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.
[*fanout.a-sorted-query-with-take-keeps-only-its-best-skip-plus-take-rows]
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.
[*fanout.aggregating-queries-fold-rows-into-groups-as-they-are-read]
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 |

[*fanout.grouped-counts-are-sorted-descending-then-taken]
[*fanout.group-sum-keeps-the-exact-and-binary64-sums]
[*fanout.group-avg-divides-the-whole-sum-by-the-whole-count]
[*fanout.group-min-and-max-keep-the-extreme-so-far]
[*fanout.distinct-keeps-each-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).
[*fanout.numeric-groups-are-sorted-by-keys-before-pagination]

`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.
[*fanout.groups-are-found-by-a-hash-that-equal-values-share]

What an aggregation holds is bounded by the number of its groups rather
than by its rows, within `MaxQueryHeldBytes` (§6.5).
[*fanout.aggregation-memory-is-bounded-by-group-cardinality]

## 6.4.2 The unbounded case

A non-aggregating query without `TAKE` has no implicit row limit.
[*fanout.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).
[*fanout.the-query-timeout-is-the-only-backstop-for-an-unbounded-query]
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.
[*fanout.an-event-query-opens-a-read-only-connection-per-database]
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.
[*fanout.active-shard-writer-connections-stay-open-for-the-process-lifetime]
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_

> What every query records for the adaptive indexer, and the concurrency, memory and timeout limits it runs under.

## 6.5.1 Recording what was asked

Every event query is recorded by the adaptive indexing system (§3.4).
[*account.every-event-query-is-recorded-by-the-adaptive-indexer]
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
  [*account.a-header-column-predicate-increments-that-columns-counter]
- a payload field reference increments that path's counter
  [*account.a-payload-field-predicate-increments-that-paths-counter]

Cross-type `WHERE` predicates are counted like any other, since they
narrow the same data by the same fields.
[*account.cross-type-where-predicates-are-counted-like-any-other]

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.
[*account.log-and-metric-queries-increment-no-counters]

Counters are in-memory and are flushed to the metadata database at each
policy interval (§3.5).
[*account.counters-are-flushed-to-the-metadata-database-each-policy-interval]
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. [*account.query-handlers-never-write-the-metadata-database-directly]

## 6.5.2 Concurrency

eventd bounds concurrent queries — streaming and non-streaming together
— at `MaxConcurrentQueries` (§A).
<!-- lint-disable-next-line line-length -->
[*account.max-concurrent-queries-bounds-streaming-and-non-streaming-queries-together]
Beyond it a query is rejected with an error rather than queued.
[*account.a-query-over-the-concurrency-limit-is-rejected-not-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.
[*account.max-streaming-queries-is-a-separate-lower-limit] 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`.
[*account.max-queries-per-user-bounds-one-callers-running-queries]
The caller is the user SID of the token read at connect.
[*account.the-per-user-limit-counts-by-the-user-sid-of-the-peer-token]
The slot is taken as soon as the token is read, before the request, so
connections held open without a query count too.
[*account.the-per-user-slot-is-taken-before-the-request-is-read]
SYSTEM's queries are not counted: SYSTEM is the machine, not one caller
among others. [*account.system-queries-are-not-counted-per-user] Over
the limit, the query is rejected with an error, as over the global ones.
[*account.a-query-over-the-per-user-limit-is-rejected-with-an-error]

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).
[*account.exhausting-the-query-slots-cannot-exhaust-ingestion]

## 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).
[*account.a-default-order-query-is-never-refused-for-its-size]

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**.
[*account.max-query-held-bytes-bounds-what-all-running-queries-hold-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.
[*account.held-memory-is-reserved-in-granules-and-given-back]
A query that would take more than is left fails with an error, rather
than being truncated or answered from part of the data.
[*account.a-query-past-the-held-budget-fails-with-an-error]

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.
[*account.a-metric-query-folds-samples-as-it-reads-them]
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.
[*account.a-metric-querys-held-series-folds-and-rows-count-against-the-budget]
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.
<!-- lint-disable-next-line line-length -->
[*account.a-request-frame-over-max-query-request-bytes-is-rejected-before-reading]
Outbound result records are grouped at record boundaries toward
`QueryResponseTargetBytes` (§A).
<!-- lint-disable-next-line line-length -->
[*account.result-records-are-grouped-at-record-boundaries-toward-the-response-target]
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).
[*account.a-record-over-the-response-target-is-sent-alone-and-whole]
Only the protocol's `u32` frame length is a hard outbound bound.
[*account.the-u32-frame-length-is-the-only-hard-outbound-bound]

## 6.5.5 Timeouts

Every query has a maximum execution time, `QueryTimeoutMs` (§A).
[*account.every-query-is-bounded-by-query-timeout-ms]

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.
<!-- lint-disable-next-line line-length -->
[*account.the-timeout-starts-after-decoding-and-token-acquisition-and-covers-the-rest]

It bounds the **initial result set only**. A non-streaming query sends
`end` before it expires; a streaming query sends `watch`.
[*account.the-timeout-bounds-only-the-initial-result-set] Past `watch`
the stream is not time-limited, and what bounds it instead is
`MaxStreamingQueries`, `MaxDistinctStreamValues` and backpressure
(§6.6). [*account.a-stream-past-watch-is-not-time-limited]

On expiry eventd cancels the query and sends an error.
<!-- lint-disable-next-line spelling -->
[*account.on-expiry-the-query-is-cancelled-and-an-error-is-sent] 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).
[*account.cancellation-interrupts-in-progress-sqlite-work]
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.
[*account.non-sql-query-work-checks-the-deadline-periodically]

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_

> How a live watch is implemented — commit generations, latency, the DISTINCT seen set, cross-type re-evaluation and backpressure.

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.
<!-- lint-disable-next-line line-length -->
[*stream.there-is-one-commit-generation-counter-for-the-event-store-and-one-for-the-log-store]
Metric queries do not stream, so the metric store has none.
[*stream.the-metric-store-has-no-commit-generation-counter]

After a writer commits a batch it increments the counter for its store
and wakes the streaming handlers waiting on it.
<!-- lint-disable-next-line line-length -->
[*stream.a-writer-increments-its-stores-generation-and-wakes-handlers-after-each-commit]
A handler records the last generation it processed and waits until the
counter exceeds it.
[*stream.a-handler-waits-until-the-generation-exceeds-its-last-processed-one]

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).
[*stream.an-event-store-wake-makes-a-handler-re-examine-every-shard]

The counter is process-local and never persisted; it has no meaning
across a restart, and a streaming query does not survive one.
<!-- lint-disable-next-line line-length -->
[*stream.the-generation-is-never-persisted-and-a-stream-does-not-survive-a-restart]
On wraparound the next increment is treated as a wake for every handler
and operation continues.
[*stream.generation-wraparound-is-treated-as-a-wake-for-every-handler]
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.
[*stream.watch-records-follow-store-order]

`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.
[*stream.a-record-is-not-streamed-until-it-is-committed]

| Store | Approximate floor | From |
|---|---|---|
| Events | `MaxBatchLatencyMs`, default 100 ms | §2.4 |
| Logs | `LogMaxBatchLatencyMs`, default 500 ms | §4.1 |

[*stream.the-event-stream-latency-floor-is-max-batch-latency-ms]
[*stream.the-log-stream-latency-floor-is-log-max-batch-latency-ms]

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).
[*stream.a-distinct-streams-seen-set-starts-from-the-initial-result-set]

It is bounded by `MaxDistinctStreamValues` (§A), and exceeding the bound
terminates the query with an error rather than evicting.
<!-- lint-disable-next-line line-length -->
[*stream.exceeding-max-distinct-stream-values-terminates-the-query-without-eviction]
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).
[*stream.precomputed-cross-type-ranges-are-discarded-when-the-watch-begins]

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).
<!-- lint-disable-next-line line-length -->
[*stream.a-metric-condition-is-evaluated-once-per-batch-at-its-latest-candidate-timestamp]

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. [*stream.an-existence-condition-is-evaluated-per-candidate-record]

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.
[*stream.records-in-one-batch-pass-or-fail-a-metric-condition-together]

## 6.6.6 Backpressure

Backpressure is detected on the socket send buffer.
[*stream.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.
[*stream.a-full-send-buffer-terminates-the-query-and-eventd-never-blocks]

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_

> Query authorization, caller identity, and the separate authorization checks that protect ingestion.

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

[*access.eventd-delegates-every-decision-to-kacs-accesscheck]

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 [*access.access-is-enforced-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.
<!-- lint-disable-next-line spelling -->
[*access.every-record-is-stored-regardless-of-who-may-read-it]

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.
  [*access.a-grant-or-revocation-applies-retroactively-to-stored-records]
- **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.
<!-- lint-disable-next-line spelling -->
[*access.every-authenticated-caller-may-connect-to-the-query-socket]
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.
[*access.the-caller-token-is-read-from-the-peer-token-socket-option] The token
represents the peer's identity as captured **at connection time**.
[*access.the-caller-token-is-captured-at-connection-time]

If the call fails, eventd denies the query entirely.
[*access.a-failed-peer-token-read-denies-the-query] It has no fallback
identification and no anonymous mode.
[*access.there-is-no-fallback-identification-or-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.
[*access.an-anonymous-level-caller-is-refused]

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

[*access.eventd-read-is-bit-0-value-0x0001]
[*access.eventd-clear-is-bit-1-value-0x0002]
[*access.eventd-administer-is-bit-2-value-0x0004]
[*access.eventd-publish-is-bit-3-value-0x0008]

The generic mapping passed to AccessCheck is in §B.

`EVENTD_ADMINISTER` is distinct from `EVENTD_READ` deliberately.
[*access.eventd-read-alone-does-not-grant-eventd-administer]
Accelerating a field costs write throughput on every record thereafter,
so `INDEX` is a way for a caller to degrade the system for everybody,
and a caller permitted only to read has not been permitted to do that
(PSPU §3.23).

> [!NOTE]
> `EVENTD_CLEAR` is defined and nothing yet uses it: no operation deletes
> records on a caller's behalf, and retention deletes on nobody's behalf
> (§3.6). [*access.no-operation-uses-eventd-clear] It is reserved for
> administrative deletion. The consequence
> worth knowing is that a descriptor written today with `GENERIC_WRITE`
> already grants it, and will start granting a real capability the moment
> one exists. [*access.generic-write-already-grants-eventd-clear]

## 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 carrying a descriptor — matching, resolution, storage, and the first-boot defaults.

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:
[*pattern.each-data-type-has-an-independent-pattern-namespace]

| Namespace | Patterns match |
|---|---|
| Events | event type |
| Logs | log origin |
| Metrics | metric name |

[*pattern.event-patterns-match-the-event-type]
[*pattern.log-patterns-match-the-log-origin]
[*pattern.metric-patterns-match-the-metric-name]

## 7.2.1 Matching

A pattern matches by **dot-delimited prefix**.
<!-- lint-disable-next-line line-length -->
[*pattern.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.
[*pattern.a-prefix-match-must-end-at-a-dot-or-the-end-of-the-string]

`*` is the wildcard default and matches everything.
[*pattern.the-wildcard-pattern-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`.
[*pattern.an-origin-with-a-producer-resolves-from-the-part-before-the-slash]
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`.
<!-- lint-disable-next-line line-length -->
[*pattern.service-producers-use-the-service-descriptor-and-all-jobs-use-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.
[*pattern.a-slash-never-enters-a-descriptor-path]

## 7.2.2 Resolution [*pattern.resolution-walks-up-the-hierarchy-to-the-wildcard]

For a concrete identifier, eventd resolves the applicable descriptor by
walking up the hierarchy:

1. Look for an exact match on the full identifier,
   `kacs.audit.access.checked`.
   [*pattern.resolution-tries-the-full-identifier-first]
2. Remove the last dot-separated component and look again,
   `kacs.audit.access`.
   [*pattern.resolution-then-drops-the-last-dot-separated-component]
3. Repeat: `kacs.audit`, then `kacs`.
4. Fall back to the wildcard, `*`.
   [*pattern.resolution-falls-back-to-the-wildcard-last]

The first match wins; a more specific pattern overrides a less specific
one. [*pattern.the-most-specific-matching-pattern-wins]

## 7.2.3 Storage

[*pattern.descriptors-are-registry-values-under-the-eventd-security-subtree]

Descriptors are registry values under the eventd security subtree:

```text
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).
[*pattern.a-missing-wildcard-default-denies-all-data-of-that-type]

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.
<!-- lint-disable-next-line spelling -->
[*pattern.whoever-may-write-a-descriptor-value-may-also-drop-its-sacl]
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.
<!-- lint-disable-next-line line-length -->
[*pattern.the-security-root-gets-a-protected-dacl-while-its-dacl-is-wholly-inherited]

## 7.2.4 Defaults on first boot [*pattern.missing-default-descriptors-are-created]

eventd creates the three wildcard keys, the descriptor for its own
health metrics and the administrative descriptor if they do not exist:

| Key | Default |
|---|---|
| `…\Security\Events\*` | SYSTEM and Administrators: `EVENTD_READ` on all fields. |
| `…\Security\Logs\*` | SYSTEM, Administrators, and Authenticated Users: `EVENTD_READ`. |
| `…\Security\Metrics\*` | SYSTEM and Administrators: `EVENTD_READ \| EVENTD_PUBLISH`; Authenticated Users: `EVENTD_READ`. |
| `…\Security\Metrics\eventd` | SYSTEM, Administrators, and Authenticated Users: `EVENTD_READ`; nobody `EVENTD_PUBLISH`, because eventd writes its own health without the socket (§5.7). |
| `…\Security\Admin` | SYSTEM and Administrators: `EVENTD_ADMINISTER`. |
[*pattern.the-default-events-descriptor-grants-read-to-system-and-administrators]
[*pattern.the-default-logs-descriptor-also-grants-read-to-authenticated-users]
[*pattern.the-default-metrics-descriptor-grants-publish-only-to-system-and-administrators]
[*pattern.the-default-eventd-metrics-descriptor-grants-publish-to-nobody]
[*pattern.the-default-admin-descriptor-grants-administer-to-system-and-administrators]

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).
[*pattern.every-default-descriptor-audits-every-failed-access-by-everyone]

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).
[*pattern.publication-is-fail-closed-for-services-without-a-specific-grant]
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.
[*pattern.a-former-default-is-replaced-only-on-an-exact-binary-match] A
value an administrator changed is never treated as a default and never
rewritten. [*pattern.an-administrator-changed-descriptor-is-never-rewritten]

## 7.2.5 Conditional ACEs

Descriptors on eventd security objects can carry conditional ACEs, and
KACS evaluates them as it would anywhere.
[*pattern.conditional-aces-are-evaluated-by-kacs-as-anywhere]

eventd passes **no eventd-specific local claims** to AccessCheck:
`local_claims_ptr` is null and `local_claims_len` is zero.
[*pattern.no-local-claims-are-passed-to-accesscheck] Conditions
referencing token claims that KACS itself supplies still evaluate;
conditions referencing eventd-local claims observe them as absent.
[*pattern.conditions-on-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.
[*pattern.index-is-checked-against-the-admin-descriptor-for-eventd-administer]
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.
[*pattern.index-is-refused-when-no-admin-descriptor-exists] 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).
[*pattern.recreating-eventd-meta-db-does-not-reset-the-admin-policy]

---

# 7.3 Per-Field Control

_Peios / Reference / eventd / Access Control_

> Granting some fields of a record and not others through object ACEs — the tree of field paths, granting a subtree by its prefix, and how field GUIDs are derived rather than registered.

A descriptor can grant read access to some fields of a record and not
others, using KACS **object ACEs** and object type lists.
[*fieldaccess.a-descriptor-can-grant-some-fields-of-a-record-and-not-others]
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).
[*fieldaccess.an-unauthorized-field-is-absent-as-if-never-carried]

## 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.
<!-- lint-disable-next-line line-length -->
[*fieldaccess.the-object-type-list-is-the-root-and-the-tree-of-field-paths-one-node-per-segment]
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`.
[*fieldaccess.a-prefix-node-has-the-guid-of-the-prefix-as-a-field-name]
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.
[*fieldaccess.a-shared-prefix-is-one-node-and-the-list-is-in-preorder]

```text
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.
[*fieldaccess.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.
[*fieldaccess.each-field-is-included-or-excluded-by-its-node-verdict]
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

[*fieldaccess.field-guids-are-derived-not-registered]

A field's GUID is computed deterministically with UUID v5 (RFC 4122):

```text
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.
<!-- lint-disable-next-line line-length -->
[*fieldaccess.a-field-guid-is-uuid-v5-of-the-utf-8-field-name-in-the-eventd-namespace]

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.
<!-- lint-disable-next-line line-length -->
[*fieldaccess.the-same-field-name-always-yields-the-same-guid] 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` |

[*fieldaccess.an-event-header-field-is-named-by-its-field-path]
[*fieldaccess.an-event-payload-field-is-named-by-its-flattened-dot-path]
[*fieldaccess.a-log-field-is-named-by-its-column-name]
[*fieldaccess.the-fixed-metric-field-names]
[*fieldaccess.a-metric-label-is-named-by-its-label-key]

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).
[*fieldaccess.suppressed-payload-fields-get-no-guid] 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.
[*fieldaccess.a-field-guid-does-not-depend-on-the-event-type-carrying-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.
[*fieldaccess.a-field-ace-is-scoped-by-the-pattern-descriptor-holding-it]

## 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.
[*fieldaccess.an-ace-naming-a-prefix-applies-to-every-field-beneath-it]
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`.
[*fieldaccess.a-grant-on-event-or-emitter-covers-the-header-fields-beneath-it]

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.
<!-- lint-disable-next-line line-length -->
[*fieldaccess.a-field-is-decided-by-the-first-ace-naming-it-a-prefix-of-it-or-the-root]
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`.
[*fieldaccess.a-deny-on-a-field-leaves-its-siblings-untouched]
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.
[*fieldaccess.a-field-that-is-also-a-prefix-is-checked-with-only-its-prefixes]

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.
[*fieldaccess.an-object-ace-without-a-guid-applies-to-every-field] One
**with** a field GUID applies to that field.
[*fieldaccess.an-object-ace-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.
<!-- lint-disable-next-line line-length -->
[*fieldaccess.a-grant-of-three-field-guids-yields-records-with-exactly-those-three-keys]

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.
[*fieldaccess.the-list-is-built-from-the-fields-present-in-the-record]

**Event records** contribute every header field plus every non-suppressed
flattened payload field present in that particular payload.
<!-- lint-disable-next-line line-length -->
[*fieldaccess.an-event-list-has-every-header-field-and-every-present-unsuppressed-payload-field]
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.
[*fieldaccess.two-events-of-the-same-type-can-produce-different-lists]

**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. [*fieldaccess.every-log-record-has-the-same-six-field-list]

**Metric records** contribute the five fixed fields plus the series'
label keys, which vary per series.
<!-- lint-disable-next-line line-length -->
[*fieldaccess.a-metric-list-has-the-five-fixed-fields-and-the-series-label-keys]

Derived aggregate outputs — `count`, `sum`, `avg`, `min`, `max` — are
omitted from the list entirely.
[*fieldaccess.aggregate-outputs-are-omitted-from-the-list] 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).
<!-- lint-disable-next-line line-length -->
[*fieldaccess.an-aggregate-is-visible-when-its-source-records-and-fields-are-authorized]


## 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.
[*fieldaccess.metric-aggregates-do-not-restore-denied-source-headers]

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_

> Access control is the third phase of query evaluation — which clauses count as referencing a field, and why denial is silent.

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.
[*enforce.access-control-is-the-third-query-phase-before-predicates] What
follows is the sequence within that phase.

1. **Obtain the caller's token** from the connection (§7.1). Failure
   denies the query.
   [*enforce.the-token-is-obtained-first-and-failure-denies-the-query]
2. **Parse** the query to establish its data sources and filters (§6.1).
   [*enforce.the-query-is-parsed-for-its-sources-and-filters]
3. **Discover the concrete identifiers** the query could touch — event
   type strings, log origin strings, metric name strings.
   [*enforce.the-concrete-identifiers-a-query-could-touch-are-discovered]
   A broad
   selector authorizes nothing by itself: `EVENTS`, `EVENTS kacs.*`,
   `LOGS` without `FROM`, and `METRIC cpu.*` are each resolved identifier
   by identifier.
   [*enforce.a-broad-selector-is-authorized-identifier-by-identifier]
4. **Resolve and check** each discovered identifier: find its descriptor
   by hierarchical matching (§7.2), and build the object type list for
   the fields the query references (§7.3). A query that references none
   asks instead about every field the descriptor's allowing object ACEs
   name, since those can make its records visible though the query names
   none of them; a GUID does not say its path, so each is a level-1 node
   of that list. Call
   `kacs_access_check_list`, and cache the verdict for this
   `(token, identifier, field set)` (§7.5).
   [*enforce.each-discovered-identifier-is-resolved-checked-and-cached]
[*enforce.the-identifier-check-adds-the-fields-the-descriptor-grants-by-name]
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.
[*enforce.a-root-denied-identifiers-records-are-excluded-before-aggregation]
   One whose root is denied but some field granted stays, for its
   records to be shaped to those fields (step 10).
   [*enforce.an-identifier-with-only-fields-granted-stays-visible]
   For a cross-type
   source, a denied identifier is treated as having no matching data.
   [*enforce.a-denied-cross-type-identifier-has-no-matching-data]
6. **Apply field verdicts to predicates.** Where the query references a
   field in a predicate or shaping clause and a matching identifier does
   not grant it, that identifier's records contribute nothing — exactly
   as if its root had been denied.
   [*enforce.a-denied-referenced-field-excludes-that-identifiers-records]
   The query is **not** rejected.
   [*enforce.a-denied-referenced-field-does-not-reject-the-query]
7. **Cross-type sources** get the same treatment. An invisible
   identifier, or a denied field needed to evaluate the condition, makes
   the condition
   evaluate as though no matching cross-source data existed.
[*enforce.a-denied-cross-source-root-or-field-evaluates-as-no-matching-data]
8. **Execute**, with root filtering already part of the logical row set.
   [*enforce.execution-runs-with-root-filtering-already-applied]
9. **Re-resolve per result identifier.** For each distinct concrete
   identifier in the resulting rows, resolve its descriptor, build the
   object type list with field GUIDs, call `kacs_access_check_list` with
   the token, the descriptor, `EVENTD_READ`, the list and an audit
   context naming the pattern the descriptor was resolved from (below),
   and cache the per-field results.
<!-- lint-disable-next-line line-length -->
   [*enforce.each-result-identifier-is-rechecked-for-eventd-read-with-field-guids]
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.
    [*enforce.each-record-is-shaped-by-its-identifiers-cached-verdicts]
    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.
    [*enforce.a-field-only-grant-gives-records-holding-exactly-those-fields]

## 7.4.1 Which clauses count as referencing a field

Step 6 applies to every clause that reads a value rather than merely
displaying one:

- ordinary `WHERE` predicates
  [*enforce.a-where-predicate-references-its-fields]
- metric label filters in a primary selector
  [*enforce.a-metric-label-filter-in-a-primary-selector-references-the-label]
- `GROUP`, `COUNT BY`, `TOP N BY`, `SORT`, and `DISTINCT` fields
<!-- lint-disable-next-line line-length -->
  [*enforce.grouping-counting-ranking-sorting-and-distinct-fields-are-referenced]
- event and log aggregation arguments — `SUM`, `AVG`, `MIN`, `MAX`
  [*enforce.event-and-log-aggregation-arguments-are-referenced]
- metric transforms and terminal aggregations, all of which read the
  fixed `value` field: `RATE`, `DELTA`, `P50`, `P95`, `P99`, `AVG`,
  `MIN`, `MAX`, `SUM`, `AVG_OVER`, `MIN_OVER`, `MAX_OVER`, `SUM_OVER`
  [*enforce.metric-transforms-and-terminal-aggregations-reference-value]
- a metric boot filter, which reads `boot_id`; and an explicit metric
  type predicate, grouping, sort or distinct, which reads `type`
<!-- lint-disable-next-line line-length -->
  [*enforce.a-metric-boot-filter-references-boot-id-and-type-clauses-reference-type]

`SELECT` is not on this list.
[*enforce.select-does-not-count-as-referencing-a-field] 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.
[*enforce.selecting-an-unreadable-field-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.
<!-- lint-disable-next-line line-length -->
[*enforce.field-authorization-is-resolved-from-the-written-name-regardless-of-presence]

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).
[*enforce.internal-values-are-not-source-fields-unless-exposed-or-named]
Errors raised by
internal checks never carry a denied field's value.
[*enforce.internal-check-errors-never-carry-a-denied-fields-value]

A metric result's `value` **is** a source field, because it is either a
raw sample or a scalar derived from raw samples.
[*enforce.a-metric-results-value-is-a-source-field]

## 7.4.5 Filtering is part of the logical result

[*enforce.access-filtering-is-part-of-the-logical-result-not-presentation]

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.
<!-- lint-disable-next-line spelling -->
[*enforce.every-aggregate-reflects-only-what-the-caller-may-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.
<!-- lint-disable-next-line line-length -->
[*enforce.every-denied-check-under-a-default-descriptor-produces-a-kacs-audit-event]
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.
[*enforce.eventds-checks-are-audited-because-its-token-holds-seauditprivilege]

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.
[*enforce.the-audit-context-names-the-data-type-and-pattern-accessed]

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).
[*enforce.access-audit-events-are-stored-and-governed-like-any-other-event]
Reading the audit store is auditable.

---

# 7.5 Caching

_Peios / Reference / eventd / Access Control_

> An access check is a syscall, and a large result cannot afford one per record — the record-level, field-level, and descriptor caches.

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.
<!-- lint-disable-next-line line-length -->
[*accesscache.verdicts-are-cached-per-query-and-keyed-by-identifier-not-pattern]

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.
<!-- lint-disable-next-line line-length -->
[*accesscache.ten-thousand-events-of-twenty-uniform-types-take-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.
[*accesscache.a-result-verdict-is-cached-per-identifier-and-field-set]

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.
[*accesscache.a-log-query-takes-two-checks-per-origin] 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.
[*accesscache.each-distinct-field-set-costs-its-own-cache-entry-and-check]

## 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).
[*accesscache.descriptor-resolution-is-cached-across-queries]

eventd watches the security registry subtree and invalidates cached
resolutions and cached check results when a descriptor changes.
[*accesscache.a-descriptor-change-invalidates-cached-resolutions-and-verdicts]
That is
what makes a revocation take effect on the next query rather than at the
next restart. [*accesscache.a-revocation-takes-effect-on-the-next-query]

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.
<!-- lint-disable-next-line line-length -->
[*accesscache.a-failed-registry-watch-discards-the-cache-and-fails-closed-for-new-resolutions]
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).
<!-- lint-disable-next-line line-length -->
[*accesscache.a-failed-watch-degrades-ingestion-continues-and-queries-see-no-records-until-it-recovers]

## 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.
[*accesscache.initial-stream-verdicts-are-reused-through-the-watch-phase]

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.
[*accesscache.a-new-identifier-in-a-stream-is-checked-before-it-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.
[*accesscache.after-a-descriptor-change-stream-batches-are-rechecked]

The **token** is not re-examined.
[*accesscache.a-streams-token-is-never-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.
[*accesscache.a-stream-keeps-its-connection-time-identity-until-disconnect]
The bound on that exposure is the client's
own connection lifetime, which for a dashboard can be days.

> [!NOTE]
> Re-obtaining the peer token periodically would narrow the window, and
> would also mean a streaming query could change what it returns halfway
> through for reasons the client cannot see. The snapshot is the simpler
> contract and is what PSPU §3.14 states; the exposure is the cost.

## 7.5.5 Metric publication

The metric ingestion thread owns a separate bounded cache for
`EVENTD_PUBLISH` checks (§7.6). It is keyed by the conveyed token's
`token_id` and `modified_id` plus concrete metric name. It caches denials
as well as grants, clears as a unit when full, and is invalidated by the
same descriptor generation as the read caches.

This cache is deliberately thread-local. A recurring metric performs a
borrowed string lookup without allocation, shared locking or AccessCheck;
the only per-datagram identity operation left is querying the fresh
token fd's stable statistics before that fd is closed.
[*accesscache.a-recurring-metric-needs-no-lock-and-only-stats-the-token-fd]

---

# 7.6 The Write Path

_Peios / Reference / eventd / Access Control_

> Broker-attested log origins and KACS-authorized metric names, including the cache that keeps AccessCheck off the steady-state hot path.

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).
[*writepath.eventd-is-not-in-the-event-admission-path]

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.
<!-- lint-disable-next-line line-length -->
[*writepath.event-identity-stamps-are-the-kernels-and-the-emitter-cannot-alter-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.
[*writepath.service-processes-cannot-reach-the-log-socket] eventd replaces the
inherited DACL on `LogSocketPath` with this protected DACL before
its first receive:
[*writepath.the-log-socket-gets-a-protected-dacl-before-the-first-receive]

```text
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.
[*writepath.the-log-socket-stays-owned-by-eventds-service-sid]

`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.
[*writepath.a-system-service-cannot-write-to-the-log-socket-but-peinit-can]

peinit determines `origin` from the output pipe it is draining and can
batch records from several origins in one datagram.
<!-- lint-disable-next-line spelling -->
[*writepath.a-log-datagram-may-carry-records-from-several-origins] eventd
therefore
does not request or check a KACS token for each log datagram.
[*writepath.eventd-requests-and-checks-no-token-for-a-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)`.
<!-- lint-disable-next-line spelling -->
[*writepath.every-authenticated-caller-may-send-to-the-metric-socket]
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.
[*writepath.eventd-sets-the-metric-socket-descriptor-again-at-each-start]

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.
[*writepath.metric-recvmsg-has-room-for-one-token-and-no-ordinary-fds]

eventd discards the whole datagram before MessagePack parsing when:

- no token arrived
  [*writepath.a-metric-datagram-without-a-token-is-discarded]
- the data was truncated
  [*writepath.a-metric-datagram-with-truncated-data-is-discarded]
- the ancillary data was truncated
  [*writepath.a-metric-datagram-with-truncated-ancillary-data-is-discarded]
- querying the token or resolving policy failed
<!-- lint-disable-next-line line-length -->
  [*writepath.a-metric-datagram-is-discarded-when-token-query-or-policy-resolution-fails]

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`.
<!-- lint-disable-next-line line-length -->
[*writepath.each-metric-record-is-checked-for-eventd-publish-against-the-conveyed-token]
A denied
record is discarded; authorized sibling records in the same datagram
continue.
<!-- lint-disable-next-line line-length -->
[*writepath.a-denied-metric-record-is-discarded-and-its-authorized-siblings-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).
[*writepath.publication-authorizes-the-metric-name-not-its-labels-or-value]

## 7.6.4 The publication cache

A full AccessCheck is not performed per sample or per datagram.
[*writepath.publication-is-not-checked-per-sample-or-per-datagram] The
metric ingestion thread owns a bounded verdict cache keyed by:
<!-- lint-disable-next-line line-length -->
[*writepath.the-publication-cache-is-keyed-by-token-id-modified-id-and-metric-name]

```text
(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.
[*writepath.a-publication-cache-hit-performs-no-allocation-and-no-accesscheck]

`MetricAuthorizationCacheSize` bounds the total entry count.
<!-- lint-disable-next-line line-length -->
[*writepath.metricauthorizationcachesize-bounds-the-publication-cache-entry-count]
When full,
eventd clears the cache rather than maintaining an LRU list on the write
path. [*writepath.a-full-publication-cache-is-cleared-rather-than-evicted]
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.
<!-- lint-disable-next-line line-length -->
[*writepath.a-security-registry-change-clears-publication-verdicts-before-reuse]
The cache stores denials as well as grants, so repeatedly sending
an unauthorized name does not repeatedly invoke KACS.
[*writepath.the-publication-cache-stores-denials-as-well-as-grants]

## 7.6.5 Rejected input

Missing identity, truncation, denied records, and policy errors increment
in-memory diagnostic counters.
[*writepath.rejected-metric-input-increments-in-memory-diagnostic-counters]
Policy errors can produce rate-limited
standard-error text.
<!-- lint-disable-next-line spelling -->
[*writepath.policy-errors-may-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).
[*writepath.rejected-input-produces-no-durable-event-or-log-record]
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_

> The four subsystems eventd needs before it can do anything, the one that is not really a dependency, and where it sits in the boot.

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

[*deps.events-are-ingested-from-kmes]
[*deps.eventd-reads-every-setting-from-the-registry]
[*deps.kacs-provides-query-authorization-and-peer-token-caller-identification]
<!-- lint-disable-next-line line-length -->
[*deps.peinit-manages-the-lifecycle-and-provisions-state-directories-before-start]

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).
[*deps.eventd-cannot-start-without-the-registry]

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).
[*deps.the-boot-id-is-read-from-proc-sys-kernel-random-boot-id]

## 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.
<!-- lint-disable-next-line line-length -->
[*deps.the-drain-write-and-retention-paths-never-call-kacs] 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.
[*deps.eventd-is-critical-and-peinit-reboots-rather-than-continue-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.
[*deps.eventd-starts-after-loregd-and-authd-and-stops-before-them]

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).
<!-- lint-disable-next-line line-length -->
[*deps.events-emitted-before-eventd-starts-are-read-by-its-first-drain-from-tail-pos]

---

# 8.2 The Bootstrap Sequence

_Peios / Reference / eventd / Startup and Shutdown_

> The seven startup phases, which either complete or fail entirely — configuration, KMES attachment, storage, sockets, and the rest.

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.
<!-- lint-disable-next-line line-length -->
[*bootstrap.the-seven-phases-group-the-work-rather-than-order-it-and-startup-completes-or-fails-entirely]

## 8.2.1 Phase 1 — configuration

1. Read every configuration key under `Machine\System\eventd\`.
   [*bootstrap.every-key-under-machine-system-eventd-is-read-first] The six
   required keys are `EventStorePath`, `LogStorePath`, `MetricStorePath`,
   `QuerySocketPath`, `LogSocketPath` and `MetricSocketPath`; a missing
   or invalid one fails startup.
<!-- lint-disable-next-line line-length -->
   [*bootstrap.the-six-required-keys-are-the-three-store-paths-and-three-socket-paths]
   [*bootstrap.a-missing-or-invalid-required-key-fails-startup]
2. Open and validate the three provisioned store directories without
   following symbolic links.
   [*bootstrap.store-directories-are-opened-without-following-symbolic-links]
   A missing directory, unsafe component, or
   descriptor that is not equivalent to the protected platform default
   fails startup (§3.3).
   [*bootstrap.a-missing-or-unsafe-store-directory-fails-startup]
   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).
   [*bootstrap.absent-optional-keys-take-their-compiled-in-defaults]
4. Arm a persistent watch on the subtree, for runtime changes (§8.3).
   [*bootstrap.a-persistent-watch-is-armed-on-the-configuration-subtree]

## 8.2.2 Phase 2 — KMES attachment and shard sizing

5. Query the KMES logical slot count with
   `kmes_attach(KMES_ATTACH_QUERY_SLOTS, …)`, walk every slot, skip
   `EINVAL` holes, and assign dense internal ordinals to successful
   logical CPU IDs (§2.2).
<!-- lint-disable-next-line line-length -->
   [*bootstrap.every-kmes-slot-is-walked-skipping-einval-holes-and-given-a-dense-ordinal]
   The calls require SeSecurityPrivilege in the
   effective token.
<!-- lint-disable-next-line line-length -->
   [*bootstrap.kmes-attachment-requires-sesecurityprivilege-in-the-effective-token]
   Discovering no buffers fails startup.
   [*bootstrap.discovering-no-kmes-buffers-fails-startup]
6. Map each per-CPU ring buffer.
   [*bootstrap.each-per-cpu-ring-buffer-is-mapped]
7. Resolve the active shard count from `StorageShards` — the attached
   KMES-buffer count when it is 0, the configured value otherwise.
   [*bootstrap.storageshards-zero-means-one-shard-per-attached-kmes-buffer]
8. Compute the shard-to-CPU assignment (§2.3).
   [*bootstrap.the-shard-to-cpu-assignment-is-computed-after-the-shard-count]

## 8.2.3 Phase 3 — storage

9. 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).
<!-- lint-disable-next-line line-length -->
   [*bootstrap.each-active-event-shard-is-opened-or-created-in-wal-mode-with-synchronous-full]
   Discover
   historical shards matching the naming pattern, and open those with a
   recognized schema read-only; exclude the rest from the query path.
<!-- lint-disable-next-line line-length spelling -->
   [*bootstrap.historical-shards-with-a-recognised-schema-open-read-only-and-the-rest-are-excluded]
10. Open or create `logs.db` in the log store directory — schema
    verified, WAL, `synchronous=NORMAL`, quarantine on corruption
    (§4.3).
[*bootstrap.logs-db-is-opened-or-created-in-wal-mode-with-synchronous-normal]
11. Open or create `metrics.db` in the metric store directory, likewise
    (§5.4).
<!-- lint-disable-next-line line-length -->
    [*bootstrap.metrics-db-is-opened-or-created-in-wal-mode-with-synchronous-normal]
    The series cache starts empty and fills on demand.
    [*bootstrap.the-series-cache-starts-empty]
12. Open or create `eventd-meta.db`.
<!-- lint-disable-next-line line-length -->
    [*bootstrap.eventd-meta-db-is-opened-or-created] 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).
    [*bootstrap.sequence-checkpoints-are-loaded-for-diagnostics-only]
    [*bootstrap.each-shards-material-indexes-are-discovered-from-its-schema]

## 8.2.4 Phase 4 — the boot boundary

13. Read `/proc/sys/kernel/random/boot_id`, require valid UUID text, and
    convert it to PCDS GUID layout.
    [*bootstrap.the-boot-id-is-read-and-converted-to-pcds-guid-layout]
    An unavailable or malformed value
    fails startup.
    [*bootstrap.an-unavailable-or-malformed-boot-id-fails-startup]
14. Read and merge every committed `receipt_ranges` row for that boot
    from every readable active and historical shard, grouped by logical
    CPU ID (§2.2, §3.1).
<!-- lint-disable-next-line line-length -->
    [*bootstrap.receipt-ranges-for-the-boot-are-merged-from-every-readable-shard-by-cpu]
15. 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).
<!-- lint-disable-next-line line-length -->
    [*bootstrap.a-boot-id-with-no-committed-row-or-receipt-marks-the-boots-first-start]
16. 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).
<!-- lint-disable-next-line line-length spelling -->
    [*bootstrap.each-drains-recovery-coverage-is-initialised-from-the-merged-receipts]

## 8.2.5 Phase 5 — sockets

17. Create the query socket at `QuerySocketPath`.
<!-- lint-disable-next-line line-length -->
    [*bootstrap.the-query-socket-is-created-at-querysocketpath] 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.
    [*bootstrap.a-stale-socket-at-a-socket-path-is-unlinked-first]
    [*bootstrap.a-non-socket-at-a-socket-path-fails-startup] Its
    inherited descriptor is replaced with the protected one that lets
    every authenticated caller connect (§7.1).
    [*bootstrap.the-query-socket-gets-the-authenticated-users-descriptor]
18. 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).
<!-- lint-disable-next-line line-length -->
    [*bootstrap.the-log-socket-gets-the-deny-service-allow-system-broker-descriptor]
19. Create the metric socket at `MetricSocketPath`, then replace its
    inherited descriptor with the protected one that lets every
    authenticated caller send (§7.6).
    [*bootstrap.the-metric-socket-gets-the-authenticated-users-descriptor]
20. Establish and verify the Security Descriptor on all three, before
    any of them accepts or receives anything (§7.6).
<!-- lint-disable-next-line line-length -->
    [*bootstrap.socket-descriptors-are-verified-before-any-socket-accepts-or-receives]

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.
<!-- lint-disable-next-line spelling -->
[*bootstrap.a-stale-socket-eventd-may-no-longer-delete-is-reclaimed-first]

## 8.2.6 Phase 6 — threads

21. One writer thread per active shard.
    [*bootstrap.one-writer-thread-is-started-per-active-shard]
22. One drain thread per attached logical CPU, each beginning to
    reconcile and read its ring buffer.
    [*bootstrap.one-drain-thread-is-started-per-attached-logical-cpu]
23. The log ingestion thread.
    [*bootstrap.one-log-ingestion-thread-is-started]
24. The metric ingestion thread.
    [*bootstrap.one-metric-ingestion-thread-is-started]
25. The retention coordinator thread.
    [*bootstrap.one-retention-coordinator-thread-is-started]
26. The adaptive indexing policy thread.
    [*bootstrap.one-adaptive-indexing-policy-thread-is-started]

## 8.2.7 Phase 7 — ready

27. Write and **commit** an `eventd.daemon.started` event in the boot
    recording whether this start is a restart, the shard count and the
    per-CPU recovered coverage points (§3.2).
<!-- lint-disable-next-line line-length -->
    [*bootstrap.an-eventd-daemon-started-event-records-restart-shard-count-and-per-cpu-coverage]
    The commit
    happens before readiness is signaled.
<!-- lint-disable-next-line spelling -->
    [*bootstrap.the-startup-event-is-committed-before-readiness-is-signalled]
28. Signal readiness to peinit.
<!-- lint-disable-next-line spelling -->
    [*bootstrap.readiness-is-signalled-to-peinit-last]

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.
<!-- lint-disable-next-line spelling -->
[*bootstrap.a-failed-phase-means-readiness-is-never-signalled] It logs the
failure to standard error where standard error exists, and exits
non-zero.
[*bootstrap.a-startup-failure-is-logged-to-stderr-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.
[*bootstrap.there-is-no-degraded-mode-without-a-store-or-kmes]

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_

> Which settings apply immediately, which wait for a restart, which do neither, and what SIGHUP does.

eventd watches `Machine\System\eventd\` and reacts to changes without
restarting — for the settings that can be changed that way.
<!-- lint-disable-next-line line-length -->
[*runtime.eventd-watches-its-configuration-subtree-and-applies-changes-without-restarting]

Notifications arriving **during** startup are queued and processed after
readiness is signaled (§8.2).
<!-- lint-disable-next-line line-length -->
[*runtime.notifications-arriving-during-startup-are-processed-after-readiness] 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.
[*runtime.tuning-parameters-apply-immediately]

A live `MaxBatchSize` change is an atomic update to the event writers'
next commit threshold.
<!-- lint-disable-next-line line-length -->
[*runtime.a-live-maxbatchsize-change-atomically-updates-the-next-commit-threshold]
It does not resize, replace, or drain their
startup-fixed handoff channels (§2.3).
[*runtime.a-live-maxbatchsize-change-leaves-the-handoff-channels-untouched]
The log and metric batch settings
likewise affect only subsequent transaction thresholds.
[*runtime.log-and-metric-batch-changes-affect-only-subsequent-transactions]

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.
<!-- lint-disable-next-line line-length -->
[*runtime.every-applied-change-requests-an-index-policy-run-and-a-retention-pass]

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

[*runtime.a-socket-path-change-waits-for-a-restart]
[*runtime.a-store-path-change-waits-for-a-restart]
[*runtime.a-storageshards-change-waits-for-a-restart]

The watch notices these changes and eventd defers them rather than
attempting a live migration.
<!-- lint-disable-next-line line-length -->
[*runtime.restart-only-changes-are-deferred-not-migrated-live] 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".
[*runtime.a-security-descriptor-change-takes-effect-on-the-next-query]

## 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).
<!-- lint-disable-next-line line-length -->
[*runtime.every-applied-change-emits-a-config-change-event-with-key-and-old-and-new-values]

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.
<!-- lint-disable-next-line line-length -->
[*runtime.an-invalid-value-is-ignored-and-the-value-in-use-is-kept] Unknown keys in the subtree are
ignored entirely. [*runtime.unknown-keys-are-ignored]

## 8.3.5 SIGHUP

`SIGHUP` re-reads the configuration, equivalent to a watch notification
(§8.5). [*runtime.sighup-re-reads-configuration-like-a-watch-notification]
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_

> Persisting as much in-flight data as possible without blocking indefinitely — the sequence, and the timeout that bounds it.

When peinit signals a stop, eventd persists as much in-flight data as it
can without blocking indefinitely.

## 8.4.1 The sequence

1. **Stop accepting.** Unlink all three socket paths so no new client
   can reach them, and stop accepting query connections.
<!-- lint-disable-next-line line-length -->
   [*shutdown.all-three-socket-paths-are-unlinked-and-query-connections-stop-being-accepted]
   Existing
   streaming queries are terminated with an error.
   [*shutdown.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.
   [*shutdown.the-log-and-metric-socket-descriptors-stay-open-after-unlinking]
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.
<!-- lint-disable-next-line line-length -->
   [*shutdown.a-send-after-the-log-and-metric-sockets-are-shut-for-reading-fails-with-epipe]
   Then read and process the datagrams still in the receive queues, and
   close those descriptors.
<!-- lint-disable-next-line line-length -->
   [*shutdown.queued-log-and-metric-datagrams-are-processed-before-their-sockets-close]
   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.
   [*shutdown.each-drain-thread-performs-one-final-drain-cycle]
4. **Final commit.** Every writer commits its current batch immediately,
   whatever its size. The log and metric writers do the same.
   [*shutdown.every-writer-commits-its-current-batch-whatever-its-size]
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).
<!-- lint-disable-next-line line-length -->
   [*shutdown.each-cpus-highest-contiguously-covered-sequence-is-written-to-sequence-checkpoints]
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).
   [*shutdown.an-eventd-daemon-stopped-event-carries-the-per-cpu-sequences]
   If no shard is writable, the event is skipped and the failure
   logged to standard error.
<!-- lint-disable-next-line line-length -->
   [*shutdown.with-no-writable-shard-the-shutdown-event-is-skipped-and-the-failure-logged]
7. **Close databases.** Close every connection, writer, and reader.
   SQLite checkpoints the write-ahead log automatically on close.
   [*shutdown.every-database-connection-is-closed-checkpointing-its-wal]
8. **Unmap.** Unmap every ring buffer and close the per-CPU descriptors.
   [*shutdown.every-ring-buffer-is-unmapped-and-its-descriptor-closed]
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.
[*shutdown.a-stopped-event-writer-releases-pending-control-requests]

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.
[*shutdown.an-unfinished-shutdown-aborts-at-the-peinit-stop-timeout]

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.
<!-- lint-disable-next-line line-length -->
  [*shutdown.event-batches-lost-to-an-aborted-shutdown-are-recovered-from-kmes-at-the-next-start]
- **Uncommitted log and metric batches** are lost, which is acceptable
  by design.
  [*shutdown.an-aborted-shutdown-loses-uncommitted-log-and-metric-batches]
- **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).
<!-- lint-disable-next-line line-length -->
  [*shutdown.stale-sequence-metadata-after-an-aborted-shutdown-does-not-affect-recovery]

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_

> What an ungraceful termination leaves behind, the signals eventd handles, and the diagnostic dump.

## 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.
[*crash.events-emitted-while-eventd-is-down-accumulate-in-the-ring-buffers]

**The databases are consistent.** WAL mode guarantees committed
transactions survive, and SQLite rolls back the in-flight batch on the
next open.
<!-- lint-disable-next-line line-length -->
[*crash.committed-transactions-survive-a-crash-and-the-in-flight-batch-rolls-back]

**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).
<!-- lint-disable-next-line line-length -->
[*crash.restart-re-ingests-uncovered-survivors-and-gaps-only-sequences-in-neither-source]

**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.
[*crash.socket-buffered-logs-and-metrics-are-lost-in-a-crash]

No manual recovery is needed and none is offered.
[*crash.no-manual-recovery-is-needed-or-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.
<!-- lint-disable-next-line line-length spelling -->
[*crash.a-restart-is-recognised-from-committed-rows-or-receipts-not-an-advance-flag]

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

[*crash.sigterm-begins-graceful-shutdown]
[*crash.sigint-begins-graceful-shutdown]
[*crash.sigquit-writes-a-diagnostic-dump-then-begins-graceful-shutdown]
[*crash.sighup-re-reads-configuration-from-the-registry]
[*crash.sigpipe-is-ignored]

Every other signal keeps its default behavior.
<!-- lint-disable-next-line spelling -->
[*crash.every-other-signal-keeps-its-default-behaviour]

## 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.
[*crash.the-diagnostic-dump-is-written-to-stderr-before-shutdown-step-one]
It includes at
least:

- the current boot ID [*crash.the-dump-includes-the-current-boot-id]
- the active shard count and the readable historical shard count
  [*crash.the-dump-includes-the-active-and-readable-historical-shard-counts]
- the per-CPU committed receipt coverage and highest covered sequence
<!-- lint-disable-next-line line-length -->
  [*crash.the-dump-includes-per-cpu-receipt-coverage-and-highest-covered-sequence]
- the current non-streaming and streaming query counts
  [*crash.the-dump-includes-the-non-streaming-and-streaming-query-counts]
- the metric series cache occupancy
  [*crash.the-dump-includes-the-series-cache-occupancy]
- KMES events discarded for claiming one of the five types eventd
  writes itself (§3.1)
  [*crash.the-dump-includes-kmes-events-discarded-for-a-reserved-type]
- log records discarded for an origin outside the origin grammar, and
  the most recent such origin where one exists (§4.1)
<!-- lint-disable-next-line line-length -->
  [*crash.the-dump-includes-invalid-origin-log-discards-and-the-latest-such-origin]
- metric datagrams missing identity, truncated, denied by name policy or
  rejected by an authorization error
<!-- lint-disable-next-line line-length -->
  [*crash.the-dump-includes-metric-datagrams-rejected-for-identity-truncation-policy-or-authorization]
- the cumulative metric type-mismatch count and the latest conflicting
  metric name and expected and received types, where one exists
[*crash.the-dump-includes-the-metric-type-mismatch-count-and-latest-conflict]
- the last observed write error for each store, where one exists
  [*crash.the-dump-includes-the-last-write-error-per-store]

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_

> The one failure that costs something unrecoverable, and why the whole ingestion pipeline is shaped around delaying it.

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).
  [*lostevents.an-overrun-is-detected-as-a-sequence-gap-on-the-affected-cpu]
- An `eventd.events.lost` record is written, naming the missing range.
<!-- lint-disable-next-line line-length -->
  [*lostevents.an-overrun-writes-an-eventd-events-lost-record-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`.
<!-- lint-disable-next-line line-length -->
  [*lostevents.after-an-overrun-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).
<!-- lint-disable-next-line spelling -->
[*lostevents.a-query-exceeding-querytimeoutms-is-cancelled-with-an-error]
Read-only connections are released; nothing is lost,
and the query did not finish.
[*lostevents.a-timed-out-query-releases-its-read-only-connections]

Streaming queries are bounded only up to `watch`; past that the watch
phase is not time-limited.
[*lostevents.the-watch-phase-of-a-streaming-query-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).
[*lostevents.a-datagram-dropped-on-a-full-receive-queue-is-not-counted]

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.
[*lostevents.a-socket-queue-is-not-drained-while-its-batch-commits]

---

# 9.2 Storage Failure

_Peios / Reference / eventd / Failure Modes_

> What a full disk does to each of the three stores, and how corruption is detected and contained.

## 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).
<!-- lint-disable-next-line line-length -->
[*storagefail.a-disk-full-or-quota-write-failure-triggers-an-immediate-retention-run-on-every-enabled-store]
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).
[*storagefail.a-write-refused-for-want-of-space-emits-no-storage-error]

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.
<!-- lint-disable-next-line line-length -->
[*storagefail.a-failed-event-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.
[*storagefail.a-failed-event-batch-is-lost] 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).
[*storagefail.failed-batch-ranges-are-held-in-an-in-memory-lost-batch-list]
<!-- lint-disable-next-line line-length -->
[*storagefail.lost-batch-gap-records-are-written-before-new-events-on-the-next-successful-commit]

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.
<!-- lint-disable-next-line line-length -->
[*storagefail.a-failed-event-batch-is-logged-to-stderr-with-its-cpus-and-sequence-ranges]
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.
<!-- lint-disable-next-line line-length -->
[*storagefail.a-crash-before-disk-recovery-still-records-the-loss-through-restart-reconciliation]

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.
<!-- lint-disable-next-line line-length -->
[*storagefail.a-failed-log-or-metric-commit-loses-the-batch-and-the-writer-carries-on]
Acceptable under the loss model, and no lost-batch accounting exists for
either — there is nothing to reconcile against, since neither has
sequence numbers.
[*storagefail.the-log-and-metric-stores-have-no-lost-batch-accounting]

## 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.
<!-- lint-disable-next-line line-length -->
[*storagefail.startup-corruption-detection-checks-that-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. [*storagefail.startup-does-not-run-integrity-check] 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).
<!-- lint-disable-next-line line-length -->
[*storagefail.a-corrupt-required-store-at-startup-is-quarantined-and-replaced-with-an-empty-database]
It logs the corruption and
emits `eventd.store.quarantined` once a shard is available to hold it.
<!-- lint-disable-next-line line-length -->
[*storagefail.startup-corruption-is-logged-and-reported-by-a-storage-error-event]

**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.
<!-- lint-disable-next-line line-length -->
[*storagefail.write-time-corruption-quarantines-and-replaces-the-database-and-writes-resume]

**At query time**, a handler encountering corruption fails the affected
query with an error.
<!-- lint-disable-next-line line-length -->
[*storagefail.query-time-corruption-fails-the-affected-query] 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.
[*storagefail.a-query-failed-by-corruption-returns-no-partial-rows]

A missing or unrecognized **schema version** is not corruption.
<!-- lint-disable-next-line line-length -->
[*storagefail.a-missing-or-unrecognised-schema-version-is-not-treated-as-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).
[*storagefail.a-required-store-with-a-bad-schema-version-fails-startup]
<!-- lint-disable-next-line line-length -->
[*storagefail.a-historical-shard-with-a-bad-schema-version-is-excluded-from-queries]

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.
[*storagefail.eventd-never-attempts-automatic-repair-of-a-quarantined-file]

---

# 9.3 Losing Dependencies

_Peios / Reference / eventd / Failure Modes_

> Two of eventd's four dependencies can vanish after startup without stopping it — what survives, and what stops working.

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.
  [*lostdeps.without-the-registry-the-last-known-configuration-is-kept]
- Descriptor lookups fall back to the cache.
  [*lostdeps.without-the-registry-descriptor-lookups-fall-back-to-the-cache]
  A pattern the cache does
  not hold is **denied**, fail-closed (§7.5).
  [*lostdeps.without-the-registry-an-uncached-descriptor-pattern-is-denied]
- eventd keeps ingesting and keeps serving queries for descriptors it
  already resolved, indefinitely.
<!-- lint-disable-next-line line-length -->
  [*lostdeps.without-the-registry-ingestion-and-queries-on-cached-descriptors-continue-indefinitely]
- When the registry returns, the watch fires and eventd re-reads.
  [*lostdeps.when-the-registry-returns-eventd-re-reads-its-configuration]

This is a degraded state, not a failure. eventd does not exit, and it
does not stop collecting.
[*lostdeps.registry-loss-does-not-make-eventd-exit-or-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.
<!-- lint-disable-next-line line-length -->
[*lostdeps.a-failed-watch-discards-the-descriptor-cache-and-fails-closed-until-re-established]
`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.
  [*lostdeps.without-kacs-new-query-connections-are-denied]
- `kacs_access_check` and `kacs_access_check_list` fail, so a query in
  progress that needs a fresh check is denied.
  [*lostdeps.without-kacs-a-query-needing-a-fresh-access-check-is-denied]
- Cached check results stay valid for the duration of the query that
  obtained them.
<!-- lint-disable-next-line line-length -->
  [*lostdeps.cached-access-check-results-stay-valid-for-the-query-that-obtained-them]
- **Event ingestion is unaffected.** Neither the drain nor the write
  path calls KACS (§8.1).
  [*lostdeps.without-kacs-event-ingestion-is-unaffected]
- Log ingestion is unaffected.
  [*lostdeps.without-kacs-log-ingestion-is-unaffected]
- Metric ingestion continues, but every record needs an `EVENTD_PUBLISH`
  check (§7.6). A record whose verdict is cached for the sender's token
  and name is stored as usual; one needing a fresh check is refused and
  counted as an authorization error, and the rest of its datagram is
  still taken.
<!-- lint-disable-next-line line-length -->
  [*lostdeps.without-kacs-a-metric-record-needing-a-fresh-publish-check-is-refused]

Established event ingestion continues. Queries or metric records that
need a fresh failing access check are rejected. Those operations resume
when KACS checks succeed. [*lostdeps.query-service-resumes-when-kacs-returns]

## 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).
[*lostdeps.a-ring-buffer-resize-is-a-generation-change-not-a-failure]

## 9.3.4 peinit

peinit manages eventd's lifecycle but supplies no runtime service to it.
[*lostdeps.peinit-supplies-no-runtime-service-to-eventd]
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_

> Memory, query slots, descriptors, and writer stalls — how each runs out, and what eventd does when it does.

## 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.
[*exhaust.an-oom-kill-is-recovered-exactly-like-a-crash]

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

[*exhaust.series-cache-memory-is-bounded-by-metricseriescachesize]
<!-- lint-disable-next-line line-length spelling -->
[*exhaust.intern-set-memory-has-no-independent-bound-beyond-catalogue-cardinality]
[*exhaust.adaptive-index-counter-memory-is-bounded-by-the-event-query-surface]
[*exhaust.sqlite-page-cache-memory-is-bounded-per-connection]
<!-- lint-disable-next-line line-length -->
[*exhaust.handoff-channel-memory-is-bounded-by-startup-fixed-slot-and-byte-limits]

The handoff limits do not follow live `MaxBatchSize` changes.
[*exhaust.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).
[*exhaust.a-query-beyond-the-concurrency-limits-is-rejected-not-queued]
The per-user bound keeps one caller from occupying every slot; several
callers together, or SYSTEM, still can.
[*exhaust.one-user-cannot-occupy-every-query-slot]

Ingestion is unaffected, because queries and ingestion are separate
channels and separate threads.
<!-- lint-disable-next-line line-length -->
[*exhaust.query-slot-exhaustion-does-not-affect-ingestion] 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).
<!-- lint-disable-next-line line-length -->
[*exhaust.a-query-whose-resources-cannot-be-allocated-fails-without-blocking-a-writer]

## 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).
<!-- lint-disable-next-line line-length -->
[*exhaust.rising-write-pressure-cancels-an-index-build-and-event-writing-resumes]

**A writer-owned maintenance command.** Retention and adaptive-index
maintenance execute only as bounded, low-priority commands at
transaction boundaries.
<!-- lint-disable-next-line line-length -->
[*exhaust.maintenance-runs-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).
[*exhaust.ingestion-takes-priority-over-the-next-maintenance-command]

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_

> The failure the three stores' durability settings were chosen against, and what a restart does afterward.

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

[*powerloss.every-committed-event-transaction-survives-power-loss]
[*powerloss.log-transactions-survive-only-up-to-the-last-checkpoint]
[*powerloss.metric-transactions-survive-only-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).
<!-- lint-disable-next-line line-length -->
[*powerloss.the-event-store-loses-only-the-in-flight-batch] 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.
[*powerloss.no-gap-record-is-written-for-a-batch-lost-to-power-loss]
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).
[*powerloss.a-new-boots-per-cpu-coverage-starts-before-sequence-1]
It does not compare a new boot's ring
against the previous boot's receipts: those are different sequence
namespaces.
<!-- lint-disable-next-line line-length -->
[*powerloss.a-new-boots-ring-is-never-reconciled-against-the-previous-boots-receipts]

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_

> Run eventd queries from a terminal or pipeline, select a stable output encoding, and understand when results become visible.

`evctl` is eventd's native command-line client. Its normal operation has no
subcommand: the one positional argument is a PSPU observability query.
[*evctl.the-one-positional-argument-is-a-query-with-no-subcommand]

```sh
evctl 'EVENTS kacs.* SINCE 1h ago TAKE 50'
evctl 'LOGS FROM authd ERROR ONLY STREAM'
evctl 'METRIC cpu.usage SINCE 10m ago AVG'
```

Quote the complete query. Without the quotes, the shell can split string
literals or expand `*` patterns before `evctl` sees them. Query syntax and
semantics remain those of PSPU §3.18–§3.27; `evctl` does not maintain a second
flag-based query language.
[*evctl.evctl-uses-pspu-query-syntax-and-has-no-flag-based-query-language]

## 10.1.1 Commands and queries

Exact standalone words such as `help` and `version` occupy the command
namespace.
[*evctl.exact-standalone-words-such-as-help-and-version-are-commands]
Anything whose first word is `EVENTS`, `LOGS` or `METRIC`, matched
without regard to ASCII case, is a query.
[*evctl.a-first-word-of-events-logs-or-metric-in-any-ascii-case-is-a-query]
This leaves room for administrative commands without requiring the common
query operation to be written as `evctl query ...`.

The query can instead be read from a UTF-8 file or standard input:
[*evctl.the-query-can-be-read-from-a-utf-8-file-or-standard-input]

```sh
evctl --file denied-events.evq
printf '%s\n' 'EVENTS eventd.* SINCE 1d ago' | evctl -
```

The default socket is `/run/eventd/query.sock`.
[*evctl.the-default-socket-is-run-eventd-query-sock]
`--socket PATH` selects a nonstandard configured socket.
[*evctl.socket-selects-a-nonstandard-query-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.
[*evctl.evctl-never-opens-a-database-or-makes-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.
[*evctl.data-goes-to-standard-output-and-diagnostics-to-standard-error]

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

[*evctl.pretty-is-the-default-format-with-one-record-per-line]
[*evctl.jsonl-writes-one-object-per-record-and-tags-values-json-cannot-carry]
[*evctl.msgpack-prefixes-each-record-with-a-four-byte-little-endian-length]

Records do not have a uniform schema. A field absent from one line is not
necessarily absent from later lines.
[*evctl.records-in-one-result-do-not-share-a-uniform-schema] 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.
<!-- lint-disable-next-line line-length -->
[*evctl.a-result-commits-only-on-end-or-watch-and-an-earlier-error-invalidates-it]

`evctl` therefore renders initial records into an anonymous temporary spool.
[*evctl.initial-records-are-rendered-into-an-anonymous-temporary-spool]
It publishes the spool to standard output only after `end` or `watch`.
[*evctl.the-spool-is-published-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. [*evctl.the-spool-bounds-heap-use-and-has-no-pathname]

After `watch`, new records are written directly as they arrive.
[*evctl.after-watch-new-records-are-written-directly] Closing `evctl`,
including with Ctrl-C, closes the query connection and ends the watch.
[*evctl.closing-evctl-closes-the-query-connection-and-ends-the-watch]

As with every streaming client, a blocked output pipeline eventually applies
socket backpressure.
[*evctl.a-blocked-output-pipeline-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_

> The Rust library a program uses to query eventd, follow it live, write query text safely, and tell its user what eventd will let them read.

`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.
[*client.eventd-client-is-the-library-for-programs-that-query-eventd]

It depends on the `peios` crate and nothing of eventd's own, so a
program using it brings in neither SQLite nor eventd's storage.

## 10.2.1 Whole results or none

PSPU §3.16 says an `error` that arrives before the terminal message
voids every result message before it. The library keeps that rule
itself, so a program cannot show part of a result as if it were all of
it.

- `query(socket, text)` runs a query that does not stream and returns
  every record once `end` has arrived, or the error and no records.
  [*client.query-returns-a-whole-result-or-none]
- `Tail::start(socket, text, capacity)` follows a `STREAM` query. It
  reports the initial result **once**, complete, when `watch` arrives;
  then each live batch; then why the tail ended. If the query fails
  before `watch`, the only report is that it ended.
  [*client.a-tail-reports-its-initial-result-once-complete]

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. [*client.a-tail-reads-its-socket-on-its-own-thread]

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. [*client.a-tail-a-program-stops-reading-is-ended-by-eventd]

Dropping the `Tail` closes the connection, which eventd treats as
canceling the query (PSPU §3.14).

## 10.2.3 Writing query text

The `text` module writes a value into query text so that it is always
exactly one value (PSPU §3.19).

- `string` writes a quoted string: the quote and backslash escaped, and
  every control character as `\n`, `\r`, `\t` or `\uXXXX`.
  [*client.text-string-escapes-quotes-backslashes-and-controls]
- `binary` writes `x"…"`; `duration` writes `90s`, `2h` and so on, in the
  largest unit that holds the duration exactly.

Every place the language takes an identifier or a pattern also takes a
quoted string, so text a person typed should always go through `string`.
Written bare, an event type called `STREAM` or `WHERE` would be read as
the clause, since the pattern after `EVENTS` is optional. After
`LOGS FROM`, which always takes an origin, the same word is read as the
origin, but quoting is never wrong there either.
[*client.text-a-person-typed-is-always-quoted]

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.
[*client.access-checks-the-descriptors-eventd-checks]

- 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.
  [*client.eventd-and-its-clients-share-the-rights-mapping-and-pattern-walk]
- `field_guid` derives a field's GUID (§7.3). eventd-core computes the
  same derivation for itself, and a test holds the two equal.
- `resolve` finds the descriptor eventd would check an identifier
  against: the identifier, each shorter dotted prefix, then `*`, with an
  origin's producer left off (§7.2).
- `access` checks a descriptor the way eventd does: the calling
  process's own token, eventd's mapping, and the object type list of the
  data type's root and the paths of any fields asked about (§7.3), then
  every field the descriptor grants by name. Records are visible with
  `EVENTD_READ` on the root or on any field, as eventd shows them
  (§7.4).
  [*client.records-are-visible-with-read-on-the-root-or-any-field]
- `field_tree` builds that list for a set of field names, and
  `field_reads` makes the check over it, answering per field; eventd
  uses both, so the tree a client asks about is the one eventd builds.
- `field_grants` lists the fields a descriptor grants by name: the
  object GUIDs of its allowing object ACEs. eventd uses it too, to find
  which identifiers a field-only grant makes visible.
  [*client.field-grants-are-the-object-guids-of-allowing-object-aces]
- `readable` says how much of events, logs or metrics the caller can
  read across **every** pattern written for them, since a more specific
  pattern can grant what `*` denies, and the other way round: everything,
  some (and which patterns it can not read), nothing, or unknown.
  [*client.readable-considers-every-pattern]

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. [*client.unreadable-policy-is-unknown-not-denied]

---

# Appendix A Configuration Keys

_Peios / Reference / eventd_

> Every configuration key under the eventd registry subtree, its type and default, and how an invalid value is treated.

Every key lives under `Machine\System\eventd\`.
[*config.every-key-lives-under-machine-system-eventd] eventd ignores unknown
keys in the subtree. [*config.unknown-keys-in-the-subtree-are-ignored] 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).
[*config.an-invalid-value-is-ignored-and-the-value-in-use-is-retained]

## A.1 Required

No compiled-in defaults. A missing or invalid value fails startup
(§8.2). [*config.a-missing-or-invalid-required-key-fails-startup]

| Key | Type | Description |
|---|---|---|
| `EventStorePath` | REG_SZ | Provisioned directory for event shards and `eventd-meta.db`; standard deployment `/var/state/eventd/events/`. |
| `LogStorePath` | REG_SZ | Provisioned directory for `logs.db`; standard deployment `/var/state/eventd/logs/`. |
| `MetricStorePath` | REG_SZ | Provisioned directory for `metrics.db`; standard deployment `/var/state/eventd/metrics/`. |
| `QuerySocketPath` | REG_SZ | Unix socket path for queries. |
| `LogSocketPath` | REG_SZ | Unix socket path for log ingestion. |
| `MetricSocketPath` | REG_SZ | Unix socket path for metric ingestion. |
[*config.event-store-path-is-the-directory-for-event-shards-and-eventd-meta-db]
[*config.log-store-path-is-the-directory-for-logs-db]
[*config.metric-store-path-is-the-directory-for-metrics-db]
[*config.query-socket-path-is-the-query-socket]
[*config.log-socket-path-is-the-log-ingestion-socket]
[*config.metric-socket-path-is-the-metric-ingestion-socket]

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

[*config.wal-checkpoint-pages-defaults-to-1000-on-every-database]

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

[*config.storage-shards-defaults-to-0-meaning-the-attached-kmes-buffer-count]
[*config.max-batch-size-defaults-to-10000-events-per-transaction]
[*config.max-batch-latency-defaults-to-100-ms]

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

[*config.log-max-batch-size-defaults-to-5000-records-per-transaction]
[*config.log-max-batch-latency-defaults-to-500-ms]
<!-- lint-disable-next-line line-length -->
[*config.max-log-datagram-bytes-defaults-to-the-262144-floor-and-cannot-go-lower]

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

[*config.metric-max-batch-size-defaults-to-5000-samples-per-transaction]
[*config.metric-max-batch-latency-defaults-to-1000-ms]
<!-- lint-disable-next-line line-length -->
[*config.max-metric-datagram-bytes-defaults-to-the-262144-floor-and-cannot-go-lower]
[*config.metric-series-cache-size-defaults-to-50000-entries]
[*config.metric-authorization-cache-size-defaults-to-16384-verdicts]
[*config.health-metric-interval-defaults-to-15-seconds-and-zero-turns-it-off]

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

[*config.adaptive-index-window-defaults-to-24-hours]
<!-- lint-disable-next-line line-length -->
[*config.adaptive-index-policy-interval-defaults-to-and-cannot-go-below-60-minutes]
[*config.adaptive-index-create-threshold-defaults-to-100-queries]
[*config.adaptive-index-drop-threshold-defaults-to-10-queries]

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

[*config.shedding-window-defaults-to-30-seconds]
<!-- lint-disable-next-line line-length -->
[*config.graduated-shedding-defaults-to-75-percent-of-batches-over-75-percent-of-max-batch-size]
[*config.emergency-shedding-defaults-to-75-percent-ring-buffer-fill]

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

[*config.event-retention-defaults-to-30-days]
[*config.event-retention-max-bytes-defaults-to-0-meaning-no-limit]
[*config.log-retention-defaults-to-14-days]
[*config.log-retention-max-bytes-defaults-to-0-meaning-no-limit]
[*config.metric-retention-defaults-to-90-days]
[*config.metric-retention-max-bytes-defaults-to-1-gib-and-0-disables-it]
[*config.retention-check-interval-defaults-to-60-minutes]
[*config.retention-delete-batch-defaults-to-10000-rows-per-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). |

[*config.query-timeout-defaults-to-30000-ms]
[*config.max-concurrent-queries-defaults-to-128-globally-including-streaming]
[*config.max-streaming-queries-defaults-to-64-globally]
[*config.max-queries-per-user-defaults-to-16-and-does-not-count-system]
[*config.max-distinct-stream-values-defaults-to-100000-per-query]
[*config.max-query-request-bytes-is-a-hard-limit-defaulting-to-65536]
[*config.query-response-target-bytes-is-a-soft-target-defaulting-to-65536]
[*config.max-query-held-bytes-defaults-to-256-mib-across-all-queries]

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

[*config.adaptive-rollup-min-samples-defaults-to-1000-raw-inputs]
[*config.adaptive-rollup-batch-rows-defaults-to-512-windows-per-command]
[*config.adaptive-rollup-max-rows-defaults-to-100000-and-0-disables-the-cache]

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

<!-- lint-disable-next-line spelling -->
[*config.cross-type-window-defaults-to-a-centred-15000-ms]
[*config.cross-type-max-lookback-defaults-to-604800-seconds]

## A.12 The security subtree

[*config.read-path-descriptors-live-under-the-security-subtree]

Read-path descriptors live under `Machine\System\eventd\Security\` and
are not configuration in the sense above (§7.2):

```text
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.
<!-- lint-disable-next-line line-length -->
[*config.security-admin-governs-eventd-administer-and-defaults-to-system-and-administrators]
It is registry-protected policy, not data in `eventd-meta.db` (§3.5,
§7.2).
[*config.the-admin-descriptor-is-registry-policy-not-metadata-database-data]

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

[*config.every-tuning-parameter-applies-immediately]
[*config.a-socket-path-change-waits-for-a-restart]
[*config.a-store-path-change-waits-for-a-restart]
[*config.a-storage-shards-change-waits-for-a-restart]
[*config.a-security-descriptor-change-applies-from-the-next-query]

---

# Appendix B Constants

_Peios / Reference / eventd_

> eventd's own constants — access rights, generic mapping, the field GUID namespace, data type roots and origin names.

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

[*constant.eventd-read-is-bit-0-value-0x0001]
[*constant.eventd-clear-is-bit-1-value-0x0002-and-reserved]
[*constant.eventd-administer-is-bit-2-value-0x0004-and-governs-index]
<!-- lint-disable-next-line line-length -->
[*constant.eventd-publish-is-bit-3-value-0x0008-and-governs-metric-publication]

## B.2 Generic mapping

Passed to AccessCheck in the `generic_read`, `generic_write`,
`generic_execute` and `generic_all` fields.
[*constant.eventd-passes-its-generic-mapping-to-accesscheck]

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

[*constant.generic-read-maps-to-0x00020001]
<!-- lint-disable-next-line hex-case -->
[*constant.generic-write-maps-to-0x0002000e]
[*constant.generic-execute-maps-to-0x00020001]
<!-- lint-disable-next-line hex-case -->
[*constant.generic-all-maps-to-0x000f000f]

`EVENTD_ADMINISTER` and `EVENTD_PUBLISH` are in `GENERIC_WRITE` and
deliberately not in `GENERIC_READ` or `GENERIC_EXECUTE` (§7.1, §7.6).
[*constant.administer-and-publish-are-not-in-generic-read-or-generic-execute]

## B.3 Field GUID namespace

[*constant.the-field-guid-namespace-is-e7d3a1b0-5c2f-4e8a-9b1d-0a6f3c8e2d4b]

```text
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).
<!-- lint-disable-next-line line-length -->
[*constant.a-field-guid-is-uuid-v5-of-the-utf-8-field-name-in-the-eventd-namespace]

## B.4 Data type root GUIDs

The level-0 node of an object type list.
[*constant.a-data-type-root-guid-is-the-level-0-object-type-list-node]

| Data type | GUID |
|---|---|
| Events | `{a1b2c3d4-0001-4000-8000-000000000001}` |
| Logs | `{a1b2c3d4-0001-4000-8000-000000000002}` |
| Metrics | `{a1b2c3d4-0001-4000-8000-000000000003}` |

[*constant.the-events-root-guid-is-a1b2c3d4-0001-4000-8000-000000000001]
[*constant.the-logs-root-guid-is-a1b2c3d4-0001-4000-8000-000000000002]
[*constant.the-metrics-root-guid-is-a1b2c3d4-0001-4000-8000-000000000003]

## B.5 Field names

Field GUIDs are **computed from the algorithm, never hardcoded**.
[*constant.field-guids-are-computed-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).
[*constant.the-nine-event-header-field-names]

**Log fields.** `timestamp`, `origin`, `is_error`, `message`, `job_id`,
`boot_id`. [*constant.the-six-log-field-names]

**Fixed metric fields.** `timestamp`, `boot_id`, `name`, `type`,
`value`. [*constant.the-five-fixed-metric-field-names]

**Event payload fields** use the flattened dot path (PSPU §3.22).
[*constant.a-payload-field-name-is-its-flattened-dot-path]
Suppressed paths, and payload paths at or beneath a header field's
path, are not query-language fields and have no GUID.
[*constant.suppressed-and-header-colliding-payload-paths-have-no-field-guid]

**Metric label keys** use the key itself: `core` produces
`uuid_v5(EVENTD_FIELD_NAMESPACE, "core")`.
[*constant.a-metric-label-field-name-is-the-label-key-itself] A label key
can never be one of the five fixed metric field names, because ingestion
rejects records whose labels collide with them.
<!-- lint-disable-next-line line-length -->
[*constant.ingestion-rejects-labels-that-collide-with-fixed-metric-field-names]

## B.6 Origin class

| Value | Origin |
|---|---|
| 0 | userspace |
| 1 | KMES |
| 2 | KACS |
| 3 | LCS |
| 4 | NTFE |

[*constant.origin-class-0-is-userspace]
[*constant.origin-class-1-is-kmes]
[*constant.origin-class-2-is-kacs]
[*constant.origin-class-3-is-lcs]
[*constant.origin-class-4-is-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).
[*constant.the-query-language-accepts-origin-class-names-as-aliases]

## B.7 Synthetic event types

| Type | Emitted when |
|---|---|
| `eventd.daemon.started` | eventd starts and attaches to KMES. |
| `eventd.daemon.stopped` | Graceful shutdown has committed everything read. |
| `eventd.events.lost` | A sequence gap is detected on a CPU. |
| `eventd.config.changed` | A configuration value is applied at runtime. |
| `eventd.store.quarantined` | A store is found corrupt and quarantined. |
[*constant.eventd-daemon-started-is-emitted-when-eventd-starts-and-attaches-to-kmes]
[*constant.eventd-daemon-stopped-is-emitted-on-graceful-shutdown]
[*constant.eventd-events-lost-is-emitted-when-a-cpu-sequence-gap-is-detected]
[*constant.eventd-config-changed-is-emitted-when-a-value-is-applied-at-runtime]
[*constant.eventd-store-quarantined-is-emitted-when-a-store-is-found-corrupt-and-quarantined]

All five are tier `essential`. These five names, and no others, are
reserved: a KMES event of one of these types is not stored (§3.1).
Payload schemas are in §3.2.

## B.8 Metric types

| Value | Type |
|---|---|
| 0 | counter |
| 1 | gauge |
| 2 | histogram |

[*constant.metric-type-0-is-counter]
[*constant.metric-type-1-is-gauge]
[*constant.metric-type-2-is-histogram]

Stored in `series.type`. [*constant.the-metric-type-is-stored-in-series-type]
The query language exposes the names, not the numbers (PSPU §3.22).
[*constant.the-query-language-exposes-metric-type-names-not-numbers]

## B.9 Log severity

| Value | Meaning |
|---|---|
| 0 | Normal — standard output. |
| 1 | Error — standard error, or explicitly marked. |

[*constant.log-severity-0-is-normal-standard-output]
[*constant.log-severity-1-is-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).
[*constant.is-error-is-stored-as-an-integer-and-exposed-as-a-boolean]

## B.10 Series hashing

FNV-1a, 64-bit, over the exact bytes of the canonical label string or
the boundary blob.
<!-- lint-disable-next-line line-length -->
[*constant.series-hashes-are-64-bit-fnv-1a-over-the-exact-label-string-or-boundary-bytes]

| Parameter | Value |
|---|---|
| Offset basis | `0xCBF29CE484222325` |
| Prime | `0x100000001B3` |
| Stored as | `hash & 0x7FFF_FFFF_FFFF_FFFF` |

<!-- lint-disable-next-line hex-case -->
[*constant.the-fnv-offset-basis-is-0xcbf29ce484222325]
<!-- lint-disable-next-line hex-case -->
[*constant.the-fnv-prime-is-0x100000001b3]
[*constant.the-stored-series-hash-has-its-high-bit-cleared]

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).
<!-- lint-disable-next-line line-length -->
[*constant.series-identity-is-always-confirmed-against-the-full-string-or-blob]

## B.11 Schema versions

| Store | Version |
|---|---|
| Event shard | 1 |
| Log store | 1 |
| Metric store | 3 |
| `eventd-meta.db` | 1 |

[*constant.the-event-shard-schema-version-is-1]
[*constant.the-log-store-schema-version-is-1]
[*constant.the-metric-store-schema-version-is-3]
[*constant.the-metadata-database-schema-version-is-1]

An unrecognized version is never migrated.
[*constant.an-unrecognised-schema-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).
<!-- lint-disable-next-line line-length -->
[*constant.an-unrecognised-version-fails-a-required-store-excludes-a-historical-shard-and-recreates-metadata]

---

# Appendix C Performance Review

_Peios / Reference / eventd_

> The implementation mechanisms and measurements used when reviewing eventd throughput, latency, and bounded resource use.

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 — a single-threaded reconciler that executes PNP's interface layer, runs its own DHCPv4, router-discovery and DHCPv6 clients, and publishes readiness and DNS facts. What is unusual about it.

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

```text
   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_

> The scope of the netd manual, the documents it leans on for the policy vocabulary, the resolver channel and the kernel's side of the network context, and the version it describes.

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_

> The terms this manual uses for netd's own concepts — interface, joined, profile, generation, pass, desired state, network, scope,  and level.

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_

> The service definition netd ships, and the order netd does things in when it starts — which failures are fatal and which only degrade it — up to the first pass and READY=1.

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:

```text
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 [*startup.sequence]

netd does these steps in this order:

1. **Opens rtnetlink**: one socket for requests and dumps, and a
   second subscribed to the link, IPv4 and IPv6 address, and IPv4 and
   IPv6 route multicast groups. Failure is fatal.
2. **Opens the control socket** at `/run/netd/control.sock`, removing a
   stale one first (§9.1). Failure is fatal.
3. **Opens the udp/68 absorber** (§5.6). Failure is a warning: netd runs
   without it, and a DHCP server's unicast reply can draw an ICMP
   port-unreachable from the kernel.
4. **Switches the kernel's RA processing off** on every interface that
   exists, and in `all` and `default` (§6.1). This happens before any
   link is brought up.
5. **Reads the configuration** (§2.3) and builds a generation from it
   (§3.2). A generation that fails to build at startup is logged as
   refused, and netd runs with an empty policy, so the backstop ignores
   every interface until a good generation is written.
6. **Arms the registry watch** on `Machine\System\Network`. Failure is a
   warning, and the configuration is then read once, never again.
7. **Dumps the kernel's state** (links, addresses and routes, both
   families). Failure is fatal.
8. **Runs the first pass** (§2.2): every interface is judged, every
   static address applied, every client that is due started.
9. **Sends `READY=1` ** on the notify socket.

Readiness is reported after the first pass, not after any lease arrives.
A lease is a network event, not a startup one. A service that needs an
address waits on a readiness level (§8.2), not on netd being ready.
[*startup.ready-after-first-pass-not-a-lease]

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.
[*startup.tie-at-startup-is-a-conflict-not-a-refusal]

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.
[*startup.missing-root-is-read-once]

## 2.1.3 Restart [*startup.restart-reacquires-the-lease]

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's single thread and single poll — its inputs, how each one leads to a full pass or a reconcile, and the converge sequence that repeats until the kernel stops changing.

netd is one thread around one `poll(2)`. [*loop.one-thread-one-poll] 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.
[*loop.kernel-event-redumps-and-converges]

## 2.2.2 A full pass [*loop.full-pass-sequence]

A full pass runs these steps, in this order:

1. identify networks on joined interfaces with carrier (§7.1);
2. bring the interface table in line with the kernel's links and judge
   every non-loopback interface (§3.3), stopping the clients of an
   interface that lost carrier or whose outcome changed;
3. start DHCPv4 clients where due (§5.1);
4. start or stop router discovery and DHCPv6 (§6.1, §6.3);
5. reconcile every interface (§4.3) and dump the kernel's state again.

It then repeats steps 1 to 5 while the dump differs from the one before the
reconcile. [*loop.converge-repeats-until-stable] 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.
[*loop.lease-marks-for-rejudgement]

---

# 2.3 Reading the Registry

_Peios / Reference / netd / The Daemon_

> What netd reads from Machine\System\Network, how values are lowered before anything interprets them, the depth limit, and what a registry change causes.

netd reads its configuration from `Machine\System\Network`, whole, every time
it reads it.

## 2.3.1 What is read [*config.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 [*config.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.
[*config.tree-read-sixteen-deep]

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 [*config.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_

> How netd resolves the profile tree — inheritance, Enabled, the accepted shapes of every value, what refuses the generation, and what a bare profile does.

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. [*profile.every-key-is-a-profile]

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`.
[*profile.lookup-is-case-insensitive]

A key whose name is empty or contains `/` or `\` refuses the generation.

### 3.1.1.1 Inheritance [*profile.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 [*profile.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 [*profile.value-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 |

[*profile.values-as-tabled]

A value name not in this table (case-insensitively) refuses the generation
with `profile <path>: unknown value <name>`, the name as written.
[*profile.unknown-name-refuses]

After parsing, any `Address.Static` entry outside the profile's families
is dropped without an error: the family switch wins.
[*profile.statics-outside-families-dropped]

## 3.1.4 A bare profile [*profile.bare-profile-does-nothing]

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_

> How netd turns Rules\Interface and Profiles\ into a generation with pnp-core — the JOIN of a disabled profile, what refuses a generation, lints, and what a refusal leaves in force.

A generation is built whenever the rules or the profiles have changed (§2.3),
and once at startup.

## 3.2.1 The order of the build

1. **Profiles** are resolved (§3.1). Any error refuses the generation.
2. If `Rules\Interface` does not exist, the generation has no forest.
   Every interface meets the backstop, `IGNORE`, and the profiles are
   kept for nothing to name. [*generation.no-rules-means-backstop]
3. Each subkey of `Rules\Interface` is a root rule. Its tree is lowered
   to `pnp-core`'s input and built as the `Interface` layer with
   `build_forest` — the same ingestion, condition parsing, and lints the
   kernel applies to the packet layers (PKM §6.5). Every build error
   refuses the generation.
4. Every profile a `JOIN` names is looked up. A `JOIN` naming no profile
   refuses the generation with `JOIN(<path>) names no profile`.
   [*generation.dangling-join-refuses]

## 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.
[*generation.join-of-disabled-profile-abstains]

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`. [*generation.join-target-recognized-loosely]

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

[*generation.refusal-causes]

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.
[*generation.never-at-layer-is-a-lint]

## 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>`.
[*generation.runtime-tie-refuses]

## 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.
[*generation.refusal-keeps-last-good-and-is-reported] 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_

> The facts netd gives the interface layer, when an interface is judged, how a verdict and its attribution are read off the evaluation, conflicts, and what a change of verdict does.

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 [*judgment.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 [*judgment.when]

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.
[*judgment.loopback-never-judged]

## 3.3.3 The verdict [*judgment.verdict]

`pnp-core` evaluates the forest and netd reads the result:

- `JOIN(i)`: the profile the forest's `i` th `JOIN` names, looked up
  case-insensitively. netd stands the interface in that profile.
- `DOWN`: the interface is kept administratively down.
- anything else, including the backstop: `IGNORE`.

The attribution is the evaluation's: the path of the rule that spoke, or
`backstop` when none did.

## 3.3.4 Conflicts [*judgment.conflict-ignores-and-names-both]

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 [*judgment.change-restarts-clients]

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 |

[*judgment.verdict-effects]

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. [*judgment.ignore-leaves-what-was-there]

---

# 4.1 Identity and Carrier

_Peios / Reference / netd / Interfaces_

> How netd classifies a link, derives its stable interface id, bus path and driver, and what appearing, disappearing and losing carrier do.

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 [*ifid.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 [*ifid.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 [*ifid.derivation]

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.
[*ifid.stable-across-renames-and-boots]

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 [*ifid.appear-disappear]

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 [*ifid.carrier-loss]

netd counts an interface as having carrier when it is administratively up
**and** the kernel reports `IFF_LOWER_UP`. When an interface that had carrier
loses it, netd logs `interface <name>: carrier lost` and:

- stops its DHCPv4 client: a RELEASE is sent if a lease was held, and the
  lease and any link-local address are forgotten (§5.4);
- stops router discovery and DHCPv6;
- forgets the network identified on it (§7.1), so `Status Network` is
  cleared and the `Network.*` facts go absent, for netd's own judgment
  and the kernel's packet layers alike.

The next reconcile then removes the leased and autoconfigured addresses and
the routes that depended on them, because nothing desires them any more.
Static addresses stay. [*ifid.carrier-loss-removes-offered-config]

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_

> What a joined interface should carry — link, MTU, addresses, routes,  and their metric — computed from its profile and what its network has offered; and what DOWN and IGNORE desire.

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 [*desired.by-verdict]

- Loopback, or an `IGNORE` d interface: there is no desired state, and
  netd plans nothing for the interface.
- `DOWN`: the link down, with no addresses and no routes.
- `JOIN`: the link up, and everything below.

## 4.2.2 The metric [*desired.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 [*desired.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 [*desired.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 [*desired.ipv4-routes]

- **The default route** goes through `Route.Gateway`'s IPv4 entry when it is
  set. Otherwise, with `Route.Offered`, it goes through the lease's gateway:
  the first router of option 3, or, when the lease carried classless
  routes, the gateway of the classless `0.0.0.0/0` route. With neither,
  there is no IPv4 default route.
- **Classless static routes** (option 121) with a prefix above zero are
  added, each through its gateway, only with `Route.Offered`.

During the first INIT-REBOOT, existing netd-marked IPv4 routes accompany the
provisional address when `Route.Offered` is enabled. The profile's explicit
gateway and current metric still take precedence (§2.1).

`Route.Gateway` is used as written; netd does not check that the gateway is on
a subnet the interface has. A gateway the kernel cannot reach makes the
route's add fail on every reconcile, logged each time (§11).

## 4.2.6 IPv6 addresses [*desired.ipv6-addresses]

1. every IPv6 entry of `Address.Static`, at its prefix, preferred, with
   a prefix route;
2. every address router discovery wants (§6.2): stable-privacy
   and temporary addresses, each deprecated or not, each with or without
   a prefix route according to the prefix's on-link flag.

## 4.2.7 IPv6 default route [*desired.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_

> How netd diffs an interface's desired state against the kernel's and applies the difference — what counts as netd's, the order of operations, how each is phrased to rtnetlink, and which failures are benign.

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 [*reconcile.ownership]

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.
  [*reconcile.foreign-address-removed]
- **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. [*reconcile.foreign-route-kept]
- **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 [*reconcile.plan-order]

For each interface with a desired state, netd plans these operations, in this
order:

1. **Link up**, if it is desired up and is down.
2. **MTU**, if one is desired, differs from the link's, and is at least
   68.
3. **Address deletions**: every address netd owns whose address and
   prefix length together match no desired address.
4. **Address additions**: every desired address the kernel does not hold
   with the same flags, in ascending address order, IPv4 before IPv6.
5. **Route deletions**: every protocol-200 route on the interface that is
   not desired.
6. **Route additions**: every desired route the kernel does not hold.
7. **Link down**, if it is desired down and is up — last, after its
   addresses, and routes have gone.

Addresses compare by address and prefix length, plus the two flags netd
sets: deprecated and no-prefix-route. A tentative flag (duplicate address
detection still running) is erased before comparing. A change of flags
alone is therefore an addition of the same address, which replaces it
(below), never a delete and re-add that would reset standing connections.
[*reconcile.flag-change-is-a-replace]

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. [*reconcile.converged-plan-is-empty]

## 4.3.3 Applying [*reconcile.apply]

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.
[*reconcile.equal-metric-ipv4-routes]

How addresses are phrased:

- An **IPv4** address carries `IFA_LOCAL` and `IFA_ADDRESS` set to
  itself, link scope for 169.254/16 and universe scope otherwise. Below
  a /31 it also carries a broadcast address: the broadcast of the lease
  the interface holds, if that lease gave one, otherwise the address's
  own subnet's all-ones address. The lease's broadcast goes on every
  IPv4 address added while the lease is held, statics included.
- An **IPv6** address carries universe scope and, when its prefix is not
  on-link, `IFA_F_NOPREFIXROUTE`. Its lifetimes are netd's to manage, so
  the kernel is told a valid lifetime of forever and a preferred lifetime
  of forever, or of zero when the address is deprecated. Source address
  selection then stops choosing a deprecated address, and connections
  already using it keep it. [*reconcile.ipv6-lifetimes-forever-or-deprecated]

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.
[*reconcile.failure-carries-on]

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_

> When netd runs a DHCPv4 client on an interface, what it is configured with, its states, and exactly what each message it sends carries.

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 [*dhcp4-client.start-stop]

On every full pass, for each joined interface:

- the interface **wants** a client when its profile has `Address.Offered`
  and IPv4 in its families;
- it **can** run one when it is up with carrier.

A running client is stopped (§5.4) in the step of the pass that brings the
interface table in line with the kernel's links, before clients are started
(§2.2):

- when the link loses carrier or goes down, logged as `interface <name>:
  carrier lost`;
- when the interface's outcome changes, logged as the new verdict
  (§3.3). Any edit to the profile the interface stands in is a change of
  outcome, so it stops the client even when the edited profile still
  wants one, and the same pass starts a new one.

Only a change of outcome changes what an interface wants, so a client its
interface does not want is always stopped the second way. A link that leaves
the
kernel takes its client with it (§5.4).

An interface that wants and can run a client but has none starts one, logging
`interface <name>: dhcp starting`, provided:

- the link has a 6-byte hardware address — otherwise no client is started,
  silently;
- its packet socket opens (§5.6) — otherwise netd logs `no packet socket`
  and tries again on the next pass.

A new client starts with no lease. It is configured with:

| 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**.
[*dhcp4-client.previous-address-starts-in-rebooting]

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

[*dhcp4-client.states]

A new transaction id is drawn on entering Selecting, Rebooting, Renewing and
Rebinding. Requesting keeps the id of the Selecting exchange it came from.
[*dhcp4-client.transaction-ids]

## 5.1.3 What every message carries [*dhcp4-client.common-fields]

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 [*dhcp4-client.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_

> The DHCPv4 client's retransmission schedule in each state, when "nobody answered" is reported, and the lease boundaries T1, T2 and expiry.

Every timer is on netd's monotonic clock.

## 5.2.1 Retransmission while acquiring [*dhcp4-timers.backoff]

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 |

[*dhcp4-timers.give-up-schedule]

## 5.2.2 "Nobody answered" [*dhcp4-timers.no-offer-once-per-client]

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`
](https://github.com/peios/netd/blob/23af1f6b84f3764d9327eb009ced56b2a16b7aa8/dhcp4/src/client.rs),
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](https://github.com/peios/netd/blob/13d593fdf64b58b08edf901b6f5edb8535f6fe75/dhcp4/src/client.rs)
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 [*dhcp4-timers.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 [*dhcp4-timers.renewal-retransmit]

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_

> Which DHCPv4 replies the client accepts, the server-identity lock, what makes an OFFER or an ACK acceptable, and how an ACK is read into a lease — prefix, routes, T1 and T2, and the options kept.

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 [*dhcp4-lease.reply-filter]

A received message is ignored unless all of these hold:

- it is a BOOTREPLY;
- its transaction id is the client's current one;
- its `chaddr` is the interface's MAC;
- it carries a message type (option 53) the client knows.

## 5.3.2 The server lock [*dhcp4-lease.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 [*dhcp4-lease.state-table]

| 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 [*dhcp4-lease.ack-requirements]

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 [*dhcp4-lease.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 [*dhcp4-lease.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`
](https://github.com/peios/netd/blob/23af1f6b84f3764d9327eb009ced56b2a16b7aa8/dhcp4/src/packet.rs),
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](https://github.com/peios/netd/blob/98f46343f6cdff62b1d9fcb886baf383c3943ac5/dhcp4/src/packet.rs)
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 [*dhcp4-lease.t1-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 [*dhcp4-lease.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).
[*dhcp4-lease.bound-clears-link-local-and-warning]

---

# 5.4 Losing a Lease

_Peios / Reference / netd / Dhcpv4_

> How a DHCPv4 lease ends — expiry, a NAK, or the client being stopped — what Address.OnExpiry decides, and when a RELEASE is sent.

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 [*dhcp4-loss.lost]

A lease is **lost** when a Rebinding client reaches the lease's end (§5.2), or
when a NAK arrives while renewing or rebinding (§5.3). The client forgets the
lease and enters Selecting, and netd acts on the interface's
`Address.OnExpiry`:

- **`Drop`** (the default): netd logs `interface <name>: lease lost` and
  forgets the lease. The next reconcile removes the address and the routes
  that came with it. [*dhcp4-loss.drop-removes-the-address]
- **`Keep`**: netd logs `interface <name>: lease lost; keeping the address
  (Address.OnExpiry = Keep)` at warning level and goes on desiring the
  lost lease — its address, gateway, and routes — while the client looks
  for a new one. The kept lease is replaced the moment a new one binds.
  [*dhcp4-loss.keep-holds-the-lease]

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 [*dhcp4-loss.stop-releases]

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 [*dhcp4-loss.operator-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_

> The 169.254/16 address netd self-assigns when DHCPv4 discovery goes unanswered — when, which address, and when it goes.

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 [*linklocal.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.
[*linklocal.not-beside-a-lease-or-static]

## 5.5.2 Which address [*linklocal.address-derivation]

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 [*linklocal.dropped-on-lease-or-stop]

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_

> The sockets behind netd's DHCPv4 client — the per-interface packet socket and its filter, the broadcast path from 0.0.0.0, the unicast path from the lease address, and the udp/68 absorber.

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 [*dhcp4-sockets.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 [*dhcp4-sockets.broadcast-frame]

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 [*dhcp4-sockets.unicast-renewal]

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 [*dhcp4-sockets.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_

> How netd names the machine and each interface to a DHCP server — the DUID and the per-interface client identifier — and how it remembers which address a network gave it.

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 [*dhcp4-memory.duid]

The machine's DHCP unique identifier, shared by DHCPv4, and DHCPv6 (RFC 4361),
is decided once per netd process, the first time a client needs it:

1. the registry's `Machine\System\Network Duid`, as hex, when it is set
   and parses;
2. otherwise the file `/var/state/netd/duid`, when it holds at least 4
   bytes;
3. otherwise a new DUID-LL: `00 03 00 01` followed by the MAC of the
   interface whose client is starting. It is written to
   `/var/state/netd/duid`; a failure to write is logged and changes
   nothing else.

When the registry's `Duid` is absent, empty or not hex, the result of 2 or 3
is written to it, as colon-separated lower-case hex, replacing a value that
was not hex. [*dhcp4-memory.duid-written-back]

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 [*dhcp4-memory.client-id]

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 [*dhcp4-memory.requested-address]

While an interface holds a lease on an identified network (§7.1), netd writes
the lease address to that network's `Networks\<id> RequestedAddress` whenever
it differs from what is there.

When a client starts, it takes as its previous address (§5.1):

1. the `RequestedAddress` of the network identified on the
   interface, when there is one; otherwise
2. the `RequestedAddress` of the network the interface's `Status
   LastNetwork` names (§8.1).

With one, the client opens with an INIT-REBOOT REQUEST for it. A server that
agrees answers with an ACK and the machine keeps the address in one round
trip. One that refuses answers with a NAK and the client discovers afresh.
Silence for two transmissions does the same (§5.2).

`RequestedAddress` is also the operator's: writing it is a soft reservation,
an address the client asks for first and the server can refuse.
[*dhcp4-memory.requested-address-is-a-soft-reservation]

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_

> How netd takes router advertisements away from the kernel, when it solicits and how often, which advertisements it accepts, and how it chooses a default router.

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 [*rdisc.kernel-accept-ra-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 [*rdisc.start-stop]

On every full pass, for each joined interface:

- it **wants** router discovery when its profile has `Address.Offered`
  and IPv6 in its families;
- it **can** run it when it is up with carrier and the kernel's
  link-local address on it has finished duplicate address detection. A
  tentative address cannot source a solicitation.

Running discovery that is not wanted or possible is stopped (`ipv6 stopping`):
the engine and any DHCPv6 client are discarded, and the next reconcile removes
their addresses and route. Nothing is sent on the wire, because neither
protocol has a goodbye. An interface that wants and can run it starts it
(`soliciting routers`), provided its ICMPv6 socket opens — otherwise netd logs
`no icmpv6 socket` and tries again on the next pass.

## 6.1.3 The socket [*rdisc.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 [*rdisc.solicitation-schedule]

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. [*rdisc.solicit-again-when-routers-gone]

## 6.1.5 Which advertisements count [*rdisc.acceptance]

An advertisement is dropped unless it arrived with hop limit 255 and from
a link-local source ([RFC 4861
§6.1.2](https://datatracker.ietf.org/doc/html/rfc4861#section-6.1.2)). A lower
hop limit has crossed a
router, and a non-link-local source is not a router on this link.
[*rdisc.hop-limit-and-source-checks]

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.

[*rdisc.malformed-advertisement-refused]

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 |

[*rdisc.option-acceptance]

Any other option is ignored. So are the advertisement's hop limit, reachable
time and retransmission timer.

## 6.1.6 What an advertisement does [*rdisc.effects]

- **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. [*rdisc.m-or-o-latches-dhcpv6]
- **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 [*rdisc.default-router-is-lowest-address]

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_

> Stateless address autoconfiguration as netd does it — which prefixes form addresses, the stable-privacy derivation and its secret, lifetimes and the two-hour rule, deprecation, and temporary addresses.

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 [*slaac.prefix-acceptance]

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 [*slaac.stable-privacy-derivation]

Each accepted prefix gets one stable address (RFC 7217): the prefix's first 64
bits, followed by the first 8 bytes of a SHA-1 digest of:

1. the bytes `peios-ndp-stable-iid|`;
2. the machine's 32-byte secret;
3. the prefix's first 8 bytes;
4. the interface id's text;
5. a one-byte counter, starting at 0.

When the resulting interface identifier is reserved (RFC 5453: all zeros,
`0200:5eff:fe00::/40`, or `fdff:ffff:ffff:ff80` to `fdff:ffff:ffff:ffff`), the
counter is incremented and the digest taken again, up to 8 times.

So the same machine on the same network has the same address on every
boot, a different network sees an unrelated address, and no MAC address
ever appears in it. The address is a function of the interface id, so a
kernel rename does not change it either.
[*slaac.same-machine-same-network-same-address]

### 6.2.2.1 The secret [*slaac.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 [*slaac.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)](https://www.rfc-editor.org/rfc/rfc4862.html#section-5.5.3),
  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 |

[*slaac.two-hour-rule]

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.
[*slaac.deprecate-then-remove]

## 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.
[*slaac.off-link-gets-no-prefix-route]

## 6.2.5 Temporary addresses [*slaac.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_

> The DNS servers and search domains routers advertise, and the stateless DHCPv6 information-request client netd runs when routers ask for it — when it starts, what it sends, what reply it accepts, and when it asks again.

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 [*v6dns.rdnss-dnssl-lifetimes]

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 [*dhcp6.start-stop]

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 [*dhcp6.information-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. [*dhcp6.retransmit-schedule]

### 6.3.2.4 The reply [*dhcp6.reply-acceptance]

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 [*dhcp6.refresh-time]

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_

> How netd decides which network is on the other side of an interface — the signals, the identity derived from them, when identification runs, and what a newly identified network does.

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 [*netid.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 [*netid.derivation]

- 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.
[*netid.same-server-and-subnet-same-network]

## 7.1.3 When [*netid.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 [*netid.new-network-rejudges]

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).
[*netid.sticky-while-carrier]

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_

> The Networks\<id> record — what netd writes under its Status, what the operator writes on the record, and how the two are read.

Every network a joined interface has been identified on gets a record,
`Machine\System\Network\Networks\<id>`. Records are never deleted by netd.
[*netrec.never-deleted]

## 7.2.1 What netd writes [*netrec.status-values]

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. [*netrec.status-descriptor]

## 7.2.2 What the operator writes [*netrec.operator-values]

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.
[*netrec.name-and-trust-are-read-each-pass]

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_

> What netd writes under Interfaces\<id>\Status for every interface it has seen, when each value is set or removed, the descriptor on Status, and the values netd shares with the operator.

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 [*inventory.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 [*inventory.status-values]

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

[*inventory.value-presence]

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. [*inventory.writes-only-on-change]

`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 [*inventory.status-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 four readiness levels, how netd computes one for each interface and for the machine, and how the machine level reaches peinit and the registry.

"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 [*readiness.interface-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.
[*readiness.usable-address]

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.
[*readiness.any-default-route-counts]

## 8.2.2 The machine's level [*readiness.machine-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 [*readiness.publish-on-change]

At every publish (§2.2) netd computes the machine level. When it differs from
the last one published — and at the first publish after startup, which
precedes `READY=1` — netd:

1. logs `machine readiness is <level>`;
2. sends the complete readiness set below in one datagram on the notify
   socket named by `NOTIFY_SOCKET`;
3. writes `Readiness` on `Machine\System\Network`.

The notify set is determined by the highest machine level:

| Machine 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 [*readiness.peinit-matches-the-published-level]

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_

> netd's side of the network-manager channel of PSPU §6.9 — the subscribe request, the snapshot and every scope field, how DNS facts are merged from profile and offer, and when snapshots are sent.

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 [*snapshot.subscribe]

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 [*snapshot.sent-on-change]

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. [*snapshot.slow-subscriber-dropped]

## 8.3.3 The snapshot [*snapshot.contents]

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. [*snapshot.scope-order-and-membership]

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

[*snapshot.scope-fields]

## 8.3.4 Merging DNS facts [*snapshot.dns-merge]

Servers, in this order:

1. the profile's `Dns.Servers`, always;
2. with `Dns.Offered`: the lease's servers (option 6);
3. with `Dns.Offered`: the routers' RDNSS servers, including link-local IPv6;
4. with `Dns.Offered`: the DHCPv6 reply's servers, including link-local IPv6.

Domains, in this order:

1. the profile's `Dns.Domains`, always;
2. with `Dns.Offered`: the lease's domain search list (option 119) if it
   is not empty, otherwise its domain name (option 15);
3. with `Dns.Offered`: the routers' DNSSL domains;
4. with `Dns.Offered`: the DHCPv6 reply's domains.

Each list removes duplicates across the entire list, retaining the first
occurrence and the source order above. This includes repeated values with
other values between them.
[*snapshot.first-occurrence-deduplication]

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.
[*snapshot.ntp-regardless-of-dns-offered]

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_

> Where netd's hostname comes from — the registry or a lease — when it calls sethostname, and what it does not do.

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 [*hostname.source]

1. `Machine\System\Network Hostname`, when it is set and not empty;
2. otherwise the hostname option (12) of a lease. netd takes the first
   joined interface, in kernel index order, whose profile has
   `Hostname.Offered` and whose lease carries a hostname;
3. otherwise none.

The selected name is checked by `netd_core::hostname`, the same rule used
by System Settings and first-boot setup: after trimming outer whitespace,
it must be one nonempty label of at most 63 ASCII letters, digits or
hyphens, with no leading or trailing hyphen, and must not be `localhost`
(case-insensitive). This applies to registry and lease names alike.
[*hostname.passed-as-written]

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 [*hostname.applied-after-each-pass]

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.
[*hostname.never-unset]

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.
[*hostname.change-recorded]

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.
[*hostname.requester-recorded]

## 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_

> netd's control socket — its path and descriptors, the control object and its default descriptor, the access rights and their generic mapping, and how each connection is checked.

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 [*control.socket-path-and-descriptor]

netd listens on `/run/netd/control.sock`, a `SOCK_STREAM` Unix socket. At
startup it:

1. creates `/run/netd` if it is missing, sets its mode to `0755`, and
   gives it the descriptor below;
2. removes a socket file left by a previous run, logging `removed a stale
   /run/netd/control.sock`;
3. binds, sets the socket file's mode to `0666`, and gives it the same
   descriptor.

The descriptor on both: owner and group SYSTEM, and a DACL allowing SYSTEM
`GENERIC_ALL` and Everyone `GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE`.
peinit creates `/run` SYSTEM-only and inheritable, so without it nobody else
could reach the socket. Everyone can connect; the control object decides what
each connection can do. A failure to set it is logged as an error and netd
carries on.

## 9.1.2 The control object [*control.object-default-descriptor]

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.
[*control.object-follows-control-security]

## 9.1.3 Rights [*control.rights-and-mapping]

| 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 [*control.access-check-on-peer-token]

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 [*control.serial-and-blocking]

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_

> The control socket's framing and limits, its four requests and the rights they need, the errors it answers with, and every field of the status reply.

Control requests use the shared framing and reply types described here. Each
operation names the right required by the daemon.

## 9.2.1 Framing [*control-req.framing]

The control socket is a PSPU observability query channel: one length-prefixed
MessagePack map in each direction, one request and one reply per connection,
except `subscribe`.

- A frame is a 4-byte little-endian payload length, then the payload.
- A length above 65536 is refused before any of the payload is read, with
  `{ok: false, error: "message of <n> bytes exceeds the ceiling"}`.
- A request is a map with a string `query`. Unknown keys are ignored, and
  a key that appears twice refuses the request.
- A reply is a map with a boolean `ok`, and either the result's fields or
  a string `error`.

An oversized, incomplete-at-EOF, or undecodable request is answered with an
error reply and the connection ends:

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

[*control-req.decode-errors]

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 [*control-req.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. [*control-req.renew-errors]

## 9.2.3 The status reply [*control-req.status-fields]

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

[*control-req.status-interface-fields]

---

# 10.1 Commands

_Peios / Reference / netd / The Net Command_

> The net command as built — each subcommand, what it reads, how net wait and net policy wait decide, and its exit statuses.

`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 [*net.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 [*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` [*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` [*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 [*net.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_

> What goes wrong with netd, what each failure looks like from outside, where the evidence is, and how to get back to a known state.

netd reports configuration, protocol, and kernel failures through status and
logs. The cases below distinguish refusal from incomplete discovery or
reconciliation.

## 11.1.1 Where the evidence is

- **`net status`**: the policy refusal, each interface's verdict and the
  rule that gave it, its warning, its addresses and gateways, and its
  lease's state.
- **netd's log.** Informational lines go to standard output; warnings and
  errors go to standard error. peinit forwards both to eventd
  (`evctl 'LOGS FROM netd SINCE 1h ago TAKE 40'`). Each line is also
  mirrored to `/dev/kmsg` at `KERN_INFO`, `KERN_WARNING` or `KERN_ERR`, so
  it
  reaches the kernel log and, at a permissive console log level, the
  console. If the mirror cannot be opened, netd says so once on standard
  error and tries again on the next line. Each mirrored line opens and
  closes its own `/dev/kmsg` descriptor, so boot and reconciliation
  bursts do not lose lines to the kernel's per-open rate limit (normally
  ten lines in five seconds). All three severities are retained. The
  mirror remains best-effort if opening or writing the device fails;
  stdout/stderr delivery is independent. [*failure.log-mirrored-to-kmsg]
- **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 `IGNORE`d, 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.Static` instead.
- **A route added by hand stays,** unless it carries protocol 200.
- **A pinned gateway never appears.** `Route.Gateway` is not checked
  against the interface's subnets. When the kernel cannot reach it, every
  reconcile logs `reconcile: AddRoute(…) failed`, and the interface stays
  `addressed`.
- **The hostname does not change back** when `Hostname` is removed. netd
  never unsets a name (§8.4).

## 11.1.5 Losing what was working

- **A cable pull drops everything offered** — the lease, autoconfigured
  addresses, routes, the network identity — and stops the clients
  (§4.1). When the carrier returns, the DHCPv4 client asks for the old
  address first, so a cooperative server restores it in one exchange.
- **A lease that cannot be renewed drops its address** at the lease's
  end, unless the profile says `Address.OnExpiry = Keep` (§5.4). After
  that, the link-local fallback does not happen again in the same
  client's life (§5.2).
- **Editing a profile restarts its interfaces' clients** (§3.3), so a
  DHCPv4 lease is released and asked for again.

## 11.1.6 netd is slow or unresponsive

- **Control requests time out.** netd handles control clients without blocking
  the event loop. It permits 64 pending clients, accepts at most 16 per pass,
  and closes requests that exceed their 2-second deadline (§9.1). Check for
  clients holding connections open or flooding `/run/netd/control.sock`.
- **`net: cannot reach netd at /run/netd/control.sock`.** netd is not
  running, or `/run/netd` lost its descriptor. The service restarts
  netd always; `evctl` shows why it stopped.

## 11.1.7 Configuration not read

- **A configuration read failed.** Check the named read error in the log.
  netd retains its previous complete configuration after a reload failure.
  Restore access or valid text, then change the configuration to retry.
- **Network state refresh failed.** An interrupted or failed netlink dump is
  discarded. netd keeps its previous complete snapshot until a refresh
  succeeds; it does not reconcile against a partial dump.

- **netd ignores every registry change.** The watch could not be armed at
  startup (`registry watch unavailable … configuration is read once`), or
  `Machine\System\Network` did not exist then (§2.1). Restart netd.

## 11.1.8 Getting back to a known state

1. Undo the last registry write. A refused generation names what to undo,
   and the next good write is taken at once.
2. `net reconcile` runs a full pass without waiting for an event.
3. `net renew <interface>` renews a lease without releasing it.
4. Restarting netd re-derives everything from the registry and the
   kernel, and asks for the remembered IPv4 address with INIT-REBOOT (§2.1).
   The requested address already installed and applicable netd-owned routes
   stay while that request is pending. A NAK or unanswered revalidation
   discards this provisional state and starts fresh discovery; an unchanged
   ACK keeps IPv4 connectivity in place. Offered DNS and IPv6 information
   still have to be reacquired.

---

# 12.1 The Public Interface

_Peios / Reference / netd / Client Library_

> Shared-library operations, ownership, timeouts, and Rust wrappers.

`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_

> Every fixed number, path and identifier netd uses, in one table, with the section that describes it.

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 one process on a Peios machine that answers names — three doors in front of one engine — and the handful of decisions that would not be guessed from its name.

**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_

> The daemon, the operator command and the NSS shim as built, and where the contract, netd's side of the channel and the kernel mechanisms are described instead.

This manual covers the resolvd source tree and its shared client library:

| Component | Package | Installed as |
|---|---|---|
| The daemon | `dev.peios.resolvd` | `/usr/sbin/resolvd` [*coverage.daemon-installed-path] |
| The operator command | `dev.peios.resolv` | `/usr/bin/resolv` [*coverage.resolv-installed-path] |
| The NSS shim | `dev.peios.resolvd-nss` | `/usr/lib/x86_64-linux-peios/libnss_peios_net.so.2` [*coverage.shim-installed-path] |

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 [*coverage.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 terms specific to resolvd's engine — task, candidate, transaction, attempt, routable scope — and where the contract's own terms are defined.

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_

> How peinit runs resolvd — the service definition, the identity it runs under, the port reservation that lets it bind port 53, readiness, restart, and where its log lines go.

## 2.1.1 The service definition seed [*service.definition-seed-inert-until-applied]

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

| Value | Type | Data | Effect |
|---|---|---|---|
| `ImagePath` | `REG_SZ` | `/usr/sbin/resolvd` | The binary. resolvd reads no command-line arguments. [*service.image-path-no-arguments] |
| `Triggers` | `REG_MULTI_SZ` | `boot` | Started at boot. [*service.triggered-at-boot] |
| `Identity` | `REG_SZ` | `Service` | Runs under its own virtual service account. [*service.identity-is-own-virtual-account] |
| `Readiness` | `REG_DWORD` | `0` | Notify: ready when resolvd says so. [*service.readiness-is-notify] |
| `RuntimeDirectories` | `REG_MULTI_SZ` | `resolvd` | peinit creates `/run/resolvd`. [*service.runtime-directory] |
| `RestartPolicy` | `REG_DWORD` | `2` | Always restarted. [*service.restart-policy-always] |
| `LimitNOFILE` | `REG_DWORD` | `16384` | Descriptor headroom for 4 096 upstream transactions, their client waiters, 512 pending clients and daemon descriptors. |
| `ErrorControl` | `REG_DWORD` | `0` | |
| `DisplayName` | `REG_SZ` | `Stub resolver` | |
| `Description` | `REG_SZ` | (one sentence) | |

## 2.1.3 Identity and privilege

resolvd holds no privilege and needs none. Its one claim on the machine
that an ordinary process could not make — binding UDP and TCP port 53 —
is met by a port reservation rather than a capability (PSPU §6.8).

Without the reservation applied, the stub listener cannot bind and
resolvd exits at startup (§2.2, §9.3).

### 2.1.3.1 The port reservation seed [*service.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` |

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 2.1.3.2 Who holds the reservation [*service.reservation-granted-to-system-and-service-sid]

The data is a security descriptor granting the reservation to SYSTEM and
to resolvd's service SID,
`S-1-5-80-3864064249-1823296737-2008945602-1354971773-2894779966`, so it
follows the service rather than whichever account the service happens to
run as.

The selector `tcp,udp:53` is more specific than the kernel package's
`tcp,udp:1-1023` and so decides port 53 alone. The descriptor bytes are
generated from the SID by a tool in the source tree, not written by
hand.

## 2.1.4 Readiness

With `Readiness` 0 peinit waits for a notification. resolvd:

- sends the datagram `READY=1` to the socket named by the
  `NOTIFY_SOCKET` environment variable once the native socket and both
  stub sockets are open and the registry has been read;
  [*service.ready-after-doors-open]
- does not wait for netd: readiness is sent after the first attempt to
  reach netd whether that attempt succeeded or not;
  [*service.ready-does-not-wait-for-netd]
- sends nothing when `NOTIFY_SOCKET` is unset, and logs a failure to
  send as `readiness notify: <error>` and carries on starting. Sending has a
  one-second deadline.
  [*service.notify-failure-not-fatal]

## 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; [*service.restart-empties-cache]
- no demoted servers; [*service.restart-clears-demotions]
- every counter at zero (§4.10);
- no scopes, and the kernel's hostname, until the first snapshot after
  netd is reached again (§3.3). [*service.restart-starts-without-scopes]

## 2.1.6 Log lines

### 2.1.6.1 The log line format [*service.log-line-format]

Every line resolvd logs has the form

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

```sh
evctl 'LOGS FROM resolvd SINCE 1h ago TAKE 40'
```

### 2.1.6.2 The kernel log mirror [*service.kmsg-mirror-fails-once]

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:

```text
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_

> What resolvd does between exec and READY=1, in order, which steps are fatal, and the only ways the process exits.

## 2.2.1 The sequence

1. **The native socket.** The runtime directory and the socket are
   created and given their modes and descriptors (§2.4). A failure to
   create the directory, set a mode, remove a stale socket file, bind,
   or make the listener nonblocking is fatal: resolvd logs `native socket:
   <error>` at error level and
   exits with status 1. A failure to write a descriptor is not fatal
   (§2.4). [*startup.native-socket-failure-is-fatal]
2. **The stub listener.** A UDP socket and then a TCP listener are bound
   to `127.0.0.53:53`. A failure of either is fatal: resolvd logs
   `stub listener on 127.0.0.53:53: <error>` and exits with status 1.
   [*startup.stub-listener-failure-is-fatal]
3. **The registry.** `Machine\System\Network\Dns` is read whole (§2.3).
   A missing key selects defaults. A read failure, including unreadable
   values or malformed UTF-8, is fatal rather than applying partial policy.
   [*startup.missing-dns-key-is-not-an-error]
4. **The registry watch.** A subtree watch is armed on
   `Machine\System\Network` (§2.3). If it cannot be armed, resolvd logs
   `registry watch unavailable (<error>); configuration is read once`
   and runs on the configuration it read in step 3 until it restarts.
   [*startup.watch-failure-reads-configuration-once]
5. **Query entropy.** The engine is given a kernel-randomness provider.
   Every upstream transaction obtains fresh bytes through nonblocking
   `getrandom`; startup does not seed a userspace generator or read
   `/dev/urandom`. There is no clock fallback.
   [*startup.entropy-from-kernel-per-query]
6. **The engine's inputs.** The engine is given the kernel's hostname,
   the fallback servers and search domains, and the static names. A
   kernel hostname that is empty or `(none)` counts as no hostname.
   [*startup.kernel-hostname-none-is-no-hostname]
7. **The control object** is built from `ControlSecurity` (§5.2).
8. **netd.** The first attempt to subscribe is made immediately (§3.1).
   Its failure is not fatal and is retried with backoff (§3.2).
   [*startup.first-netd-attempt-immediate-and-not-fatal]
9. **The listening line.** resolvd logs
   `listening on /run/resolvd/resolv.sock and 127.0.0.53:53` at info
   level. [*startup.listening-log-line]
10. **Readiness.** `READY=1` is sent (§2.1).
11. **The loop** is entered (§2.5).

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
## 2.2.2 Answering from the moment of readiness [*startup.answers-before-first-snapshot]

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 [*startup.no-signal-handlers-socket-left-behind]

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 [*startup.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 values resolvd reads from Machine\System\Network\Dns, how each is parsed and what a malformed one does, and how a change reaches the running daemon.

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 [*config.absent-key-gives-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_SZ` or `REG_EXPAND_SZ` is one string: its data up to the first
  NUL, read as UTF-8. Invalid UTF-8 rejects the complete configuration read.
  [*config.single-string-read-to-first-nul]
- A `REG_EXPAND_SZ` is read as it is stored; nothing in it is expanded.
  [*config.expand-sz-not-expanded]
- A `REG_MULTI_SZ` is split at every NUL. Empty strings are skipped.
  Invalid UTF-8 rejects the complete read rather than omitting one entry.
  [*config.multi-sz-empty-and-non-utf8-strings-skipped]
- A value of any other type is treated as absent.
  [*config.other-value-types-treated-as-absent]

## 2.3.3 `FallbackServers`

- Each string is trimmed of surrounding whitespace and parsed as an IPv4
  or IPv6 address. A string that does not parse is skipped and logged as
  `Dns FallbackServers: ignoring malformed address "<string>"`, with the
  string as stored — untrimmed, in double quotes, with quotes,
  backslashes and control characters escaped. A lone `REG_SZ` that is
  empty or only whitespace, a whitespace-only string in a multi-string,
  and an address with a zone such as `fe80::1%eth0` (§4.7) are all
  logged this way. [*config.fallback-malformed-address-skipped-and-logged]
- There is no way to give a port; every server is asked on port 53.
  [*config.fallback-servers-port-53]

The order of the list is the order servers are tried in (§4.6).

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
## 2.3.4 `ExtraSearchDomains` [*config.extra-search-domain-malformed-skipped-and-logged]

Each string is parsed as a domain name, with or without a trailing dot.
It is not trimmed, so a leading or trailing space becomes part of a
label. A string that does not parse, or that is the root — a lone empty
`REG_SZ`, or `.` — is skipped and logged as
`Dns ExtraSearchDomains: ignoring malformed domain "<string>"`, quoted
as for `FallbackServers`.

## 2.3.5 `ControlSecurity`

- A `REG_BINARY` value with at least one byte is taken as a
  self-relative security descriptor. An empty value, a value of another
  type, or an absent value selects the compiled default, with no log
  line. [*config.control-security-empty-or-wrong-type-selects-default]
- Bytes that do not form a valid descriptor also select the compiled
  default, and resolvd logs
  `ControlSecurity is not a valid descriptor (<error>); using the default`
  each time it builds the control object from them: at startup, and at
  every configuration change (below).
  [*config.control-security-invalid-selects-default-and-logs]

## 2.3.6 `Hosts\`

- Every value under `Machine\System\Network\Dns\Hosts` is one static
  name. The value's name is the host name and its data is one address
  (`REG_SZ` or `REG_EXPAND_SZ`) or several (`REG_MULTI_SZ`), read as
  above. [*config.hosts-value-is-one-static-name]
- A value name that is not UTF-8 rejects the complete read.
  [*config.hosts-non-utf8-name-skipped]
- A value name that does not parse as a domain name is skipped and
  logged as `Dns Hosts: ignoring malformed name "<name>"`.
  [*config.hosts-malformed-name-skipped-and-logged]
- A value name that parses to the root — an empty name, or `.` — is
  skipped silently. [*config.hosts-root-name-skipped-silently]
- Each address is parsed as for `FallbackServers`, and a malformed one
  is skipped and logged as
  `Dns Hosts: ignoring malformed address "<string>"`.
  [*config.hosts-malformed-address-skipped-and-logged]
- A name left with no valid address, including one whose value has any
  other type, is not a static name at all.
  [*config.hosts-name-without-address-dropped]
- Names match case-insensitively, so `Printer` and `printer` are the
  same static name. [*config.hosts-names-case-insensitive]

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 [*config.watches-network-key-recursively]

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 [*config.any-event-rereads-dns-key]

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 [*config.unchanged-configuration-is-a-no-op]

The fresh configuration is compared with the one in use. When nothing
differs, nothing is applied and nothing more is logged.

### 2.3.7.4 A changed configuration

When anything differs, resolvd, in this order:

1. rebuilds the control object from `ControlSecurity`;
   [*config.change-rebuilds-control-object]
2. replaces the fallback servers and search domains, discarding every
   answer cached through the fallback scope if the server list differs
   in content or in order;
   [*config.fallback-server-change-flushes-fallback-cache]
3. replaces the static names; [*config.change-replaces-static-names]
4. logs `configuration changed` at info level. [*config.change-logged]

### 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. [*config.changes-apply-live]
- Static names are never cached, so a new or removed `Hosts\` value is
  visible to the next question. [*config.static-name-change-visible-at-once]
- Answers already cached through an interface scope are not discarded
  by a registry change. [*config.registry-change-keeps-interface-cache]

### 2.3.7.6 When the watch fails

- If reading watch events fails, resolvd logs
  `registry watch: <error>; re-arming` and arms a new watch. The key is
  not read again when the new watch is armed, so a change made in
  between is applied only with the next event. [*config.watch-error-re-arms]
- 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. [*config.failed-re-arm-stops-watching-silently]

---

# 2.4 Sockets and Descriptors

_Peios / Reference / resolvd / Startup and Configuration_

> The native socket and its directory and their descriptors, the stub listener's sockets, and every other descriptor resolvd holds.

## 2.4.1 The native socket

The native door is a `SOCK_STREAM` Unix socket at
`/run/resolvd/resolv.sock` (PSPU §6.4), inside resolvd's runtime
directory rather than directly in `/run`, which resolvd's account cannot
write.

At startup resolvd:

1. creates `/run/resolvd` if peinit has not, and sets its mode to
   `0755`; [*sockets.runtime-directory-mode-0755]
2. replaces the directory's DACL (below);
3. removes any existing `/run/resolvd/resolv.sock`, logging
   `removed a stale /run/resolvd/resolv.sock` at warn level when there
   was one, and a removal that fails is fatal (§2.2);
4. binds the socket, sets its mode to `0666`, and replaces its DACL in
   the same way; [*sockets.socket-mode-0666]
5. makes the listener nonblocking.

### 2.4.1.1 A socket left by a previous run [*sockets.stale-socket-removed-on-restart]

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 [*sockets.directory-and-socket-dacl]

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

```text
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 [*sockets.owner-left-as-resolvd]

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

```text
could not set a descriptor on <path> (<error>); programs other than SYSTEM and administrators will not be able to reach the socket
```

and carries on. The socket then keeps whatever descriptor it was created
with, and for ordinary processes the native door — and with it the NSS
shim — is unreachable while the stub listener still works (§9.3).

## 2.4.2 The stub listener

- Two sockets, a UDP socket and a TCP listener, are both bound to
  `127.0.0.53` port 53 and both nonblocking (PSPU §6.8).
  [*sockets.stub-udp-and-tcp-on-127-0-0-53]
- Nothing is bound on `::1` or on any other address.
  [*sockets.nothing-bound-on-other-addresses]

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

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 2.4.3.1 Connections whose request has been read [*sockets.resolving-connections-keep-their-slot]

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_

> resolvd's single thread — what it polls, how long it sleeps, the order it services ready descriptors in, and what that order means for a client.

## 2.5.1 One thread and one poll [*loop.single-thread-single-poll]

resolvd runs on one thread. Every input is a descriptor in one `poll`
call, and the engine sees time only when the loop hands it the current
instant.

## 2.5.2 What is polled

Each iteration builds the poll set afresh:

1. the native listener, except during its accept-error backoff;
2. the stub UDP socket;
3. the stub TCP listener, except during its accept-error backoff;
4. the netd channel, while connected;
5. the registry watch, while armed;
6. every native connection still sending its request;
7. every stub TCP connection still sending its query;
8. every upstream socket — for reading, or for writing while a TCP
   connection is still being established or its query is still being
   sent;
9. native and stub TCP replies waiting to write, for writability;
10. native and stub TCP streams awaiting engine answers, for hangup and
    error indications only. Readability and read-half-close are not
    requested, preserving supported half-closes without spinning on EOF.

### 2.5.2.1 The poll timeout [*loop.poll-timeout-is-earliest-deadline]

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 [*loop.service-order]

After `poll` returns, ready descriptors are serviced in this order:

1. waiting native and stub TCP streams with definite hangup/error,
   canceling their questions and upstream transactions;
2. upstream sockets — replies that have arrived are answers already owed;
3. queued native replies, then queued stub TCP replies, whose sockets are
   writable;
4. the stub UDP socket, reading at most 64 datagrams;
5. the stub TCP listener, accepting at most 64 connections;
6. stub TCP connections still sending queries;
7. the native listener, accepting at most 64 connections;
8. native connections still sending requests;
9. the netd channel;
10. the registry watch.

The fixed datagram/accept batches yield to the other doors and timers even
while one listener remains continuously ready. [*loop.listener-batches]

## 2.5.4 Timers after descriptors [*loop.timers-run-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 [*loop.local-answers-within-the-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 [*loop.replies-written-blocking]

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_

> How resolvd subscribes to netd's DNS snapshots, reads the stream, and what ends the subscription.

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 [*netd-subscribe.connect-and-send-subscribe]

When a connection attempt is due (§3.2), resolvd:

1. opens a nonblocking connection to `/run/netd/control.sock`;
2. writes the `subscribe` request using a four-byte little-endian length
   and a MessagePack map;
3. retains the nonblocking socket for snapshot reads.

A full connection queue or an incomplete subscription write fails the
attempt without blocking the event loop.

The request needs netd's `NETWORK_QUERY` right for resolvd's account;
whether that is granted is netd's decision.

### 3.1.1.2 A failed attempt [*netd-subscribe.any-step-failure-is-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 [*netd-subscribe.success-logged]

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 [*netd-subscribe.writes-only-the-request]

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:

| Frame | What resolvd does |
|---|---|
| A `snapshot` reply | Applies it (§3.3), once the whole read has been taken. Several in one read are applied one after another, so the last wins. [*netd-subscribe.snapshots-applied-in-order] |
| An error reply | Logs `netd refused the subscription: <message>`, and drops the channel once the whole read has been taken. [*netd-subscribe.error-reply-drops-channel] |
| Any other well-formed reply | Ignores it. [*netd-subscribe.other-replies-ignored] |
| A payload that does not decode | Logs `netd sent something unreadable: <error>`, and drops the channel once the whole read has been taken. [*netd-subscribe.undecodable-payload-drops-channel] |
| A length above 65 536 bytes | Stops taking frames: the rest of the buffer is discarded and the channel dropped. [*netd-subscribe.oversized-frame-drops-channel] |

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 3.1.2.1 Frames behind an error are still taken [*netd-subscribe.frames-after-error-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.

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 3.1.2.2 The channel is dropped before the read's snapshots are applied [*netd-subscribe.drop-logged-before-snapshots-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 [*netd-subscribe.partial-frame-buffered]

A partial frame stays buffered until the rest arrives.

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 3.1.2.4 End of file or a read error [*netd-subscribe.eof-or-read-error-drops-channel]

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 [*netd-subscribe.drop-logged-and-reconnect-scheduled]

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_

> When resolvd tries to reach netd again, the exact backoff sequence, what it logs, and what it keeps answering with while netd is away.

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 [*netd-reconnect.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 [*netd-reconnect.first-failure-logged-once]

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 [*netd-reconnect.success-resets-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;
  [*netd-reconnect.sequence-after-loss]
- the `netd not reachable` warning is not logged for the failures that
  follow, however many there are; the `lost the netd channel;
  reconnecting` line that preceded them is the record.
  [*netd-reconnect.no-unreachable-warning-after-loss]

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 3.2.4.1 A refused subscription also backs off [*netd-reconnect.refusal-reconnects-every-half-second]

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 [*netd-reconnect.state-kept-while-disconnected]

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

<!-- Keep the published reference identifier. -->
<!-- lint-disable-next-line spelling -->
## 3.2.6 Before the first snapshot [*netd-reconnect.no-snapshot-yet-behaviour]

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_

> How each snapshot becomes resolvd's hostname and scope list — the conversion of each field, what is dropped, and which cached answers are discarded.

Each snapshot replaces resolvd's scopes whole (PSPU §6.9). Applying one
has three parts: the hostname, the scope list, and the cache.

## 3.3.1 The hostname

- The snapshot's `hostname` is used when it is not empty. When it is
  empty, resolvd reads the kernel's hostname at that moment, into a
  256-byte buffer; a kernel hostname that is empty or `(none)` counts as
  none. [*netd-snapshot.empty-hostname-reads-kernel-hostname]
- The result is parsed as a domain name. A name that does not parse, or
  the root, leaves resolvd with no hostname: no synthetic answer is
  given for it, and `status` reports an empty `hostname`.
  [*netd-snapshot.unparseable-hostname-is-no-hostname]
- The kernel's hostname is otherwise read only at startup. A change to
  it is not seen until the next snapshot with an empty `hostname`.
  [*netd-snapshot.kernel-hostname-read-only-at-snapshot-or-startup]

## 3.3.2 The scope list

Each `DnsScope` in the snapshot becomes one scope, in snapshot order:

| Snapshot field | Becomes |
|---|---|
| `ifid` | The scope key [*netd-snapshot.ifid-is-scope-key] |
| `name` | The interface name reported in answers and in `status` [*netd-snapshot.name-is-reported-interface] |
| `servers` | Server addresses, in order. Malformed addresses are logged and dropped. Link-local IPv6 addresses use the containing interface; an optional `%name` or `%index` must match it (§4.7). There is no port; servers are asked on port 53. [*netd-snapshot.servers-parsed-malformed-dropped] |
| `domains` | Search domains, in order. A string that does not parse as a name, and the root, are dropped. [*netd-snapshot.domains-parsed-malformed-dropped] |
| `addresses` | `(address, prefix length)` pairs. A string that is not `address/prefix` is dropped. [*netd-snapshot.addresses-parsed-malformed-dropped] |
| `default_route`, `exclusive`, `metric`, `level` | Carried as they are |
| `ntp` | Ignored |

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 [*netd-snapshot.every-scope-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 [*netd-snapshot.summary-log-line]

resolvd then logs one line at info level summarizing the snapshot:

```text
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;
  [*netd-snapshot.new-scope-key-flushed]
- a scope whose server list differs from before — in content or in
  order — loses its cached answers;
  [*netd-snapshot.changed-server-list-flushes-scope]
- a scope missing from the new snapshot loses its cached answers;
  [*netd-snapshot.missing-scope-flushed]
- a change to a scope's domains, addresses, flags, metric or level
  leaves its cache alone. [*netd-snapshot.other-changes-keep-cache]

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`.
  [*netd-snapshot.in-flight-retries-follow-scope-key]
- 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. [*netd-snapshot.in-flight-reply-cached-after-flush]

---

# 4.1 How a Question Is Answered

_Peios / Reference / resolvd / The Engine_

> The path every question takes through the engine, in order — parsing, synthetic names, candidates, routing, the cache, the network — and what each way out reports as its source.

Every door ends here. The native socket's `resolve`, `lookup` and
`reverse`, and every stub query, become one or more tasks, and each task
takes the same path.

## 4.1.1 The path

1. **Parse.** The name is parsed from presentation form. A trailing dot
   makes no difference. Escapes are not interpreted; a label is the
   bytes between dots. A name with an empty label, a label over 63
   bytes, or more than 255 bytes on the wire does not parse, and the
   task is answered `notfound` at once.
   [*engine-flow.unparseable-name-is-notfound]
2. **Synthetic names.** The name as asked is checked against the
   synthetic names (§4.2). A match answers the task.
   [*engine-flow.synthetic-check-first]
3. **Candidates.** The name becomes its list of candidates (§4.3). An
   empty list — a single label with no applicable search domain —
   answers the task `notfound`. [*engine-flow.no-candidates-is-notfound]
4. **Routing.** Each candidate in turn is routed to one scope (§4.4).
   When no scope can take it, the task is answered `unavailable`.
   [*engine-flow.unroutable-candidate-is-unavailable]
5. **The cache.** Unless the request asked to bypass the cache, the
   cache is consulted under that scope (§4.5).
6. **The network.** Otherwise the candidate is sent upstream (§4.6 to
   §4.8).
7. **The next candidate.** A `notfound` for a candidate — from the cache
   or from a server — moves to the next candidate when there is one.
   Any other result answers the task.
   [*engine-flow.notfound-moves-to-next-candidate]
8. **The last candidate.** When the last candidate is `notfound`, the
   task is answered `notfound`.
   [*engine-flow.all-candidates-notfound-is-notfound]

## 4.1.2 The empty name is the root [*engine-flow.empty-name-is-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.

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
## 4.1.3 Each candidate is routed separately [*engine-flow.each-candidate-routed-separately]

Each candidate is routed on its own, so the expansions of one single
label can go to different scopes. Candidates share the question's attempt
budget (§4.6).

## 4.1.4 What each way out reports

| Ends at | Outcome | `source` | `server` | `interface` | `rcode` |
|---|---|---|---|---|---|
| Name does not parse | `notfound` | `local` | nil | nil | 0 [*engine-flow.report-unparseable] |
| Synthetic name | per §4.2 | `synthetic` or `hosts` | nil | nil | 0 [*engine-flow.report-synthetic] |
| No candidates | `notfound` | `local` | nil | nil | 0 [*engine-flow.report-no-candidates] |
| No scope can take the candidate | `unavailable` | `local` | nil | nil | 0 [*engine-flow.report-unroutable] |
| Cache hit | as cached | `cache` | the server whose reply was cached | the scope's interface | the cached reply's response code [*engine-flow.report-cache-hit] |
| A server's reply | `found` or `notfound` | `dns` | the server | the scope's interface | the server's response code [*engine-flow.report-server-reply] |
| Every candidate `notfound` | `notfound` | as the last candidate's cache hit or server's reply, in the two rows above | as that row | as that row | as that row [*engine-flow.report-all-candidates-notfound] |
| Attempts exhausted | `unavailable` | `local` | nil | the scope's interface | 0 [*engine-flow.report-attempts-exhausted] |
| No servers left in the scope | `unavailable` | `local` | nil | nil | 0 [*engine-flow.report-scope-without-servers] |
| In-flight ceiling reached | `unavailable` | `local` | nil | nil | 0 [*engine-flow.report-in-flight-ceiling] |

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.

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 4.1.4.1 Answers from the fallback scope [*engine-flow.fallback-scope-has-no-interface]

`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 [*engine-flow.validation-always-unvalidated]

`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.
<!-- Keep the published reference identifier. -->
<!-- lint-disable-next-line spelling -->
[*engine-flow.departed-asker-transactions-cancelled]

Replies to canceled transactions are ignored; they do not populate the
cache. Answers already cached before cancellation remain cached.
<!-- Keep the published reference identifier. -->
<!-- lint-disable-next-line spelling -->
[*engine-flow.cancelled-replies-not-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. [*engine-flow.departed-asker-not-answered]

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_

> The names resolvd answers before any network — localhost, the static names, the machine's own name, .local, and their reverses — in the order it checks them and for which record types.

PSPU §6.7 lists the names a resolver answers before any network.
resolvd checks them in a fixed order, on the name as asked and before
any search expansion, and the first match answers the task.

## 4.2.1 The order

1. **`localhost`, or any name under it.** `127.0.0.1` for `A`, `::1`
   for `AAAA`, both for `ANY`. Source `synthetic`.
   [*engine-synthetic.localhost]
2. **A static name.** An exact, case-insensitive match against the
   `Hosts\` values (§2.3). The name's addresses of the asked family —
   IPv4 for `A`, IPv6 for `AAAA`, both for `ANY`. Source `hosts`.
   [*engine-synthetic.static-name]
3. **The machine's hostname.** An exact, case-insensitive match against
   the hostname (§3.3), answered with the machine's own addresses
   (below). Source `synthetic`. [*engine-synthetic.hostname]
4. **`.local`.** The name `local` or any name under it is `notfound`,
   whatever the type asked. Source `synthetic`. No query is sent.
   [*engine-synthetic.local-is-notfound]
5. **A reverse-mapping name, for `PTR` or `ANY` only.** See below.

A name that matches none of these goes on to search expansion and the
network.

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 4.2.1.1 Static names beat the hostname and `.local` [*engine-synthetic.check-order]

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.

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 4.2.1.2 `localhost` beats a static name [*engine-synthetic.static-name-under-localhost-unused]

`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 [*engine-synthetic.other-types-are-empty-found]

For the three address-bearing kinds, the answer is `found` whatever type
was asked; a type other than `A`, `AAAA` or `ANY`, or a family the name
has no address in, gives `found` with no records. `localhost` asked for
`MX` is an empty `found`, not a `notfound`, and is not forwarded.

### 4.2.1.4 The machine's own addresses

- They are every address of every scope at `addressed` or better,
  whether or not the scope has servers, in snapshot order, link-local
  addresses included and loopback addresses excluded.
  [*engine-synthetic.own-addresses-from-every-addressed-scope]
- 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. [*engine-synthetic.only-adjacent-duplicates-removed]
- When there are none, the hostname is answered with `127.0.0.1` and
  `::1`. [*engine-synthetic.hostname-without-addresses-is-loopback]

## 4.2.2 Reverse names

### 4.2.2.1 Reverse-mapping names [*engine-synthetic.reverse-name-forms]

A reverse-mapping name is one under `in-addr.arpa` with exactly four
labels before the suffix, or one under `ip6.arpa` with exactly 32. The
suffix is matched case-insensitively.

- Each `in-addr.arpa` label parses as a decimal number from 0 to 255.
  Leading zeros and a leading `+` are accepted, so `1.0.0.0127.in-addr.arpa`
  and `+1.0.0.127.in-addr.arpa` both name `127.0.0.1`.
- Each `ip6.arpa` label is a single hexadecimal digit, in either case.

A name of either shape whose labels do not parse is not a
reverse-mapping name.

### 4.2.2.2 Synthetic reverse answers

Asked for `PTR` or `ANY`, a reverse-mapping name is answered
synthetically when its address is:

| Address | Answer | Source |
|---|---|---|
| A loopback address — anything in `127.0.0.0/8`, or `::1` | `PTR localhost` | `synthetic` [*engine-synthetic.reverse-loopback] |
| Listed under a static name | `PTR` that name | `hosts` [*engine-synthetic.reverse-static-name] |
| One of the machine's own addresses, when there is a hostname | `PTR` the hostname | `synthetic` [*engine-synthetic.reverse-own-address] |

The rows are tried in that order.

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 4.2.2.3 An address shared by static names [*engine-synthetic.shared-static-address-reverse-per-configuration]

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.

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 4.2.2.4 Other reverse questions [*engine-synthetic.other-reverse-questions-go-to-network]

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. [*engine-synthetic.ttl-zero]
- Synthetic answers are never cached, and the `no_cache` flag has no
  effect on them. [*engine-synthetic.never-cached]
- Each one adds one to the `synthetic` counter (§4.10).

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
## 4.2.4 Expanded candidates are not checked [*engine-synthetic.expanded-candidates-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_

> Which search domains resolvd applies to a single-label name, in what order, how the candidates are built and asked, and what never gets expanded.

PSPU §6.7 sets the search expansion rules. This article is how resolvd
builds and asks the list of candidates.

## 4.3.1 What counts as a single label

- A name is single-label when it parses to exactly one label. The
  trailing dot plays no part: `printer.` is single-label and is expanded
  exactly as `printer` is.
  [*engine-expansion.trailing-dot-does-not-suppress-expansion]
- A top-level domain such as `com` is a single label too, and cannot be
  asked for directly: it is asked only as its expansions.
  [*engine-expansion.top-level-domain-cannot-be-asked]
- Any other name — a multi-label name, or the root — has one candidate,
  itself. [*engine-expansion.multi-label-single-candidate]

## 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`.
[*engine-expansion.exclusive-scope-domains-only]
[*engine-expansion.routable-scope-domains-then-extra]

An up scope without servers still contributes domains. Equal metrics keep
snapshot order, and each scope retains its domain order.
[*engine-expansion.scope-without-servers-contributes-no-domains]
[*engine-expansion.up-scope-domains]

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. [*engine-expansion.extra-domains-ignored-under-exclusive]

## 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. [*engine-expansion.duplicate-candidates-removed]
- A candidate longer than 255 bytes on the wire is left out.
  [*engine-expansion.overlong-candidates-left-out]

With no candidates left the name is `notfound` without a query (§4.1).

## 4.3.4 The case of a candidate [*engine-expansion.candidate-case-preserved]

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).
  [*engine-expansion.candidates-asked-one-at-a-time]
- 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. [*engine-expansion.found-or-nodata-ends-expansion]
- `unavailable` is the answer, and later candidates are not asked.
  [*engine-expansion.unavailable-ends-expansion]
- When the last candidate is `notfound`, the question is `notfound`
  (§4.1).

---

# 4.4 Scope Routing

_Peios / Reference / resolvd / The Engine_

> How resolvd picks the one scope a candidate goes to — which scopes take part at all, each step of the order as implemented, and how ties are broken.

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 [*engine-routing.only-routable-scopes-take-part]

A scope at `link` or better is up. Server availability does not exclude it
from explicit routing decisions. Search expansion uses the same up scopes.

## 4.4.2 The steps

1. **Exclusive.** Choose an exclusive scope at `addressed` or better,
   preferring the lowest metric and then snapshot order.
   [*engine-routing.step-exclusive]
2. **Search domain.** Among up scopes, choose the longest matching domain
   suffix, compared by labels without case distinctions.
   [*engine-routing.step-search-domain]
3. **Reverse subnet.** For a reverse-mapping name, choose an up scope whose
   subnet contains the address. Lowest metric wins, then snapshot order.
   A prefix beyond the address width is treated as that width.
   [*engine-routing.step-reverse-subnet]
4. **Default route.** Choose an up default-route scope, preferring the lowest
   metric and then snapshot order. [*engine-routing.step-default-route]
5. **Lowest metric.** Choose an up scope that has servers, preferring the
   lowest metric and then snapshot order. [*engine-routing.step-lowest-metric]
6. **Fallback.** Use the fallback scope if configured servers exist.
   [*engine-routing.step-fallback]

The first matching step wins. When none selects a scope, the candidate is
`unavailable` without a query.

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 4.4.2.1 An exclusive scope that does not qualify [*engine-routing.exclusive-without-servers-or-address-not-exclusive]

An exclusive scope at `link` alone does not qualify for step 1. It can
participate in later steps as an ordinary up scope.

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 4.4.2.2 A selected scope without servers [*engine-routing.serverless-scope-keeps-selection]

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 [*engine-routing.search-domain-tie-break]

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

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 4.4.3.1 Step 1 takes every candidate [*engine-routing.exclusive-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.

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 4.4.3.2 Search domains beat the subnet rule [*engine-routing.search-domain-beats-subnet]

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.

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 4.4.3.3 Fallback servers are a last resort [*engine-routing.fallback-unused-while-any-interface-has-a-server]

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

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 4.4.3.4 A candidate asks only its own scope's servers [*engine-routing.candidate-asks-only-its-scope]

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.

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 4.4.3.5 Demotion does not affect routing [*engine-routing.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_

> What resolvd caches and for how long, the key, the capacity and how entries are evicted, what a hit reports, and every event that flushes it.

The cache's key and lifetimes are set by PSPU §6.7. This article is how
resolvd computes them and what it does at the edges.

## 4.5.1 The cache key

- An entry is keyed by the candidate in lower case, the record type, and
  the scope key (§1.3). The class is not part of the key; every question
  resolvd asks is class `IN`. The stub rejects other classes before
  consulting the cache (§6.1), even when a matching `IN` answer is held.
  [*engine-cache.key-is-lowercase-candidate-type-scope]
- The same name asked through two scopes is two entries, and a single
  label's expansions are each cached under the expanded name.
  [*engine-cache.expansions-cached-under-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:

| Reply | Stored as | Lifetime |
|---|---|---|
| `NOERROR` with relevant answer records of class `IN` (§4.8) | `found` with those records | The least TTL among those records, capped at 86 400 s [*engine-cache.positive-lifetime] |
| `NOERROR` with no relevant answer records of class `IN` | `found` with none | Negative lifetime [*engine-cache.nodata-uses-negative-lifetime] |
| `NXDOMAIN` | `notfound` | Negative lifetime [*engine-cache.nxdomain-uses-negative-lifetime] |

### 4.5.2.1 The negative lifetime

- The negative lifetime comes from the first `IN` `SOA` record in the
  reply's authority section whose owner is the effective name or an
  enclosing domain. The effective name is the candidate after following
  its relevant CNAME path (§4.8); suffix matching respects label boundaries.
  Use the lesser of the SOA's `MINIMUM` field and its own TTL, capped at
  300 s. When an alias leads to NXDOMAIN, also cap the lifetime at the
  least TTL of that alias path. [*engine-cache.negative-lifetime-from-soa]
- A reply with no qualifying `SOA` in its authority section has a negative
  lifetime of zero. [*engine-cache.no-soa-negative-lifetime-zero]

### 4.5.2.2 A zero lifetime is not stored [*engine-cache.zero-lifetime-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 [*engine-cache.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.

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 4.5.2.4 The TTLs inside an entry [*engine-cache.record-ttls-kept-entry-lifetime-capped]

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. [*engine-cache.hit-ttl-lowered-to-remaining-seconds]
- A `notfound` hit with further candidates waiting moves to the next
  candidate, as a `notfound` from a server would (§4.1).

## 4.5.4 Bypassing the cache

- A `resolve` request with `no_cache` set skips the lookup for each of
  its candidates. The reply it gets is still stored.
  [*engine-cache.no-cache-skips-lookup-still-stores]
- Stub queries, `lookup`, and `reverse` always consult the cache.
  [*engine-cache.other-doors-always-consult-cache]

## 4.5.5 Capacity and eviction

- The cache holds at most 8 192 entries. [*engine-cache.capacity]
- Expiry alone does not remove an entry. Looking up an expired key
  removes it immediately, before any replacement answer arrives. Otherwise
  it stays until overwritten, flushed, or removed during admission at
  capacity. The `cache_entries` count in `status` includes expired entries
  that have not yet been removed.
  [*engine-cache.expired-entries-linger-and-are-counted]

### 4.5.5.1 Eviction

Storing an entry under a key the cache does not already hold, when it
already holds 8 192 entries, first evicts:

1. every entry whose expiry is at or before the current time;
   [*engine-cache.eviction-sweeps-expired-entries]
2. then, if the cache still holds 8 192 entries, the one entry with the
   earliest expiry — any one of them, when several share it.
   [*engine-cache.eviction-then-earliest-expiry]

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 4.5.5.2 A long-lived answer preserves other live entries [*engine-cache.long-lived-entry-preserves-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 [*engine-cache.overwrite-evicts-nothing]

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.

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 4.5.6.1 A reply after its scope was flushed [*engine-cache.late-reply-stored-after-flush]

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.
[*engine-cache.invalidated-task-does-not-store]

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_

> Which server each attempt goes to, what counts as a failure, how demotion works, how many attempts a question gets and how long it can take, and the in-flight ceiling.

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 [*engine-servers.transaction-timeout] |
| Attempts per question (all candidates and transports) | 3 [*engine-servers.attempts-per-candidate] |
| Demotion period | 30 s [*engine-servers.demotion-period] |
| Upstream transactions in flight | 4 096 [*engine-servers.in-flight-ceiling-value] |

## 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.
  [*engine-servers.healthy-first-then-demoted]
- 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.
  [*engine-servers.server-choice-rule]
- With one server, all three attempts go to it.
  [*engine-servers.single-server-gets-every-attempt]
- The order is computed afresh for each attempt, so a server demoted by
  the previous attempt is already behind its peers for the next.
  [*engine-servers.order-recomputed-each-attempt]
- 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.
  [*engine-servers.attempts-sequential]

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;
  [*engine-servers.timeout-fails-attempt]
- 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;
  [*engine-servers.send-error-fails-attempt-at-once]
- an error receiving on a UDP socket, such as the refusal that follows
  an ICMP port-unreachable; [*engine-servers.udp-receive-error-fails-attempt]
- for TCP, the connection failing to complete: an error or hang-up
  while it is being established;
  [*engine-servers.tcp-connect-failure-fails-attempt]
- for TCP, an error, a hang-up or a failed write before the whole query
  has been sent; [*engine-servers.tcp-error-before-query-sent-fails-attempt]
- for TCP, the connection closing, or a read error, before a whole matching
  reply
  has arrived; [*engine-servers.tcp-incomplete-reply-fails-attempt]
- a matching reply whose response code is neither `NOERROR` nor
  `NXDOMAIN` — `SERVFAIL`, `REFUSED`, `FORMERR`, `NOTIMP`, and every
  other code, including EDNS extended codes.
  [*engine-servers.failure-rcodes-fail-attempt]

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.
  [*engine-servers.demotion-marks-address-for-30-seconds]
- A matching reply with response code `NOERROR` or `NXDOMAIN` that
  resolvd uses — a UDP reply without `TC`, or a TCP reply — removes the
  server's mark at once. A UDP reply with `TC` set does not remove it,
  whatever its response code; the reply to the TCP retry decides.
  [*engine-servers.good-reply-clears-demotion]
- 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.
  [*engine-servers.demotion-is-per-address]
- A demoted server is still asked, after the healthy ones.
  [*engine-servers.demoted-servers-still-asked]
- `status` lists, for each scope, which of its servers are demoted at
  that moment (§5.3); demotion of the fallback servers is not reported.
  [*engine-servers.fallback-demotion-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). [*engine-servers.third-failure-is-unavailable]
- The budget is not reset when the question moves to another candidate,
  but a candidate's `NXDOMAIN` that moves it on is an answer, not a
  failure, and does not spend an attempt. Every search candidate is
  therefore asked, however many there are. Cached answers spend no
  attempt. [*engine-servers.limit-is-per-question]
- 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`.
  [*engine-servers.tcp-retry-spends-an-attempt]

The three attempts allow at most six seconds of upstream timeout waiting
in total, including TCP and search-domain expansion. Each `NXDOMAIN` that
moves to another candidate adds one round trip. Loop scheduling and local
I/O can add elapsed time; the attempt limit does not give those
operations a separate deadline.

## 4.6.5 The in-flight ceiling

- When 4 096 or more transactions are outstanding, a question about to
  allocate an upstream transaction is answered `unavailable` at once, and the
  `refused` counter goes up by one. A question whose scope has no
  servers left is answered `unavailable` before the ceiling is looked
  at, and is not counted as refused.
  [*engine-servers.in-flight-ceiling-refuses-new-transactions]
- 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.
  [*engine-servers.retries-checked-against-ceiling]
- Synthetic names and cache hits are answered as usual whatever the
  count. [*engine-servers.local-answers-unaffected-by-ceiling]

---

# 4.7 The Upstream Query

_Peios / Reference / resolvd / The Engine_

> What resolvd puts on the wire for each transaction — sockets and source ports, the message identifier and 0x20 case pattern, EDNS0, link-local servers, and the TCP retry.

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 [*engine-query.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. [*engine-query.udp-fresh-ephemeral-port]
- The socket is connected to the server's port 53, so the kernel
  delivers only datagrams from that address and port.
  [*engine-query.udp-socket-connected-to-server]
- Each datagram is read into a 4 096-byte buffer; a longer datagram is
  truncated by the read. [*engine-query.udp-read-buffer-4096]

The query is sent with one `send`.

### 4.7.1.3 The TCP connection [*engine-query.tcp-one-query-per-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 [*engine-query.send-failure-logged]

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 [*engine-query.link-local-server-uses-scope]

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.
[*engine-query.snapshot-zone-matches-interface]

`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.
[*engine-query.fallback-zone-unsupported]

## 4.7.3 The message

| Field | Value |
|---|---|
| ID | 16 bits from the kernel CSPRNG, fresh for every transaction [*engine-query.id-fresh-per-transaction] |
| Flags | `RD` set; `CD` clear; everything else clear [*engine-query.rd-set-other-flags-clear] |
| Question | The candidate, case-randomized; the record type asked; class `IN` [*engine-query.question-is-randomised-candidate-in-class-in] |
| Additional | One `OPT` record: payload size 1 232, `DO` clear, extended response code 0, version 0, no options [*engine-query.opt-record-advertises-1232] |

Authority and answer sections are empty.

### 4.7.3.1 Query entropy [*engine-query.cryptographic-entropy-per-transaction]

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.
[*engine-query.entropy-failure-is-unavailable]

### 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. [*engine-query.letters-flipped-on-generator-bits]
- Case bytes follow the ID bytes. Bits are taken lowest first from each
  byte in order. A bit is used only for a letter.
  [*engine-query.case-bits-consumed-per-letter]
- Each transaction — a retry to the same server, and the TCP retry after
  truncation, included — gets a new pattern and a new ID.
  [*engine-query.new-pattern-every-transaction]

## 4.7.4 No fallback without EDNS0 [*engine-query.no-fallback-without-edns]

Every query carries the `OPT` record. resolvd does not fall back to a
query without EDNS0: a server that answers an EDNS0 query with
`FORMERR` has failed the attempt (§4.6).

## 4.7.5 The TCP retry

- A matching UDP reply with `TC` set is not used. The same candidate is
  sent to the same server over TCP as a new transaction, with a new ID,
  a new case pattern and its own two-second deadline, if an attempt
  remains in the question budget. The TCP transaction spends one attempt
  (§4.6); without budget the question is `unavailable`.
  [*engine-query.truncated-udp-retried-over-tcp-same-server]
- A TCP reply with `TC` set is used as it is.
  [*engine-query.truncated-tcp-reply-used-as-is]

---

# 4.8 Reply Validation

_Peios / Reference / resolvd / The Engine_

> How resolvd decides a reply belongs to its transaction, what happens to one that does not, and what it takes from one that does — outcome, records, case, and lifetime.

## 4.8.1 Matching

A reply is matched against the transaction it arrived for. It matches
when all of these hold:

1. it decodes as a DNS message — bytes after its last section are
   tolerated; [*engine-reply.match-decodes]
2. its ID equals the transaction's; [*engine-reply.match-id]
3. its `QR` bit is set; [*engine-reply.match-qr-set]
4. it has exactly one question; [*engine-reply.match-one-question]
5. that question's type and class equal those sent;
   [*engine-reply.match-type-and-class]
6. that question's name is byte-for-byte identical to the name sent,
   case pattern included. [*engine-reply.match-name-case-exact]

### 4.8.1.1 A non-matching reply is ignored [*engine-reply.non-matching-reply-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.

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 4.8.1.2 A non-matching datagram on UDP [*engine-reply.non-matching-udp-datagram-becomes-timeout]

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

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 4.8.1.3 An undecodable or cut-short datagram [*engine-reply.undecodable-or-cut-short-datagram-becomes-timeout]

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.

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 4.8.1.4 A non-matching TCP reply [*engine-reply.non-matching-tcp-reply-becomes-timeout]

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` [*engine-reply.noerror-is-found] |
| Response code `NXDOMAIN` | `notfound` [*engine-reply.nxdomain-is-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 [*engine-reply.extended-rcode-combined]

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. [*engine-reply.answer-records-of-class-in]
- For `NXDOMAIN` none are taken, even if the server sent some.
  [*engine-reply.nxdomain-records-discarded]
- Start at the candidate. Keep records of the requested type at that
  owner; otherwise follow the first `IN` CNAME there, retaining it, and
  repeat at its target. Stop after sixteen aliases, on a repeated name,
  or when no matching record remains. Records unrelated to that path or
  of an unrequested type are discarded before rendering or caching.
  Their TTLs cannot shorten the cache lifetime.
  [*engine-reply.records-match-question]
- An explicit CNAME question returns CNAME records at the queried owner.
  ANY accepts all `IN` types at that owner and does not follow aliases.
  Owner comparisons are case-insensitive and use DNS label boundaries.
- The authority and additional sections are not returned.
  [*engine-reply.authority-and-additional-not-returned]

### 4.8.3.2 The case of returned records [*engine-reply.candidate-case-restored]

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 [*engine-reply.upstream-flags-not-carried]

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` [*engine-reply.empty-noerror-is-nodata]

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_

> How a lookup becomes one task per family and how their results are combined — outcome, CNAME chasing, the canonical name, address order, and source — and how a reverse becomes a PTR question.

## 4.9.1 `lookup`

A `lookup` (PSPU §6.5) asks for `A`, `AAAA`, or both:

| `family` | Tasks |
|---|---|
| `any` | `A` and `AAAA`, started together [*engine-lookup.any-starts-both-families] |
| `inet` | `A` [*engine-lookup.inet-asks-a] |
| `inet6` | `AAAA` [*engine-lookup.inet6-asks-aaaa] |

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 4.9.1.1 Each task is an ordinary question [*engine-lookup.tasks-independent-reply-after-last]

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` [*engine-lookup.any-found-is-found] |
| None `found`, at least one `unavailable` | `unavailable` [*engine-lookup.unavailable-without-found] |
| Every one `notfound` | `notfound` [*engine-lookup.all-notfound-is-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.

1. If the first record at the current name is a `CNAME`, and no record
   of the asked type is at the current name, the chase moves to the
   `CNAME`'s target. [*engine-lookup.cname-chase-follows-first-cname]
2. This repeats at most 16 times; a loop stops there.
   [*engine-lookup.cname-chase-depth-16]
3. The addresses are the `A` (for the `A` task) or `AAAA` (for the
   `AAAA` task) records at the name the chase ended at, in answer order,
   each with its record's TTL.
   [*engine-lookup.cname-chase-addresses-at-final-name]

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 4.9.1.4 The chase asks nothing further [*engine-lookup.chase-asks-no-further-question]

Only the records in the task's own answer are used. A chain that leaves
them — a `CNAME` whose target's addresses the server did not include —
ends with no addresses, and no further question is asked.

### 4.9.1.5 The reply fields

- `addresses` lists each finished task's addresses in turn, in the order
  the tasks finished, so whether IPv4 or IPv6 addresses come first
  depends on which family was answered first.
  [*engine-lookup.address-order-follows-completion]
- `canonical` and `source` come from the same selected `found` task.
  Prefer a task that produced addresses; when both or neither did, prefer
  `A` over `AAAA`. Completion order does not affect this choice.
  `canonical` is the name that task's CNAME chase ended at, after search
  expansion. Without a `found` task it is the name asked, as parsed, in
  presentation form without a trailing dot (the root is `.`).
  [*engine-lookup.canonical-name-rule]
- A `found` with no addresses still reports the expanded or chased name.
  [*engine-lookup.canonical-expanded-without-addresses]
- A name that does not parse is answered at once with `outcome`
  `notfound`, `canonical` `.`, no addresses and `source` `local`; no
  task is started. [*engine-lookup.unparseable-name-canonical-root]
- `source` is the source of the selected task, and `local` when no task
  was `found`. It describes that task; the other family's records can
  have a different source. [*engine-lookup.deterministic-source]
- `validation` is `unvalidated`.
- A `lookup` adds one to `queries` however many tasks it makes.
  [*engine-lookup.counts-one-query]

## 4.9.2 `reverse` becomes a `PTR` question [*engine-lookup.reverse-is-ptr-resolve]

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 seven counters status reports, exactly what moves each one, and what resets them.

The engine keeps seven counters, reported by `status` (§5.3). Each is an
unsigned 64-bit count.

## 4.10.1 What each counter counts

| Counter | Goes up by one for |
|---|---|
| `queries` | Every `resolve`, `lookup` and `reverse` request that passes the access check, and every syntactically accepted stub query, including UDP budget refusals and requests whose name does not parse [*engine-counters.queries] |
| `synthetic` | Every task answered by a synthetic name (§4.2), including `.local`'s `notfound`; an `any` lookup of `localhost` adds two [*engine-counters.synthetic] |
| `cache_hits` | Every candidate found live in the cache (§4.5), including a `notfound` hit that moves on to the next candidate [*engine-counters.cache-hits] |
| `upstream_sent` | Every transaction started, UDP or TCP, including TCP retries. It is counted before the socket is opened, so a transaction whose socket cannot be opened, connected or sent on (§4.7) counts here as well as in `upstream_failed`, though nothing reached the wire [*engine-counters.upstream-sent] |
| `upstream_answered` | Every matching reply (§4.8), whatever its response code, including a truncated one [*engine-counters.upstream-answered] |
| `upstream_failed` | Every failed transaction (§4.6): a timeout, a transport failure, or a reply with a response code other than `NOERROR` and `NXDOMAIN` [*engine-counters.upstream-failed] |
| `refused` | Every question refused at the in-flight ceiling (§4.6), the UDP pending budgets (§6.1), or because fresh query entropy is unavailable (§4.7) [*engine-counters.refused] |

## 4.10.2 What is not counted [*engine-counters.status-flush-and-netd-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 [*engine-counters.reset-only-by-restart]

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_

> How resolvd reads a request from a native connection — the connection cap, the size ceiling, the five-second bound, decoding, and the exact error replies — and how it writes the reply.

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.

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
## 5.1.1 Accepting connections [*native-framing.pending-connection-cap-closes-silently]

At most 64 waiting connections are accepted per event-loop iteration.
When 256 native connections are either still sending their requests or
waiting for engine answers, a newly accepted connection is closed at
once, with no reply; so is one that cannot be made nonblocking. Reading a
request keeps its slot occupied until resolution completes or the asker
is abandoned (§4.1). Reply writers use a separate bounded queue (§2.5).

## 5.1.2 Reading the request

Each connection is read without blocking. Partial headers and payloads
are retained until more bytes arrive or the delivery bound expires.

1. Read exactly the four-byte little-endian payload length. A length
   above 65 536 gets the reply `request too large` and the connection
   closes, without reading any payload bytes. [*native-framing.length-ceiling]
2. Read only that many payload bytes, in chunks of at most 4 096 bytes.
   The buffered frame never exceeds 65 540 bytes, including its header.
   [*native-framing.buffered-bytes-ceiling]
3. Decode the complete payload immediately. Bytes after this first frame
   remain unread and do not count against its size ceiling; they cannot
   make a legal request too large. [*native-framing.trailing-bytes-ignored]

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 5.1.2.1 The length check precedes the payload [*native-framing.payload-read-before-length-check]

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. [*native-framing.early-close-dropped]
- 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.
  [*native-framing.request-then-half-close-dropped]
- A connection that has not delivered a complete request five seconds
  after it was accepted is closed without a reply.
  [*native-framing.five-second-delivery-bound]

## 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.
[*native-framing.duplicate-top-level-key-is-error]

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.
[*native-framing.unknown-keys-skipped]
[*native-framing.unknown-key-unsupported-value-fails]
[*native-framing.unknown-key-nesting-limit]
[*native-framing.proposed-unknown-field-correction]

`query` is required and must name a supported operation.
[*native-framing.missing-or-unknown-query-is-error]

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.
[*native-framing.wrong-field-type-is-error]

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.
[*native-framing.bytes-after-map-ignored]

## 5.1.5 Error replies

Every error reply is `ok: false` with an `error` string and nothing
else. The decoder reports these causes:

| `error` | Cause |
|---|---|
| `request too large` | The size checks above |
| `malformed message: truncated message` | The payload ends inside a value, or an array or map claims more items than bytes remain, a map's keys and values counted separately [*native-framing.error-truncated] |
| `malformed message: unexpected value type` | A known field, a key, or the payload itself has the wrong MessagePack type; this includes a `type` that is negative or above 9 223 372 036 854 775 807 [*native-framing.error-unexpected-type] |
| `malformed message: unsupported value type` | The reserved MessagePack marker `0xC1` [*native-framing.error-unsupported-type] |
| `malformed message: string is not UTF-8` | A string that is not UTF-8 [*native-framing.error-not-utf8] |
| `malformed message: nested too deeply` | Nesting beyond 32 levels inside a skipped value [*native-framing.error-nested-too-deeply] |
| `missing or malformed field <name>` | A field the request needs is absent; a `type`, in any request, from 65 536 to 9 223 372 036 854 775 807; or the `address` of a `reverse` that is not an IP address [*native-framing.error-missing-or-malformed-field] |
| `duplicate field <name>` | A repeated key [*native-framing.error-duplicate-field] |
| `unknown query "<name>"` | A `query` resolvd does not know [*native-framing.error-unknown-query] |
| `access denied` | The access check (§5.2) |
| `reply too large` | The encoded reply would exceed the 65 536-byte payload ceiling; it is replaced by this error |

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 5.1.5.1 The connection after an error reply [*native-framing.connection-closed-after-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.
  [*native-framing.reply-written-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.
  [*native-framing.reply-size-not-checked]

---

# 5.2 The Access Check

_Peios / Reference / resolvd / The Native Socket_

> How resolvd checks each native request against its control object — the peer's token, the generic mapping, the compiled default descriptor — and when a new descriptor takes effect.

The control object and its check are PSPU §6.4's. resolvd makes the
check after the request has been decoded and before anything else is
done with it.

## 5.2.1 The check

1. The connecting peer's token is opened from the socket. When it
   cannot be, resolvd logs `control: no peer token: <error>` and the
   request is denied. [*native-access.no-peer-token-is-denial]
2. A KACS access check is made of the request's right against the
   control object's descriptor, with that token. A check that cannot be
   completed counts as a denial. [*native-access.failed-check-is-denial]
3. A denied request is answered `access denied` (§5.1).
   [*native-access.denial-reply]

| Request | Right |
|---|---|
| `resolve`, `lookup`, `reverse`, `status` | `RESOLVER_QUERY` (`0x0001`) [*native-access.query-right-requests] |
| `flush` | `RESOLVER_CONTROL` (`0x0002`) [*native-access.control-right-requests] |

### 5.2.1.1 The generic mapping [*native-access.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 [*native-access.decode-before-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`.

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 5.2.1.3 The answer does not depend on the caller [*native-access.answer-independent-of-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.

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
## 5.2.2 The compiled default descriptor [*native-access.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` |

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
## 5.2.3 A new descriptor applies to later requests [*native-access.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 [*native-access.stub-not-governed]

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_

> What resolvd does with each native request — resolve, lookup, reverse, status, flush — and what it puts in each reply field.

The requests, their fields, and their reply shapes are PSPU §6.5. This
article covers what resolvd accepts and what it fills in.

## 5.3.1 Common to every request

A request that passes the access check (§5.2) is handled at once:

- `status` and `flush` are answered within the same loop iteration;
  [*native-requests.status-and-flush-answered-at-once]
- the other three become engine questions (§4.1), and the connection is
  held until the engine answers; the reply is written then.
  [*native-requests.questions-held-until-answered]

## 5.3.2 `resolve`

| Field | Accepted |
|---|---|
| `name` | Any string: no `name` is refused at decoding. It is handed to the engine as it is, which parses it (§4.1). [*native-requests.resolve-name-accepted] |
| `type` | Any value from 0 to 65 535, forwarded as it is — `ANY` (255), `OPT` (41) and types resolvd has no parser for included. [*native-requests.resolve-type-forwarded-as-is] |
| `no_cache` | Boolean; absent means `false`. Skips the cache lookup (§4.5). [*native-requests.resolve-no-cache-default-false] |

The reply's `outcome`, `source`, `server`, `interface`, and `rcode` are
as §4.1 describes. Each record carries:

| Key | Content |
|---|---|
| `name` | The owner name in presentation form, without a trailing dot; the root is `.`. A dot or backslash inside a label is written `\.` or `\\`, and any byte outside `!` to `~` as a backslash and three decimal digits. [*native-requests.record-name-presentation] |
| `type` | The record type number |
| `ttl` | As sent by the server, lowered on a cache hit (§4.5); 0 for a synthetic record |
| `data` | The record data in uncompressed wire form [*native-requests.record-data-uncompressed-wire] |
| `text` | The record data in presentation form (below) [*native-requests.record-text-forms] |

| 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 [*native-requests.lookup-unknown-family-is-any]

`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 [*native-requests.reverse-bad-address-is-error]

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

| Key | Content |
|---|---|
| `hostname` | The hostname in use (§3.3), or an empty string when there is none [*native-requests.status-hostname] |
| `netd` | Whether the netd channel is connected at this moment [*native-requests.status-netd] |
| `scopes` | Every scope in the latest snapshot, in snapshot order — including scopes with no servers and scopes that take no part in routing [*native-requests.status-scopes-every-scope] |
| `fallback_servers` | `FallbackServers` as parsed (§2.3) [*native-requests.status-fallback-servers] |
| `cache_entries` | The number of entries held, expired ones included (§4.5) |
| `counters` | §4.10 |

### 5.3.5.1 Each scope in `status`

Each scope carries `interface` (the interface name), `servers` and
`domains` as parsed from the snapshot (§3.3), `default_route`,
`exclusive`, `metric`, `subnets`, and `demoted`:

- `subnets` holds the interface's addresses as `address/prefix` — the
  address itself, not the network it is in;
  [*native-requests.status-subnets-are-interface-addresses]
- `demoted` holds those of the scope's servers that are demoted at this
  moment (§4.6); [*native-requests.status-demoted-servers]
- a scope's `level` is not reported.
  [*native-requests.status-level-not-reported]

## 5.3.6 `flush`

- Every cache entry, for every scope, is discarded, resolvd logs
  `cache flushed` at info level, and the reply is `ok: true` with no
  `kind`. [*native-requests.flush-discards-everything]
- Demotions and counters are left as they are.
  [*native-requests.flush-keeps-demotions-and-counters]

---

# 6.1 Receiving Queries

_Peios / Reference / resolvd / The Stub Listener_

> How the stub listener reads queries over UDP and TCP — source checks, connection limits, the per-connection bound, the queries it refuses at the door, and what it ignores in a query it accepts.

The stub listener's address, its loopback-only rule and its rendering
are PSPU §6.8. This article covers how resolvd reads queries; the
replies are §6.2.

## 6.1.1 UDP

When the UDP socket is readable, at most 64 datagrams are read per
event-loop iteration, including malformed or dropped datagrams. For each:

1. A datagram whose source address is not a loopback address — anything
   outside `127.0.0.0/8` — is dropped without a reply.
   [*stub-receive.udp-non-loopback-source-dropped]
2. It is checked as a query (below). A refused query gets its error
   reply, or nothing.
3. A valid query is admitted if fewer than 16 UDP questions from its
   source address **and port**, and fewer than 256 UDP questions in total,
   are waiting for engine answers. Otherwise it gets `SERVFAIL`, with no
   upstream transaction, and increments both `queries` and `refused`.
   This admission check precedes synthetic and cache lookup.
   [*stub-receive.udp-pending-budgets]
4. An admitted query becomes an engine question (§4.1). Its slot is
   released when the engine completes it, including timeout completion.

The endpoint is an accounting key, not an authenticated process identity.
Changing source ports can consume the aggregate UDP allowance but cannot
consume the separate native or TCP admission allowances. These bounds
limit retained work; they do not promise fairness between local processes.

### 6.1.1.1 The UDP read buffer [*stub-receive.udp-read-buffer-4096]

Each datagram is read into a 4 096-byte buffer; a longer datagram is
truncated by the read to its first 4 096 bytes.

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
### 6.1.1.2 A UDP query longer than the buffer [*stub-receive.udp-oversized-query-formerr]

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 [*stub-receive.udp-reply-to-source]

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; [*stub-receive.tcp-pending-cap-256]
- when its source is not a loopback address.
  [*stub-receive.tcp-non-loopback-source-closed]

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. [*stub-receive.tcp-buffer-ceiling]
- 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. [*stub-receive.tcp-one-query-per-connection]
- 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.
  [*stub-receive.tcp-query-then-half-close-dropped]
- A connection that has not delivered a whole message ten seconds after
  it was accepted is closed without a reply.
  [*stub-receive.tcp-ten-second-delivery-bound]
- 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). [*stub-receive.tcp-bound-ends-once-query-arrives]

## 6.1.3 Checking a query

| The message | Result |
|---|---|
| Does not decode, and is at least 12 bytes long | `FORMERR`: the query's ID, `QR` set, every other header bit clear, no sections [*stub-receive.undecodable-long-message-formerr] |
| Does not decode, and is shorter than 12 bytes | Dropped without a reply [*stub-receive.undecodable-short-message-dropped] |
| Has `QR` set | Dropped without a reply [*stub-receive.response-dropped] |
| Has an opcode other than `QUERY` | `NOTIMP` [*stub-receive.non-query-opcode-notimp] |
| Has no question, or more than one | `FORMERR` [*stub-receive.question-count-formerr] |
| Has a question class other than `IN` | `NOTIMP`; the question is echoed unchanged and no upstream query is made [*stub-receive.unsupported-class-notimp] |
| Otherwise | Accepted |

### 6.1.3.1 The `NOTIMP` and question-count `FORMERR` replies

These two replies are built from the query:

- the header copies the query's ID, opcode, `RD` and `CD` bits, and
  sets `QR` and `RA`; every other bit is clear;
  [*stub-receive.error-reply-header]
- the question section is the query's, whatever it holds;
  [*stub-receive.error-reply-question]
- when the query carried an `OPT` record, the reply carries one whose
  payload size is the size the query advertised, with `DO` clear and no
  options; without one, the reply has none.
  [*stub-receive.error-reply-opt-size]

## 6.1.4 What an accepted query contributes

- Only `IN` questions are accepted. Their decoded name and type reach the
  engine; unsupported classes are rejected at the stub door over both
  UDP and TCP.
- `RD`, `CD`, the `DO` bit, and any EDNS options are not looked at.
  [*stub-receive.flags-and-edns-options-ignored]
- 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).
[*stub-receive.wire-labels-preserved]

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.
[*stub-receive.wire-lengths-preserved]

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 [*stub-receive.refused-queries-not-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_

> How an engine answer becomes a DNS reply at the stub listener — header bits, the CNAME for an expanded name, negative replies, EDNS, and truncation.

The outcome-to-response-code table and the rules for `CNAME`, `RA`, `AA`
and `AD` are PSPU §6.8. This article is how resolvd builds each reply.

## 6.2.1 The header and question

- The reply copies the query's ID, opcode, `RD` and `CD` bits and its
  question section. [*stub-render.copied-header-fields]
- `QR` and `RA` are set. `AA`, `AD` and `TC` are clear, except that `TC`
  is set on a truncated UDP reply (below).
  [*stub-render.qr-ra-set-aa-ad-clear]
- No bit from an upstream server's reply reaches the stub reply.
  [*stub-render.no-upstream-bits]

## 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).
  [*stub-render.found-records-in-engine-order]
- When the answer was found at a candidate other than the question's
  name — compared case-insensitively — the section begins with a
  `CNAME` from the question's name, in
  the query's case, to the candidate. Its TTL is the least TTL among the
  records when any are present. [*stub-render.expansion-cname]
- A `found` with no records at an expanded name is `NOERROR` with only
  that leading `CNAME`. Its TTL is the negative cache lifetime: the lesser
  of the enclosing upstream `SOA` record's TTL and minimum field, capped at
  300 seconds and at the TTL of any `CNAME` path the reply followed (§4.5).
  A cache hit uses the remaining lifetime, rounded down to whole seconds.
  With no enclosing `SOA`, the TTL is zero; no lifetime is invented. The
  authority section remains empty. An unexpanded empty `found` has no
  `CNAME`. [*stub-render.expanded-nodata-has-no-cname]

### 6.2.2.2 `notfound` replies [*stub-render.nxdomain-without-soa]

`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 [*stub-render.servfail-empty]

`SERVFAIL`, with empty sections.

## 6.2.3 EDNS in stub replies [*stub-render.opt-echoed-with-1232]

When the query carried an `OPT` record, the reply carries one
advertising a payload size of 1 232 bytes, with `DO` clear and no
options. A query without `OPT` gets a reply without one.

## 6.2.4 Size and truncation

- Over UDP the reply's size limit is the payload size the query's `OPT`
  advertised, or 512 bytes when that is smaller or there is no `OPT`.
  [*stub-render.udp-size-limit]
- A reply over the limit is replaced by a truncated one, which keeps the
  same header with `TC` set, and the question.
  [*stub-render.truncated-reply-header-and-question]
- The truncated reply keeps the `OPT` record when the reply has one.
  [*stub-render.truncated-reply-keeps-opt]
- The truncated reply carries no records: nothing is partially
  included. [*stub-render.truncated-reply-has-no-records]
- A reply that cannot be encoded at all is not sent.
  [*stub-render.unencodable-reply-not-sent]
- Over TCP the whole reply is sent, whatever its size up to the 65 535
  bytes a DNS message can hold. [*stub-render.tcp-sends-whole-reply]
- 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.
  [*stub-render.tcp-write-failure-not-logged]

---

# 7.1 The Module

_Peios / Reference / resolvd / The Nss Shim_

> libnss_peios_net.so.2 as built — what it links, how each call talks to resolvd, its timeout, and the status, errno and h_errno it returns for every result.

The shim's obligations are PSPU §6.10. This chapter describes the module
resolvd's source tree builds.

## 7.1.1 The object

- `libnss_peios_net.so.2` is installed by `dev.peios.resolvd-nss` at
  `/usr/lib/x86_64-linux-peios/libnss_peios_net.so.2`.
  [*nss-module.installed-path]
- It is built from the `nss` crate, with the native channel codec
  compiled in. Its only shared-object dependencies are `libc.so.6` and
  the dynamic loader, `ld-linux-x86-64.so.2`. The GCC unwinder required by
  Rust is linked statically, with its symbols private to the module; name
  lookups do not load `libgcc_s.so.1`. The identity shim, `libnss_peios.so.2`,
  uses the same static-unwinder arrangement. Neither shim links libpeios.
  [*nss-module.link-dependencies]

### 7.1.1.1 The entry points [*nss-module.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. [*nss-module.one-connection-per-call]
- Nothing is kept between calls: no connection, no cache, no
  configuration. The module reads no file. [*nss-module.no-state-no-files]

### 7.1.2.1 The ten-second socket timeouts [*nss-module.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

| Result | NSS status | `errno` | `h_errno` |
|---|---|---|---|
| Addresses, or names, found | `SUCCESS` | — | — [*nss-module.found-is-success] |
| `found`, but no address of the asked family | `NOTFOUND` | `ENOENT` | `NO_DATA` [*nss-module.found-without-family-is-host-not-found] |
| `notfound` | `NOTFOUND` | `ENOENT` | `HOST_NOT_FOUND` [*nss-module.notfound-is-host-not-found] |
| `unavailable` | `TRYAGAIN` | `EAGAIN` | `TRY_AGAIN` [*nss-module.unavailable-is-try-again] |
| No reply within ten seconds | `TRYAGAIN` | `EAGAIN` | `TRY_AGAIN` [*nss-module.timeout-is-try-again] |
| resolvd cannot be connected to | `UNAVAIL` | `ENOENT` | `NO_RECOVERY` [*nss-module.unreachable-is-unavail] |
| An error reply, including `access denied` | `UNAVAIL` | `ENOENT` | `NO_RECOVERY` [*nss-module.error-reply-is-unavail] |
| A reply of the wrong kind, a reply that does not decode, or any other I/O error | `UNAVAIL` | `ENOENT` | `NO_RECOVERY` [*nss-module.other-failures-are-unavail] |
| The caller's buffer is too small | `TRYAGAIN` | `ERANGE` | `NETDB_INTERNAL` (`-1`), required for retry [*nss-module.small-buffer-is-erange] |
| `gethostbyname3_r` or `2_r` with an `af` other than `AF_INET` or `AF_INET6` | `UNAVAIL` | `EAFNOSUPPORT` | `NO_DATA` [*nss-module.unsupported-family-forward] |
| `gethostbyaddr2_r` or `_r` with an `af` and length other than `AF_INET`/4 or `AF_INET6`/16 | `UNAVAIL` | `EAFNOSUPPORT` | `NO_RECOVERY` [*nss-module.unsupported-family-reverse] |
| A null name, a name that is not UTF-8, or a null address | `NOTFOUND` | `ENOENT` | `HOST_NOT_FOUND` [*nss-module.null-or-non-utf8-input-is-notfound] |

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`.
[*nss-module.found-without-family-is-no-data]

<!-- Keep the published reference identifier. -->
<!-- lint-disable-next-line spelling -->
### 7.1.3.1 `AF_UNSPEC` [*nss-module.af-unspec-only-via-gethostbyname4]

`AF_UNSPEC` is accepted only by `gethostbyname4_r`, which always asks
for both families.

## 7.1.4 The caller's buffer [*nss-module.results-placed-in-caller-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_

> How the shim answers a host name — localhost in-process, everything else through a lookup — and how the reply is laid out as gaih_addrtuple and hostent.

## 7.2.1 `localhost` in the shim

- A name that, with trailing dots removed, is `localhost` or ends in
  `.localhost`, compared case-insensitively, is answered inside the
  calling process without contacting resolvd — whether resolvd is
  running or not. [*nss-forward.localhost-answered-in-process]
- The answer is `127.0.0.1` for IPv4, `::1` for IPv6, or both, IPv4
  first, with canonical name `localhost` and TTL 0.
  [*nss-forward.localhost-answer]

## 7.2.2 Other names

- Any other name is sent as a `lookup` (§4.9), with the family the
  entry point asks for. The addresses in the reply are filtered to that
  family, and an empty result is `NOTFOUND` (§7.1).
  [*nss-forward.addresses-filtered-to-family]
- Addresses are returned in the order resolvd's reply lists them.
  [*nss-forward.reply-order-kept]

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:

| Field | Content |
|---|---|
| `next` | The next tuple: one tuple per address, in reply order [*nss-forward.gaih-addrtuple-order] |
| `name` | One copy of the canonical name, shared by every tuple [*nss-forward.gaih-addrtuple-name-shared] |
| `family` | `AF_INET` or `AF_INET6`, per address [*nss-forward.gaih-addrtuple-family] |
| `addr` | The address |
| `scopeid` | 0, so an IPv6 link-local address is returned without the interface it belongs to [*nss-forward.gaih-addrtuple-scopeid-zero] |

### 7.2.3.1 The `gethostbyname4_r` TTL [*nss-forward.gethostbyname4-ttl-least]

When `ttlp` is given it receives the least TTL among the addresses.

## 7.2.4 The forward `hostent` [*nss-forward.hostent-layout]

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

<!-- Keep the published citation identifier on its heading. -->
<!-- lint-disable-next-line line-length -->
## 7.2.5 The `gethostbyname3_r` TTL and canonical name [*nss-forward.gethostbyname3-ttl-and-canon]

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_

> How the shim answers an address — loopback in-process, everything else through a reverse — and which records become h_name and h_aliases.

## 7.3.1 Loopback addresses in the shim [*nss-reverse.loopback-answered-in-process]

An address in `127.0.0.0/8`, or `::1`, is answered inside the calling
process without contacting resolvd: `h_name` is `localhost`, with no
aliases and TTL 0.

## 7.3.2 Other addresses

- Any other address is sent as a `reverse` (§4.9). A `found` reply with
  no records is `NOTFOUND` (§7.1).
  [*nss-reverse.found-without-records-is-notfound]
- A found reply without a PTR record returns `NOTFOUND`, `ENOENT`, and
  `NO_DATA`. Explicit `notfound` returns `HOST_NOT_FOUND`; transient failures
  retain their separate results (§7.1).
  [*nss-reverse.no-ptr-record-is-notfound]

## 7.3.3 The reverse `hostent` [*nss-reverse.hostent-layout]

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 [*nss-reverse.ttl-least-of-all-records]

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_

> The operator command — its verbs and arguments, the request each sends, its output formats, and its exit statuses.

`resolv` (`/usr/bin/resolv`, package `dev.peios.resolv`) owns no state.

## 8.1.1 One request per verb [*resolv.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

| Command | Request |
|---|---|
| `resolv status` | `status` |
| `resolv query <name> [<type>] [--no-cache]` | `resolve` |
| `resolv lookup <name>` | `lookup`, family `any` |
| `resolv reverse <address>` | `reverse` |
| `resolv flush` | `flush` |
| `resolv version`, `resolv --version` | none: prints `resolv <version>` [*resolv.version-needs-no-daemon] |

### 8.1.2.1 The command line

- `--no-cache` is recognized anywhere on the command line and removed
  before the rest is matched; it affects only `query`.
  [*resolv.no-cache-anywhere]
- Any other argument list prints a usage line to standard error and
  exits 64. [*resolv.usage-exit-64]

### 8.1.2.2 Arguments checked before contacting resolvd

- The `<type>` of `query` is `A` when omitted. It is one of `A`, `NS`,
  `CNAME`, `SOA`, `PTR`, `MX`, `TXT`, `AAAA`, `SRV` or `ANY`, in any
  case, or `TYPE<n>` for any type number from 0 to 65 535.
  [*resolv.query-type-names]
- Any other `<type>` prints `resolv: unknown record type "<type>"` and
  exits 1 without contacting resolvd. [*resolv.unknown-type-exits-1]
- The `<address>` of `reverse` is checked in the same way: anything
  that is not an IPv4 or IPv6 address prints
  `resolv: "<address>" is not an address` and exits 1 without
  contacting resolvd. [*resolv.bad-address-exits-1]

### 8.1.2.3 Bounded exchanges in `resolv` [*resolv.no-timeout]

`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 [*resolv.query-output]

`query` prints a summary line, then one line per record:

```text
<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 [*resolv.lookup-output]

`lookup` prints `<outcome>  <source>  canonical <name>`, then
`<address>	<ttl>`, tab-separated, for each address.

### 8.1.3.3 `reverse` output [*resolv.reverse-output]

`reverse` prints `<outcome>  <source>`, then the `text` of every record
in the answer, whatever its type.

### 8.1.3.4 `status` output [*resolv.status-output]

`status` prints three lines:

```text
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

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

```text
queries <n>  synthetic <n>  cache-hits <n>  upstream sent <n> answered <n> failed <n>  refused <n>
```

### 8.1.3.5 `flush` output [*resolv.flush-silent]

`flush` prints nothing on success.

## 8.1.4 Exit status

| Status | Meaning |
|---|---|
| 0 | `found`, or `status`, `flush` or `version` succeeded [*resolv.exit-0] |
| 1 | resolvd unreachable, a protocol failure, an error reply (including `access denied`), or a bad type or address argument; an unexpected reply kind is diagnosed [*resolv.exit-1] |
| 2 | `notfound` [*resolv.exit-2] |
| 3 | `unavailable` [*resolv.exit-3] |
| 64 | A command line `resolv` does not recognize |

### 8.1.4.1 The unreachable message [*resolv.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_

> The signals available when names stop resolving — what resolv status, the counters, the log, and each door's error shape tell you — and the log lines resolvd writes.

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

| Line | Level | Meaning |
|---|---|---|
| `native socket: <error>` | error | Startup failed at the native socket; resolvd exits (§2.2) |
| `stub listener on 127.0.0.53:53: <error>` | error | Startup failed at port 53; resolvd exits (§2.2) |
| `poll: <error>` | error | The loop failed; resolvd exits (§2.2) |
| `could not set a descriptor on <path> (<error>); …` | error | The native socket is reachable only by SYSTEM and administrators (§2.4) |
| `removed a stale /run/resolvd/resolv.sock` | warn | A previous instance left its socket behind and this one removed it; expected on every restart of the service (§2.4) |
| `could not build a descriptor: <error>` | warn | As `could not set a descriptor …`, but before writing was attempted (§2.4) |
| `registry watch unavailable (<error>); configuration is read once` | warn | Configuration changes will not be seen (§2.3) |
| `registry watch: <error>; re-arming` | warn | The watch failed and is being replaced (§2.3) |
| `Dns FallbackServers: ignoring malformed address "<s>"` | warn | §2.3 |
| `Dns ExtraSearchDomains: ignoring malformed domain "<s>"` | warn | §2.3 |
| `Dns Hosts: ignoring malformed name "<s>"` | warn | §2.3 |
| `Dns Hosts: ignoring malformed address "<s>"` | warn | §2.3 |
| `ControlSecurity is not a valid descriptor (<error>); using the default` | warn | §2.3 |
| `readiness notify: <error>` | warn | peinit was not told resolvd is ready (§2.1) |
| `netd not reachable (<error>); retrying` | warn | First failure to reach netd (§3.2) |
| `netd refused the subscription: <message>` | warn | netd answered `subscribe` with an error (§3.1) |
| `netd sent something unreadable: <error>` | warn | §3.1 |
| `lost the netd channel; reconnecting` | warn | §3.1 |
| `upstream <server>: <error>` | warn | A transaction could not be sent (§4.7) |
| `control: no peer token: <error>` | warn | A native request was denied because its token could not be read (§5.2) |
| `control: reply failed: <error>` | warn | A native reply could not be written (§5.1) |
| `stub udp: <error>`, `stub tcp accept: <error>`, `native accept: <error>` | warn | A listener read or accept failed. Accept errors pause that listener for 250 ms before retrying; other descriptors continue to be serviced [*failure-signals.listener-errors-logged-and-survived] |
| `listening on /run/resolvd/resolv.sock and 127.0.0.53:53` | info | Startup reached readiness (§2.2) |
| `subscribed to netd` | info | §3.1 |
| `netd: <summary>` | info | A snapshot was applied (§3.3) |
| `configuration changed` | info | A registry change was applied (§2.3) |
| `cache flushed` | info | A `flush` request was carried out (§5.3) |
| `/dev/kmsg mirror unavailable (<error>): log lines go to stdout/stderr only` | warn | The kernel log mirror could not be opened, which for resolvd is always; written once, directly after the first line logged (§2.1) |

## 9.1.3 What a question logs [*failure-signals.no-per-question-logging]

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_

> The common ways resolution fails while resolvd is running — no scopes, unreachable servers, single labels that never leave the machine, an exclusive scope, overload, stale answers — what each looks like and how to get back to a known state.

## 9.2.1 Everything needing the network is `unavailable`

**Looks like:** `resolv query example.com` exits 3; the stub answers
`SERVFAIL`; `getaddrinfo` returns `EAI_AGAIN`. `localhost`, the
hostname, and static names still answer.

**Check `resolv status`:**

- **`netd not connected` and `scopes (none)`.** resolvd has never had a
  snapshot. Without fallback servers nothing can be asked (§4.4). Start
  netd; resolvd reconnects within ten seconds of netd's socket appearing
  (§3.2) and the first snapshot brings the scopes.
- **Scopes listed, but none has a server.** An explicit routing rule can
  select a serverless scope and return
  unavailable (§4.4). Either the profiles and leases supply
  no servers, or the offered addresses or explicit zones were invalid
  (§4.7). Correct the selected profile's servers. Fallbacks do not bypass an
  explicit serverless selection.
- **Servers listed and marked `(demoted)`.** Every server's last failure
  was less than 30 seconds ago (§4.6). `upstream_failed` rising shows
  it. Questions are still sent to demoted servers, so service returns as
  soon as one answers.
- **The servers listed are link-local (`fe80::…`).** Check that the
  scope names the intended interface and that it still exists. resolvd
  sends through that interface for UDP and TCP (§4.7). Link-local servers
  belong in an interface profile, not the unscoped fallback list.

## 9.2.2 A single label is `notfound` at once

**Looks like:** `resolv query printer` exits 2 without delay, with
source `local`.

No search domain applies (§4.3). Check the `domain` lines in `status`.
An up scope's domains count even without servers; while an exclusive
scope takes every question (§4.4), only its domains apply and
`ExtraSearchDomains` is ignored.
A single label is never sent bare, so with no domain it is answered
locally.

## 9.2.3 Names meant for the VPN go elsewhere

An exclusive scope takes every question at `addressed` or better (§4.4),
even without servers. Without a server, uncached upstream work is unavailable
instead of using another interface. At `link` alone, the exclusive rule does
not apply. Check the interface state as well as its flags.

## 9.2.4 An answer is wrong or stale

Cached answers live up to a day (§4.5). They are discarded for a scope
when its server list changes, and for everything by
`resolv flush` (§5.3), which needs `RESOLVER_CONTROL`. A static name in
`Hosts\` overrides DNS at once, with no flush (§4.2).

To see what the network says now, use
`resolv query <name> --no-cache`. It skips the cache lookup, but the
answer it gets is still stored, replacing the cached one (§4.5).

## 9.2.5 Answers are slow

Each question shares three attempts across candidates and TCP retries,
allowing six seconds of timeout waiting (§4.6). Successful negative answers
can add further round trips while advancing through search domains.
A dead first server costs two seconds per question until it is demoted;
after that it is asked last, for 30 seconds, and the cycle repeats if
it is still dead.

A UDP reply that does not match its query — a server that does not echo
the question's case exactly, for instance — is ignored (§4.8). A later
matching reply can still answer the transaction. Only if none arrives by
the original two-second deadline does the attempt time out, demote the
server, and add to `upstream_failed` without adding to `upstream_answered`.

## 9.2.6 `refused` is rising

The counter includes transactions rejected at the 4,096-transaction ceiling
and failures to obtain randomness for a new transaction. Both return
`unavailable`; cached and synthetic answers do not allocate a transaction.
Check outstanding work and the host's random-source health before assuming
that the service is overloaded. The capacity used by completed transactions
is released; a new request can then proceed.

## 9.2.7 Getting back to a known state

A new resolvd discards the cache, the demotions and the counters,
re-reads the registry, and takes a fresh snapshot from netd; nothing is
persisted. `svctl restart resolvd` is enough: the new process replaces
the socket its predecessor left (§2.4).

The exception is the first start after an upgrade from a resolvd whose
DACL did not name its own account (§2.4). That older resolvd's directory
and socket shut the new one out, and it exits with `native socket:
Permission denied (os error 13)` until they are gone. Reboot to recreate the
runtime directory. If a reboot is not possible,
stop the service and have an administrator inspect and replace only its
stale runtime socket and directory before restarting it.

---

# 9.3 resolvd Cannot Be Reached

_Peios / Reference / resolvd / Failure Modes_

> What each door does when resolvd is not running, will not start, or refuses a caller — and the failures that leave one door working and another not.

## 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 for `tcp,udp:53` is not in the registry — its seed is
  inert until the image applies it (§2.1) — or something else already
  holds `127.0.0.53:53`. The error text says which.
- **`native socket: <error>`:** `/run/resolvd` could not be created or
  given its mode, a stale socket file could not be removed, or the
  socket could not be bound or set up.

Because the restart policy is Always, a failure that persists is a
restart loop: the same line in the log each time.

## 9.3.3 The native door is closed to ordinary programs

**Looks like:** `getaddrinfo` fails with `NO_RECOVERY` for every name
but `localhost`, for every user but SYSTEM and administrators, while
programs that send DNS to `127.0.0.53` themselves work.

Two causes:

- The socket's descriptor could not be written at startup (§2.4), and
  the log has the `could not set a descriptor` line. Ordinary programs
  cannot reach the socket at all.
- `ControlSecurity` holds a valid descriptor that does not grant
  `RESOLVER_QUERY` to them (§5.2). They reach the socket and are denied:
  `resolv query` prints `resolv: access denied`. Deleting the value
  restores the compiled default without a restart (§2.3).

The stub listener is not governed by either, which is why direct DNS
clients are unaffected.

---

# 9.4 Stalls and Loops

_Peios / Reference / resolvd / Failure Modes_

> The failures that come from resolvd's single thread and its channel to netd — a stalled reply reader, a refused subscription, a lost registry watch, and cache capacity pressure.

## 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_

> Every fixed value in resolvd, the NSS shim and resolv, with the article that describes it, and the paths and addresses they use.

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_

> Every registry key and value resolvd reads or its package seeds, with types, defaults and the article that describes each.

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_

> Packet integrity, encrypted credential exchange, and explicit network admission in the portable RADIUS core.

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

```mermaid
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](/peios/reference/radius/access-assignment.md).

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](/peios/reference/radius/accounting.md).

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

- [RADIUS](https://www.rfc-editor.org/rfc/rfc2865.html).
- [RADIUS support for EAP](https://www.rfc-editor.org/rfc/rfc3579.html).
- [EAP-TTLS](https://www.rfc-editor.org/rfc/rfc5281.html).
- [TLS-based EAP methods with TLS 1.3](https://www.rfc-editor.org/rfc/rfc9427.html).
- [Microsoft key attributes](https://www.rfc-editor.org/rfc/rfc2548.html).

---

# 2 Qualification

_Peios / Reference / RADIUS_

> Running the independent supplicant gate and understanding what its results establish.

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:

```sh
cargo build --workspace --locked
python3 tools/build-eapol-test.py --out target/test-tools/eapol_test
```

The tool builder requires a C compiler, Make, OpenSSL development files
and network access to the pinned upstream archive. It builds only the
test executable and removes its temporary source tree. An existing
qualified `eapol_test` can be supplied instead.

Run the required gate:

```sh
python3 tests/interop.py --server target/debug/radius-test-server --eapol-test target/test-tools/eapol_test
```

The runner fails if required tools are missing. Successful cases check
both EAP success and MPPE key agreement. It forces TLS 1.2 and TLS 1.3
separately, uses a large certificate chain and small fragments, checks
anonymous and differing outer names, and rejects wrong credentials,
denied admission, untrusted issuers and wrong server names. A loopback
relay duplicates requests and suppresses a reply. Direct packet checks
also verify reply authenticators and discard tampered requests.

The fixture listener rejects non-loopback addresses. Temporary test
credentials and certificates are removed on completion; captured
supplicant output is not printed because it can contain key material.
The fixture uses explicit test credentials and never contacts authd.

## 2.2 Component checks

```sh
pekit test --strict -j 2 unit integration management policy authorization accounting clippy doctests
pekit build --strict -j 2 test_server radiusd radius_cli radius
pekit test --strict -j 2 native native_management administration native_clippy native_management_clippy administration_clippy
```

These are raw component targets. They do not package files or build a
kernel or image. `radius_cli` builds terminal administration with native
support; `radius` also includes the GXWI window. The native targets supply
matching pinned SDK, authentication and desktop libraries. Cargo and Pekit
must select the same source revision for each imported component; do not
bypass a reported mismatch. Before dependency commits are published, local
qualification needs those exact commits in the build cache.

The host Cargo equivalents are documented in the repository README. Native
host tests do not replace guest qualification: tests marked as requiring a
disposable Peios guest remain ignored on the host. The Rust checks exercise
malformed and truncated packets, duplicate attributes, conversation quotas,
idle and overall deadlines,
binding changes, one-shot admission and rejection without key delivery.

The `authorization` target checks typed settings, independent standard and
vendor wire vectors, exact unit conversion, protected attributes, reset
requirements and complete reply bounds. Native coordinator and loopback CoA
checks cover complete assignments, cache integrity, quota gating, real UDP
requests and acknowledged baselines. These establish server behavior; actual
equipment needs separate shaping, filter, gateway, and management tests.

## 2.3 Native session controls

In a fresh, isolated guest, run `tests/native/setup.sh`, then
`tests/native/session-controls.sh` and `tests/native/automatic-controls.sh`.
Supply the compiled `native-session-controls` example, the native-policy test
binary, and the independent supplicant in `/mnt/dev/bin`, with the fixture
credentials under `/mnt/dev/credentials`. These scripts require
`PEIOS_DISPOSABLE_RADIUS_TEST=yes` and `RADIUS_DEV_RUNTIME=1`. They change
accounts, policy, service definitions, and the ledger; use no deployed state
or LAN interface.

The checks exercise actual caller tokens, separate action and fallback
permissions, protected credential metadata, password revision changes,
maintenance stability, exact-session CoA and Disconnect, forged replies,
durable request IDs, restart, rebuild, and real PEAP/TTLS authentication.
Automatic cases use direct Registry VLAN edits, account disablement, password
replacement with an explicit Disconnect fallback, and opt-in CoA updates.
The generic profile does not claim fresh reauthentication support.

`tests/native/richer-profiles.sh` checks saved setting types, equipment
mapping, Explain, exact 64-bit values, unsupported ranges, invalid direct
Registry edits, removal, restart, TLS 1.2/1.3 authentication, key agreement,
and actual-caller permission checks. Run it after `setup.sh` in an isolated
guest, or after the session-control scripts to include the accounting ledger.
It qualifies server behavior with a loopback supplicant; no fixture emulates
traffic shaping or gateway enforcement.

A migration fixture can seed accounts with a previously qualified format-6
lpsd before switching to the new runtime. Set
`RADIUS_QUALIFY_LEGACY_STORE=1` only for that arrangement. Fresh-store checks
do not exercise the old-store upgrade.

## 2.4 Component load and recovery

The developer-only qualification program measures bounded synthetic loads,
checks overload recovery, and injects storage failures in child processes.
See [Component Load and Recovery](/peios/reference/radius/component-load-and-recovery.md)
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](/peios/reference/radius/native-integration.md). 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_

> Service identity, Registry configuration, failure behavior, and disposable-guest qualification of radiusd.

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

```sh
pekit build --strict -j 2 radiusd radius_cli radius
```

`radius_cli` includes native terminal administration; `radius` includes the
same commands and the optional GXWI window. These raw component targets do
not invoke final PPK packaging in `pkgs/`.

The native Cargo feature links the matching public `libauth.so.1` and
`libpeios.so.0`. The Pekit target supplies those libraries and SDK
headers from pinned canonical source revisions. A development guest
must load these matching libraries rather than older image copies.

The daemon, command-line client and GXWI window use one Peios Rust bindings
0.5 dependency graph, aligned with the distribution's SDK and service pins.
Build these clients with their pinned dependencies and matching libraries.

Fresh state-directory provisioning requires a kernel with KACS control
handles: native opens that request no data rights. The administrator creates
each directory carrying its security descriptor. Older kernels reject this
open with `EINVAL`; provisioning does not fall back to creating an unprotected
directory and setting its descriptor afterward. Existing directories keep
their descriptors.

The current bindings require authd's PGSS version 6 protocol and libauth
ABI 6. The shared-library filename remains `libauth.so.1`, so successful
loader resolution alone does not establish compatibility; the bindings
check the ABI when creating a client. Upgrade the daemon, matching library,
peinit service-token client, and other authentication clients together.
An older GXWI server or SSH bridge cannot authenticate against the new
authd merely because radiusd has been rebuilt. RADIUS continues to request
only password or MSCHAPv2 verification; this update adds no NTLM method.

The service must be named `radiusd` and use `Identity=Service`. It
checks its actual token user SID at startup. Trusted authd policy gives
this account the `peios.auth.authenticate` capability. It receives no
`peios.auth.logon` capability and needs no token-creation or impersonation
privileges. `SeChangeNotifyPrivilege` permits ordinary path traversal;
`SeAuditPrivilege` permits operational event emission. The normal UDP
port-reservation descriptor grants its service SID PORT_BIND for each
configured listening port. Use peinit's Notify readiness mode.

The radius package provides these as Registry seeds, in `registry.d`:
`radiusd-service.reg` defines the service, `radiusd-policy.reg` grants its
account the capability and the two privileges, and `radiusd-port.reg`
reserves UDP ports 1812 and 1813 for it. The definition has no Triggers, so
installing the package starts nothing. `radius service boot on` adds a boot
trigger once the configuration is initialized.

Packet admission is separate from the port reservation. When packet filtering
is enabled, allow inbound UDP for each configured RADIUS listener. GXWI's
inbound TCP rule does not also admit RADIUS authentication traffic.

The default AuthenticationSecurity descriptor grants this service
ReadGroups and ReadClaim across the namespace. Authenticate remains a
separate capability grant. Administrators can use ordinary claim object
ACEs to restrict sensitive claims. An explicit AuthenticationSecurity
value replaces the default and is never silently broadened.

## 3.2 Configuration and admission

The component's `radiusd.regman` describes every value under
`Machine\Software\Radius`. Settings define literal UDP listeners and
bounded conversation resources. Clients define source-address prefixes,
protected secret-file references, and allowed access-policy GUIDs. Access
policies define exact SSIDs, Connect security descriptors, periodic
reauthentication, and an authentication-profile reference. Profiles select
ordered methods and a named server identity. Server identities reference an
ordered DER certificate chain and matching protected DER private key.
All records have stable GUID keys and independent display names. Schema
version 3 adds access profiles and nested assignment rules. Existing schema
2 deployments require the explicit migration described in Administration.

Most-specific source prefixes select the trusted client. There is no
fallback to another secret. The integrity-checked Called-Station-Id must
contain a valid MAC prefix and exact SSID; NAS identifiers and MAC
addresses do not establish user identity. Continuations retain their
original client, source, and network binding. A changed secret, source
trust definition, SSID, or listener set invalidates affected work.

Each profile's required `AuthenticationMethods` is an ordered allowed-method
list containing `ttls-pap`, `peap-mschapv2`, or both. All methods share the
access policy's Connect descriptor. Changing a method list invalidates
affected unfinished exchanges and cached replies. Enabling NT storage does
not change the configured methods.

An intentionally disabled client, policy, or profile denies affected
admissions without falling back to other clients or profiles. Otherwise
valid disabled records do not invalidate unrelated policy. These changes do
not disconnect established stations immediately. Missing references remain
invalid even on disabled records.

One nonblocking authd operation belongs to each credential attempt. PAP
uses one typed Password prompt and requires confirmed Password verification.
PEAP requests MSCHAPv2, relays one source-issued challenge and typed
response, and requires confirmed MSCHAPv2 verification with the protocol's
server proof. radiusd receives no reusable NT hash. Unsupported or repeated
prompts, unavailable sources, and incomplete verification cannot grant access.
A configurable concurrency limit rejects excess verification work without
an unbounded queue. NT storage and opportunistic password-side backfilling
are documented with the local principal source, not configured by radiusd.

Admission uses the verified SID, source groups, permitted typed claims,
and explicit claim coverage. It does not reconstruct identity from a
later username lookup or invent local-session group memberships.
For example, grant Connect to a source's household group SID. An
Everyone ACE matches only when that membership is supplied; the adapter
does not add it. Hidden claims remain unknown. Missing context, device,
or local execution requirements deny admission. The stateless kernel query
conveys no token authority. An older kernel fails admission with
`kernel-api-unavailable`; other query errors use `access-check-error`,
independently of wrong credentials and an ordinary policy denial. There is no
userspace evaluator fallback.

Each check supplies the stable Registry network ID and SSID display label in
an `AuditContext` of kind `network`. Invalid UTF-8 in the label is replaced
with U+FFFD; policy binding still uses the original SSID bytes. The fields are
defined as asserted values in radiusd's event catalog fragment. Matching SACL
audit ACEs produce `kacs.audit.subject.checked`
when radiusd holds enabled `SeAuditPrivilege`. The event identifies radiusd's
real caller identity separately from the supplied, hypothetical user SID.
Audit preparation errors fail admission. radiusd's own admission events remain
separate and describe the real service decision.

Current policy is checked immediately before success and key delivery.
Access-Accept carries signed Session-Timeout and Termination-Action
attributes. The default requests reauthentication after one hour.
It does not immediately disconnect existing Wi-Fi stations, and AP
enforcement must be qualified separately.

## 3.3 Reload and reporting

A bounded worker handles blocking Registry and protected-file reads.
The packet loop continues processing bounded handshakes and expiry.
Observed pending, invalid, unreadable, or unwatched configuration pauses
new admissions and cached success replies. Pending verification results
can wait only within their original deadlines. Recovery validates the
assembled configuration before resuming. Certificate replacement cancels
affected unfinished exchanges and cached replies. Cosmetic name changes
preserve authentication bindings.

Notify readiness means the local status endpoint is ready. An invalid
initial configuration leaves that endpoint available for diagnosis and
repair while authentication is paused. It does not imply active listeners.
The administration program shows saved and effective configuration
separately; it also distinguishes a stopped service from an unreachable or
unauthorized status endpoint. See
[Administration](/peios/reference/radius/administration.md).

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.

```sh
export PEIOS_DISPOSABLE_RADIUS_TEST=yes
bash /mnt/dev/native/setup.sh
bash /mnt/dev/native/qualify.sh
bash /mnt/dev/native/mschapv2.sh
bash /mnt/dev/native/administration.sh
bash /mnt/dev/native/initialize.sh
bash /mnt/dev/native/assignment.sh
bash /mnt/dev/native/migrate-policy.sh
```

The independent supplicant runs inside the guest against loopback UDP.
The native service identity, Registry, authd/lpsd verification, supplied
subject admission, and key export are real. Wi-Fi equipment and its
radio link are simulated. The scripts check both TLS versions, matching
MPPE keys, account and policy denials, restricted-claim uncertainty,
invalid-configuration recovery, secret rotation, and source failure.
They capture supplicant output privately because it can contain keys.
The MSCHAPv2 sequence also checks method negotiation, both NT controls,
opportunistic backfilling, password changes, and password eligibility.
Administration qualification additionally requires `bin/radius`, matching
`libgxwi.so.1`, and the native-authority example in the development share.
It checks shared profiles, references, renames, disabled isolation, invalid
startup recovery, credential staging, stopped-daemon edits, and real-token
status, Registry, and secret-file authorization. Certificate import checks
also need the corresponding PEM chain and private key in the fixture share.
The initialization script temporarily replaces and restores the disposable
fixture's Registry subtree and credential directory. It verifies fresh setup,
existing-configuration refusal, and enabled-administrator writes without
granting the test token extra privileges.
Set `RADIUS_DEV_RUNTIME=1` when using the replaceable raw-binary layout
at `/lcl/radius-dev/current` rather than copying binaries into `/lcl`.

The optional `native-events` Cargo example reads the two fixture CPU
rings as the guest administrator. Start it before `qualify.sh`, wait
for `/run/radiusd/events.ready`, and create
`/run/radiusd/qualification.done` afterward. Its zero exit status and
PASS marker verify typed, cataloged payload fields and absence of
unexpected credential or claim fields. It is a qualification tool,
not part of the daemon or a required service privilege.

Portable coordinator tests separately cover concurrent verification
bounds, exact replay, policy changes, preserved deadlines, binding
invalidation, and cancellation. Native SDK tests cover typed claims,
known absence, and missing device or audit context.

## 3.5 Diagnostic reader qualification

Stage eventd and evctl in the replaceable runtime, plus the
`native-diagnostics` Cargo example in the share's `bin` directory. In a fresh
disposable guest, `tests/native/diagnostics.sh` provisions the fixture and
checks actual attempt history, exact authd operation links, caller identity,
delegated event reads, and denial of personal fields. It also checks that
authentication continues through an eventd outage and tight emission bounds.

The script defaults to eventd's Service identity. The explicit override
`RADIUS_DIAGNOSTICS_EVENTD_IDENTITY=SYSTEM` isolates query checks when normal
service ingestion is unavailable. A pass with that override does not qualify
the Service deployment. The fixture must not be applied to a deployed machine.

The CLI and GXWI require a working, separately provisioned eventd deployment
for diagnostic history. RADIUS authentication remains independent of it.

Passing these checks is development evidence, not a production release
or a complete security audit. Real UniFi/iPhone TTLS/PAP connectivity and
a profile-free iPhone join through PEAP have succeeded in development
trials. Roaming and AP reauthentication enforcement need their own
qualification. The supplied-subject evaluator runs in the kernel;
the loader uses the public Registry read-snapshot API before further feature
expansion.

---

# 4 Persistent Development VM

_Peios / Reference / RADIUS_

> Persistent machine state and replaceable raw binaries for offline RADIUS development.

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:

```sh
python3 radius/tools/dev-vm/vm.py --vm local/radius-dev-vm \
    prepare local/isos/console.iso
python3 radius/tools/dev-vm/vm.py --vm local/radius-dev-vm create-state
```

Disk creation exclusively creates a 512 MiB sparse file and refuses an
existing file. Boot preparation also refuses existing boot assets.

Build raw targets directly in their component repositories. Assemble the
reported outputs into a directory with these entries:

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

```sh
python3 radius/tools/dev-vm/vm.py --vm local/radius-dev-vm \
    stage initial local/radius-runtime
python3 radius/tools/dev-vm/vm.py --vm local/radius-dev-vm \
    run initial --initialize
```

Use `run initial` without `--initialize` on subsequent boots. Successful
startup reports that persistent state is mounted, followed by peinit's
ordinary boot messages and the console shell.

## 4.3 Updating development binaries

Stage every update under a different set name. Staging copies every required
files before publishing the set and does not alter the running VM.
Existing set names cannot be overwritten.

For a configured development VM, activate a staged set from its console:

```sh
bash /mnt/dev/activate.sh update-name
```

Activation copies and verifies the set before stopping services. It stops
radiusd if active, then lpsd and authd, and netd if active. It switches the
selected set, restarts netd if needed, starts lpsd and its authd dependency,
and restarts radiusd if it was active. A set that omits network binaries
cannot replace a running netd.
Service definitions must use `/lcl/radius-dev/current/bin` and explicitly
select `/lcl/radius-dev/current/lib` for library loading. Running PID 1
changes only on the next boot. Select the desired set in the next host
`run` command; runtime activation does not change the host boot selection.

A missing or damaged staged set leaves running services untouched. A
failure after services stop remains visible and requires correction or
activation of the previous set; activation promises no automatic rollback.
Old sets remain available until deliberately removed while the VM is off.

## 4.4 Qualifying the desktop

Successful sign-in and a desktop document do not establish that the shell
and management window work. With RADIUS open on Overview, run this additional
check from the host:

```sh
python3 radius/tools/dev-vm/check-desktop.py https://10.10.0.111:7780 \
    --certificate-sha256 "$GXWI_CERT_SHA256" \
    --administrator-file local/radius-administrator.json \
    --unprivileged-file local/radius-user.json
```

Supply the actual development VM address and its certificate's SHA-256
fingerprint, obtained from its console. Each private JSON file contains
`username` and `password` fields. Keep these files outside the repository and
restrict their permissions. The check pins the server certificate before
sending credentials; it never prints passwords, session cookies, or app-origin
secrets.

The check signs in as both accounts and uses the desktop's HTTP and WebSocket
protocols to verify a shell-owned taskbar panel, launcher overlay and declared
RADIUS window. It reads the app's rendered Overview: the administrator must
see Running and active saved configuration, while the non-administrator must
be denied configuration and status access. Both accounts need permission to
sign in through GXWI. This does not change configuration or group membership.
It can start or rejoin those users' desktop sessions; close them through the
ordinary desktop controls after qualification.

This protocol check does not verify browser layout, input or accessibility.
Inspect those separately in a browser. It also does not replace independent
supplicant tests or the real AP assignment and reauthentication trial.

Shut down through the matching control tool:

```sh
LD_LIBRARY_PATH=/lcl/radius-dev/current/lib \
    /lcl/radius-dev/current/bin/svctl shutdown poweroff
```

## 4.5 LAN attachment

LAN mode requires a separately configured persistent Ethernet bridge on
the host, NetworkManager, and permission to control network connections.
The launcher never moves the host's physical Ethernet configuration.
Preparing or changing the bridge is a separate administrative action;
preserve the host's addressing identity and prepare a rollback before
activating that change.

Save a stable virtual MAC address and the bridge/TAP names once:

```sh
python3 radius/tools/dev-vm/vm.py --vm local/radius-dev-vm \
    configure-lan --bridge br-peios
```

This command writes `network.json` beside the state image. It refuses an
existing file, so ordinary setup cannot replace the virtual MAC. The
configuration belongs to this VM and should accompany its state disk.

Configure the guest's `radius-dev-lan` netd profile and a matching
interface rule through the ordinary network registry settings. Static
addressing requires the address/prefix, gateway, and DNS settings; it
does not require a DHCP reservation. Do not copy addresses from another
network into this profile.

Stage a complete runtime set containing the network programs and library.
Boot it offline first to provision the service:

```sh
python3 radius/tools/dev-vm/vm.py --vm local/radius-dev-vm run lan-initial
```

In the guest, apply the prepared profile and rule, then run:

```sh
bash /mnt/dev/provision-network.sh
```

The provisioning helper creates the persistent netd state directory if
absent and configures the ordinary SYSTEM netd service using the raw
executable. It preserves existing network profiles and rules. An existing
netd definition retains its unrelated settings. The service starts at
boot and publishes network readiness through its normal control APIs.

For a VM prepared by an earlier helper version, copy the updated
`activate.sh` and `provision-network.sh` into its host `share` directory
before provisioning. No initramfs or kernel rebuild is required.

After a clean shutdown, boot with the LAN attachment:

```sh
python3 radius/tools/dev-vm/vm.py --vm local/radius-dev-vm \
    run lan-initial --lan
```

The launcher creates a temporary NetworkManager TAP profile owned by the
invoking user and connects it to the configured bridge. QEMU uses that
TAP and the saved virtual MAC. Existing TAP names are rejected. Shutdown
or a failed QEMU launch removes the temporary profile and device while
leaving the host bridge in place. The profile is not saved to disk.

Check `net status` in the guest for the matched profile, saved address,
gateway, and routed readiness. Check reachability from another LAN
machine. Routed readiness reports configured state; it does not prove
that the gateway or a remote service answers. The host must remain
connected after the VM shuts down and its TAP disappears.

LAN attachment does not expand radiusd's trusted-client configuration or
replace the offline fixture's deny-all network policy. Real AP clients,
certificates, and network admission require separate provisioning.

## 4.6 Offline qualification fixture

`tests/dev-vm/prepare.py` prepares inputs from authd's standard policy
seeds and the existing protocol-test certificate helper. Run it only for
a fresh offline VM. The guest fixture refuses an existing account store
or authentication policy and creates a development account, group,
registry marker, and loopback-only radiusd configuration. It supplies
fixed test credentials and a Connect descriptor that denies all access.
It is not real-network provisioning.

```sh
python3 radius/tests/dev-vm/prepare.py \
    --vm local/radius-dev-vm --authd authd
```

In the freshly initialized guest:

```sh
PEIOS_OFFLINE_VM_PROOF=yes bash /mnt/dev/proof-setup.sh
PEIOS_OFFLINE_VM_PROOF=yes bash /mnt/dev/proof-check.sh save
```

After binary activation and again after a clean shutdown and normal boot:

```sh
PEIOS_OFFLINE_VM_PROOF=yes bash /mnt/dev/proof-check.sh check
```

The check requires all three services active and compares the machine ID,
account domain and security identifiers, groups, configuration, policy,
and hashes of the account store and protected credentials. Its PASS
marker establishes offline persistence and activation, not a real Wi-Fi
connection. Certificate onboarding, a LAN address, UniFi integration,
and production credentials require separate provisioning and qualification.

---

# 5 Administration

_Peios / Reference / RADIUS_

> Manage RADIUS clients, policies, methods, certificates, and local service state through the CLI or GXWI.

The `radius` program provides terminal administration and a GXWI window:

```sh
radius --window
```

Both interfaces use the same management library and the caller's actual
permissions. Configuration is stored directly in the local Registry, so
editing works while radiusd is stopped. The daemon's local status endpoint is
read-only. There is no remote management listener. Use an SSH session for a
remote CLI; a GXWI desktop can present the window remotely.

## 5.1 Configuration objects

The window groups authentication, assignment, and accounting administration
into separate sections. Overview reports service and configuration activation
state.

Overview's listener field starts with the saved addresses. Background
refreshes follow external changes while the field is unchanged, preserving an
edit in progress. The saved value shown below the field remains separate from
the draft.

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

```sh
radius status
radius client list
radius policy list
radius profile list
radius identity list
radius access-profile list
radius rule list
radius dynamic-profile list
radius config check
```

`radius --help` lists commands. `--json` produces structured output, including
GUIDs and typed errors. Exit status is 0 for success, 64 for invalid
arguments, 3 for denied permission, 4 for a missing object, 5 for invalid
configuration, and 1 for other failures. Explicit secret output is raw bytes
and does not accept `--json`.

See [Access Assignment](/peios/reference/radius/access-assignment.md) 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](/peios/reference/radius/session-controls.md) 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](/peios/reference/radius/native-integration.md). 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:

```sh
radius identity create Main \
    --set CertificateFiles=/path/server.pem,/path/intermediate.pem \
    --set PrivateKeyFile=/path/server.key
radius profile create Passwords \
    --set AuthenticationMethods=peap-mschapv2,ttls-pap \
    --set ServerIdentity=IDENTITY-GUID
radius policy create Household --set SSID=Home \
    --set AuthenticationProfile=PROFILE-GUID \
    --set 'ConnectSecurity=O:SYG:SYD:(A;;0x1;;;HOUSEHOLD-GROUP-SID)'
radius client create AccessPoints --set Addresses=10.10.0.0/16 \
    --set Policies=POLICY-GUID
```

Replace the placeholder GUIDs and group SID with actual values. Source
addresses must be canonical literal addresses or prefixes. The first
authentication method is preferred. Credential rejection does not cause
fallback to another method. PEAP/MSCHAPv2 requires matching authd credential
support; enabling it in a profile does not change authd's password policy.

The client receives a generated 48-character shared secret. Explicitly reveal
it and configure the same value on the corresponding RADIUS client:

```sh
radius client secret AccessPoints show
```

The window similarly requires an explicit reveal. Normal lists, records,
status, and errors contain no secret contents. Reveal still requires read
permission on the protected file. Supply your own secret using an echo-free
prompt, standard input, or a file; avoid placing secrets in process arguments:

```sh
radius client secret AccessPoints set
radius client secret AccessPoints set --file /protected/shared-secret
radius client secret AccessPoints generate
```

A generated replacement also needs updating on the corresponding client. The
policy's reauthentication interval defaults to 3600 seconds.

## 5.3 Permissions and credentials

Connect permissions decide whether an authenticated subject can use a policy.
Management permissions are the ordinary Registry key descriptor controlling
who can edit it. The window opens the existing security descriptor editor for
each, under separate controls. The CLI exposes their descriptors without a
separate permission language:

```sh
radius policy permissions Household connect
radius policy permissions Household management
```

Add an SDDL argument to set a descriptor. Configuration-write rights,
credential-file read rights, service-control rights, and local-status query
rights remain independent. The default status descriptor permits SYSTEM and
Administrators. An explicit `Settings\StatusSecurity` can change that policy;
malformed or unreadable explicit values deny queries. The endpoint checks the
kernel-attested peer token, including deny-only groups.

Certificate import accepts PEM or DER and verifies that the key matches the
leaf certificate. The window shows certificate subject, issuer, DNS names,
validity dates, and fingerprint. Import paths refer to files on the Peios
machine, including when the window is presented remotely. The program does not
issue certificates or replace a CA. Replacing an identity preserves its GUID
and dependent profile references:

```sh
radius identity inspect Main
radius identity import Main --set CertificateFiles=/path/new-chain.pem \
    --set PrivateKeyFile=/path/new-key.pem
```

Shared secrets and keys are staged as new protected files before Registry
references switch in a transaction. Failed saves remove their new files.
Successful replacement retains old files until they can safely be removed;
deleting a record does not erase credential files automatically.

## 5.4 Saving, activation, and recovery

Saving updates stored configuration. It does not claim the daemon activated
it. Overview shows saved and effective fingerprints and activation issues. The
daemon independently validates direct Registry edits. A broken reference, bad
descriptor, or unreadable credential pauses admissions until repaired; the old
policy is not silently kept active. The local status endpoint remains
available even when initial configuration is invalid.

The tools preserve malformed records for inspection and repair. Direct
Registry editing can bypass deletion safeguards. Related management writes are
transactional; there is no stale-form conflict detection.

Disabled clients, policies, and profiles deny affected admissions while
unrelated valid policy continues. A disabled shared profile affects every
policy using it; the window shows those dependents before confirmation.
Established stations are not immediately disconnected by these edits.

Service controls are separate from object state:

```sh
radius service stop
radius service start
radius service restart
radius service boot on
radius service boot off
```

Commands report submission; check status for completion. Boot preference does
not start or stop the current process. Stop and restart interrupt ongoing
authentication; existing network access can continue until reauthentication.
Routine edits reload without a service restart. No command requires a kernel
rebuild.

---

# 6 Accounting

_Peios / Reference / RADIUS_

> Durable network session reports, protected history, principal allowances, and Disconnect outcomes.

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](/peios/reference/radius/native-integration.md).
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_

> Select a complete network access profile using PNP-style rules, typed identity facts, and explicit defaults.

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](/peios/reference/radius/access-profile-settings.md).
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.

```sh
radius access-profile create Staff --set VlanId=20
radius access-profile create Default
radius rule create Default --set Policy=POLICY-GUID \
    --set 'Actions=ASSIGN(DEFAULT-PROFILE-GUID)'
radius rule create Staff --set Policy=POLICY-GUID --set Parent=DEFAULT-RULE-GUID \
    --set Subject.Group.Equal=S-1-5-32-545 \
    --set 'Actions=ASSIGN(STAFF-PROFILE-GUID)'
```

Replace the GUID placeholders with identities returned by the creation
commands. A nested `Parent` uses slash-separated ancestor GUIDs. `Policy` and
`Parent` are derived management fields; direct Registry edits do not store
them as rule values. A rule's location remains fixed after creation.

Remove a VLAN override with `radius access-profile unset PROFILE-GUID VlanId`.
Use `radius rule unset RULE-GUID CONDITION-KEY` to remove a condition, or
`radius rule unset RULE-GUID Priority` to restore inherited priority. Deleting
an object with references is refused.

GXWI provides Access Profiles, Assignment Rules, and Explain Policy sections.
The rule editor exposes actions, profiles, conditions, and parent selection.
Shared-profile references appear in the affected-object information.

## 7.2 Rule evaluation

The evaluator shares PNP's tree traversal, ancestor fallback and collation.
Conditions on a rule are ANDed. Alternatives inside one condition are ORed.
Disabled rules hide their subtree. A matching child shadows its parent only
within that tree; independent trees still contribute candidates.

`Priority` is a signed decimal string or a DWORD. It inherits from the parent,
or defaults to zero at a root. `Actions` accepts a string or string list:

- `ASSIGN(profile-guid)` selects a complete profile.
- `REJECT` refuses admission.
- `NULL` abstains. The nearest ancestor with a direct decision speaks for
  that region, using the ancestor's priority.

The highest-priority candidate wins. At equal priority, `REJECT` wins over
assignment. Equal-priority assignments to the same profile agree. Different
profiles tied at the winning priority cause a per-connection refusal, with
both rule paths reported in operational diagnostics. Rule order has no effect
on permission. A single rule cannot select multiple different profiles.

## 7.3 Facts and types

| 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](/peios/reference/radius/session-controls.md) 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](https://www.rfc-editor.org/rfc/rfc2131.html#section-3.7)
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](https://www.rfc-editor.org/rfc/rfc3580.html#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:

```json
{
  "values": {
    "Subject.Group": [{"type": "sid", "value": "S-1-5-32-545"}],
    "Subject.Claim.Department": [{"type": "string", "value": "Engineering"}]
  },
  "claim_coverage": "filtered",
  "absent_claims": []
}
```

```sh
radius --json policy explain POLICY-GUID --facts /path/to/facts.json
```

`claim_coverage` defaults to `filtered`. Set `complete` only when the
hypothetical input intentionally asserts a complete claim set. `absent_claims`
supplies known absences separately. GXWI exposes the same knowledge
distinction.

The result identifies saved configuration and its fingerprint. It does not
claim that the daemon activated that configuration. Simulation does not verify
credentials, run Connect checks, reserve allowances, grant access, or contact
an AP.

Supplying a single `Client.Id` fact compiles the selected settings with that
client's saved equipment mapping. The returned authorization plan separates
encoded settings from missing mappings and missing client context. Successful
encoding does not establish that a device supports or enforces the attributes.

## 7.6 Bounds and development migration

The Registry loader accepts at most 1024 rules, 32 nested exception levels, 64
conditions per rule, 256 alternatives per condition and 4 MiB of rule values.
Profile count is bounded at 256. Hypothetical input has equivalent fact
bounds; the CLI file limit is 1 MiB.

Schema 3 requires explicit assignment rules. For a stopped schema 2
development deployment without assignment objects, the `migrate-policy-v3`
example prepares one default profile and a catch-all rule for each
authenticating policy. Running without arguments prints the candidate.
`--apply` creates the defaults and changes the schema in one Registry
transaction. It preserves credentials, existing records, and descriptors;
created keys inherit normal permissions. Do not edit RADIUS configuration
concurrently with this one-off migration. Keep the prior configuration and
runtime available for rollback.

---

# 8 Authentication Diagnostics

_Peios / Reference / RADIUS_

> Protected attempt timelines, exact authority links, dropped-request reports, and incomplete evidence.

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

```sh
radius diagnostics list --since 900 --username alice
radius diagnostics follow --since 300 --station aa:bb:cc:dd:ee:ff
radius diagnostics show ATTEMPT-ID --since 86400
radius diagnostics drops --since 300
radius diagnostics status
```

`--network` selects an access-policy GUID. `--client` selects a client
configuration GUID. `--username` matches the supplied inner username exactly;
it does not establish identity. Station identifiers are normalized reported
MAC addresses. The outer EAP identity is not recorded.

Personal and configuration filters operate on reconstructed, readable attempts
in the returned record window. This keeps anonymous TLS stages alongside a
later supplied username. A limited record window can omit other matches.
Use a narrower time window or adjust the configured bounds when necessary.

Finite `--json` commands return structured results. The command
`diagnostics follow --json` writes one JSON object per line: `kind=status` for
reader state, or `kind=event` with an authorized record. Stop following with
Ctrl+C.

In GXWI, select Diagnostics, enter filters, and select Follow Live or Refresh
History. Details retain the selected attempt during live updates. A selected
attempt outside the returned readable window remains selected but unavailable.

## 8.3 Authority and configuration links

An authority supporting the optional PGSS operation GUID supplies an exact
link to `authd.authentication.attempted`. `show` and Read Linked Events query
that GUID and the RADIUS service caller SID. eventd independently authorizes
the authority records. Empty results do not establish that no authority event
exists. An older authority can authenticate without supplying the identifier.

Correlation is not attestation or authorization. Event type names alone do
not prove an emitter's identity. Retain readable kernel event headers when
reviewing evidence. Principal-source events are not joined by guessing from
names or timestamps.

An attempt records the effective authentication fingerprint, relevant
configuration identifiers and observed decisions. Labels and diagnostic
controls do not alter that authentication fingerprint. The saved configuration
fingerprint is separate. Historical decisions are not recomputed against
edited policy. The hypothetical Explain Policy operation remains separate.

Recorded labels remain historical. Open Current Object opens today's readable
configuration, which can differ or be unavailable after deletion or a
permission change. Current configuration never fills a field missing from the
timeline.

## 8.4 Permissions and privacy

eventd's record and field security descriptors govern both history and live
streams. RADIUS management rights do not automatically grant diagnostic read
rights. The reader does not elevate or query as radiusd. Configuration-read
permission is not required to use independently delegated event access.

Live readers run in the caller's own process. An impersonating host can use
finite history queries on its calling thread, but cannot start a live worker
that would inherit a different process identity. Reader startup checks this
boundary without requiring token-duplication or impersonation rights.

Records can include packet source addresses, AP-reported station identifiers,
supplied usernames, and verified identities. Supplied usernames remain
unverified even when an attempt succeeds. Verified names and security
identifiers come from the authentication result. The normal timeline does not
copy the full groups-and-claims snapshot.

Passwords, authentication proofs, shared secrets, private keys, and decrypted
authentication payloads are excluded. Unknown diagnostic fields are refused
by the emitter's schema guard. This interface provides no packet dump.

A field absent from eventd's response is unavailable. The reader cannot tell
whether it was never recorded or withheld. It does not recover missing fields
through configuration or a more privileged query.

## 8.5 Loss, bounds, and retention

A missing terminal event leaves the outcome unavailable. Late evidence can
complete a timeline. Disconnected streams show their state immediately,
reconnect with overlapping history, and deduplicate records. Reader renewal,
limited backfill, collection loss, and missing stage sequences can leave gaps.
Old results retained during a failed reconnect are marked disconnected.

Finite queries publish no result if eventd fails before confirming completion.
An empty successful query means no matching readable records were returned.
It does not prove that no connection was attempted.

Requests discarded before conversation allocation have separate aggregate
reports, with bounded recent samples. Client matching is not proof of request
integrity. An integrity failure does not prove a wrong shared secret.

Registry values beginning with `Diagnostics` under
`Machine\Software\Radius\Settings` control emission and reader bounds. Consult
`radiusd.regman` for defaults and valid ranges. Client bounds limit retained
records and payload bytes; decoded frames and collection structures require
additional memory. eventd applies its own query resource limits independently.

Emission reserves capacity for final summaries, without guaranteeing delivery
under overload. Collection reports expose emission failures, local rate
suppression, and records omitted by emission policy. These reports are also
best effort. Missing reports leave collection state unconfirmed.

eventd controls persistent retention and field permissions. RADIUS does not
maintain an independent retention database or replay deleted evidence.

---

# 9 Session Controls

_Peios / Reference / RADIUS_

> Reevaluate established access and send precise, durable Disconnect and CoA requests.

RADIUS session controls operate on the accounting ledger's exact connection
occurrences. They use [RFC 5176](https://www.rfc-editor.org/rfc/rfc5176.html)
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:

```sh
radius accounting disconnect SESSION-GUID
radius accounting reauthenticate SESSION-GUID
radius accounting update SESSION-GUID
radius accounting reconciliation SESSION-GUID
radius accounting commands SESSION-GUID
```

These commands retain the original occurrence, NAS selectors, device source,
action, actor and configuration revision before sending. An AP-reported
username never establishes identity or selects another connection. Sessions
without precise NAS and session selectors cannot be controlled. Missing
verified identity also prevents automatic controls; manual Disconnect can
still terminate a precisely identified occurrence.

CLI and GXWI generate a request GUID. Automation can supply `--request-id ID`
and reuse it after a lost reply. The actor/request pair retains one command,
including terminal results; it cannot select another session or action. A
different deliberate action needs a new ID. Inspect command history before
repeating an operation whose reply was lost. Request IDs are not capabilities.

## 9.1 Device capabilities

A client can reference a reusable `DynamicAuthorizationProfile` GUID. Its
record lives under `DynamicAuthorizationProfiles` and contains `Name`,
`Enabled` and a JSON `Definition`. CLI uses the `dynamic-profile` object;
GXWI calls these Session Control Profiles. A missing reference uses the
generic RFC 5176 profile.

The same definition's `authorization` member supplies admission mappings,
qualified live settings and explicit reset attributes for richer profiles.
See [Access Profile Settings](/peios/reference/radius/access-profile-settings.md).
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](https://datatracker.ietf.org/doc/html/rfc5176#section-6.3).

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:

```json
{
  "version": 1,
  "name": "Disconnect without Proxy-State",
  "proxy_state_nonce": false,
  "station_selector": true,
  "require_station": true,
  "recipes": [
    {"action": "disconnect", "fresh_proof": false, "attributes": []}
  ]
}
```

On the development UniFi AP, the generic request received an authenticated
NAK with Error-Cause 401. Omitting only Proxy-State produced an authenticated
ACK, an accounting Stop and a new session with fresh password proof. This
also worked automatically when changing the assignment to VLAN 20 and back
to no override. This qualifies Disconnect on that tested device; it does not
establish CoA update, other firmware behavior or a DHCP address change.

In the observed iPhone trial, the address eventually changed to the VLAN 20
subnet after Disconnect and fresh authentication. On the return to no
override, the phone still displayed its old address after five minutes.
Explicitly assigning the main VLAN also failed to produce a new address and
connectivity was lost. Manually toggling Wi-Fi restored an address on the
main subnet. Automatic DHCP renewal on VLAN changes is therefore not qualified
by this test. A successful Disconnect and new password proof do not establish
that the client has usable IP configuration. AP forwarding and client DHCP
behavior were not captured, so the precise cause remains unverified.

## 9.2 Automatic behavior

With accounting enabled, automatic session controls default on. The defaults
disconnect a session after its effective VLAN assignment changes or current
access is revoked, and request fresh authentication after password
replacement.
Automatic CoA authorization updates have a separate switch, default off.
Disabling VLAN-change Disconnect therefore does not implicitly select CoA.

Each access policy can override the defaults through `SessionControl` JSON.
Omitted members inherit their global values. GXWI exposes the overrides as
ordinary selectors under Access Policies:

```json
{
  "vlan_disconnect": true,
  "revoke_access": true,
  "password_reauthenticate": true,
  "update_authorization": false,
  "unavailable_grace_seconds": null,
  "fallback": []
}
```

`null` outage grace keeps existing connections and retries. A positive grace
can disconnect when current identity evaluation remains unavailable. The
timer persists across daemon restart and accounting rebuild. This requires
an active, valid control configuration; invalid or pending configuration
pauses controls as well as new successful admissions.

Reconciliation uses the original verified SID with current account status,
permitted claims, groups, Connect permissions, and assignment rules. It never
turns missing or withheld information into a grant or confirmed deletion.
Available, authorized lpsd change events are hints; periodic fresh reads cover
missed events, other sources, and restarts. Rapid hints coalesce without
continually restarting an unfinished inventory scan. Rules and shared-profile
effects use the same activation path as direct Registry edits. Renames and
unchanged effective decisions do not create session-control requests.

Only successfully activated configuration can authorize a command. A bounded
worker rechecks queued intent and retries against fresh identity state, away
from the UDP loop. Changed policy can supersede unsent commands. A transmitted
command whose relevance is lost remains uncertain: it might already have
acted.
An old occurrence's command is never redirected to a new roaming occurrence.

## 9.3 Evidence and outcomes

The ledger keeps issued authorization, desired current authorization, and
device-reported observations separate. A recorded no-VLAN-override is an
explicit issued decision. No baseline means unknown, including sessions from
older ledger versions. Missing NAS observations do not imply an applied VLAN.

Successful authentication also binds an opaque credential reference and
revision. Password, MSCHAPv2, and NTLMv2 share the local password revision.
Replacement rotates it; NT-hash backfill and storage maintenance do not.
Current lookup can detect change or ineligibility, but only successful fresh
authentication can advance the revision proved by a session. RADIUS receives
no stored password hash or private key through this metadata.

The command history distinguishes pending, sent, acknowledged, rejected,
unsupported, uncertain, and superseded outcomes. Retries retain the exact
packet across restart. Only an explicit unsupported capability permits a
configured fallback; timeout, permission refusal, missing selectors, and a
missing session do not. The default fallback reports failure. Allowed fallback
order is update, then fresh reauthentication, then Disconnect; configure only
the steps desired.

An ACK records NAS acceptance. It does not establish fresh proof, a Stop
report, reconnection, DHCP renewal, or working applications. A phone can
retain an old lease after a VLAN change. Qualify reconnection and address
renewal separately on each AP/client combination.

## 9.4 Configuration and permissions

Global controls are under `Machine\Software\Radius\Settings`. Individual
DWORDs override the corresponding `DynamicAuthorizationSettings` JSON member.
Unknown JSON members and out-of-range values prevent activation. GXWI exposes
the same controls; CLI uses `radius config set NAME=VALUE`.

The `radiusd.regman` reference owns each value's type, default, and bounds.
Controls include the scan interval and batch/work limits, identity-read
timeout, retry count and delay, command lifetime, maximum concurrent requests,
response-integrity requirements, and each automatic trigger. One identity
read can complete after the scan's work budget; its own timeout still bounds
that read.

`DynamicAuthorizationFallback` is REG_MULTI_SZ, empty by default. It accepts
`reauthenticate`, `disconnect`, or both in that order. For example, an
explicit
`disconnect` fallback lets an unsupported fresh-authentication request fall
back to terminating that occurrence. It does not bypass permissions.

Accounting SD rights add Reauthenticate (`0x40`) and Update Authorization
(`0x80`) alongside Disconnect (`0x8`). Read and Personal remain independent.
Manual requests need Read and the action right, plus every configured fallback
right, under the actual caller's token. Authorization is captured when the
durable request is submitted. Automatic requests identify radiusd as their
origin and are limited to enabled policy enforcement. Existing custom
descriptors retain their existing grants; review them before delegating new
actions. Packet bytes and shared-secret fingerprints are not returned by the
management interface.

## 9.5 Upgrade and rollback

Ledger schema 2 adds control state while preserving usage, observations,
corrections, and command history. Older sessions keep unknown baselines until
fresh authentication. Rebuild preserves outage timers and command history and
does not resend commands as a side effect. Stable reevaluations do not fsync a
heartbeat on every scan. Schema 3 adds the durable wire allocator described
above, preserving that control state.

Schema 4 retains complete logical authorization, per-setting encodings, timer
caps and command baselines. It accepts schema 1–3 records without inventing
missing legacy attributes. An acknowledged update becomes the comparison
baseline for subsequent changes, including a return to the originally issued
profile. Quota countdowns do not change the configured policy identity.

The matching lpsd uses store format 7 and persists credential bindings before
exposing an upgraded store. Preserve offline copies of both stores, their
security metadata, the prior configuration, and the prior runtime before a
live upgrade. Older binaries cannot read these newer formats. An older
development Registry can also need the `DynamicAuthorizationProfiles`
collection provisioned with the existing parent's permissions; fresh
`radius config init` creates it.

Host regression checks do not qualify an AP's fresh-authentication behavior,
VLAN reset conventions, DHCP renewal or roaming timing. Keep device-specific
qualification evidence separate from protocol and ledger tests.

---

# 10 Component Load and Recovery

_Peios / Reference / RADIUS_

> Measuring synthetic admission and accounting loads, checking storage failures, and interpreting incomplete fuzzing evidence.

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

```sh
pekit build --strict -j 2 qualify
pekit test --strict -j 2 qualification clippy
```

Use the executable path printed by the build. The Cargo equivalent is
`cargo build --locked -p radius-qualification`; the executable is
`target/debug/radius-qualify`. Use an optimized executable for measurements.
Do not compare debug and optimized throughput.

```sh
radius-qualify auth --requests 4096 --concurrency 32
radius-qualify accounting --requests 2048 --concurrency 256 --batch 128 --scratch-parent /path/to/scratch
radius-qualify failures --scratch-parent /path/to/scratch
```

The scratch parent must already exist. Each invocation creates a new private
subdirectory and removes it on completion. The failure fixture creates and
terminates its own child processes; it never opens an existing ledger.
`--help` lists workload options. Requests, peers, queue depth, batch size,
and completion deadlines are bounded. Unexpected rejection fails a normal
load; `--allow-overload` allows intentional rejection while still checking
request conservation and recovery.

To collect the nine standard load cases and machine context:

```sh
python3 tools/capacity-qualification.py --binary /path/to/optimized/radius-qualify --out /path/to/new-results --scratch-parent /path/to/scratch
```

The output directory must be new. The runner records the executable hash,
CPU, affinity, starting load, filesystem type, commands, exit statuses, and
JSON results. Each case has a controller deadline. Keep the report with the
source revision and build settings used to produce that executable.

## 10.2 What the workloads measure

Authentication runs full TTLS/PAP exchanges through the production
coordinator and TLS implementation. Credential verification and authorization
use a fixed synthetic backend. The measurement excludes native authd,
password hashing cost, UDP transport, APs, and client radio behavior. After
the load drains, a fresh conversation must succeed on the same coordinator.

Accounting submits unique session Start records to the real asynchronous
owner and SQLite WAL/FULL ledger. Latency runs from submission to receipt
collection and includes batching delay. Every accepted receipt must map to
a unique retained observation after stopping and reopening the owner. This
is not a mixed Start/Interim/Stop benchmark or a measurement of native packet
ingestion. Both workloads use a bounded window of outstanding work rather
than a fixed external arrival rate.

`max_pending` counts outstanding synthetic peers for authentication and
submitted receipts awaiting collection for accounting. It does not measure
internal queue occupancy. Peak RSS is the process high-water mark from Linux,
including fixtures and recovery checks. Successful completions determine
throughput and latency percentiles; rejections are reported separately.

## 10.3 Observed measurements

On 19 November 2026, the optimized hermetic build ran on a Ryzen 5 7600X
host with 12 logical CPUs available. The host was shared with other work;
starting load averages were approximately 3.7, 7.0, and 4.2. The scratch
filesystem reported `ext2/ext3`. These single-run observations establish
neither a production ceiling nor a recommended deployment limit.

| 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](/peios/reference/radius/qualification.md) 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_

> Typed network authorization, equipment mappings, complete replies, and the limits of live updates.

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:

```sh
radius access-profile fields
```

An absent setting requests no override. An explicit false flag requests the
equipment's disabled value; it differs from absence. Unknown settings and
wrong Registry types invalidate configuration. `Extensions` is a JSON object
of typed, namespaced `Extension.<namespace>.<name>` values, with explicit
vendor mappings. It cannot override server-owned identity, selectors, keys,
EAP state, Class, or integrity fields.

Rates are per connection, in bits per second from the connected device's
perspective. Upload travels from the device; download travels to it. Bursts
are bytes. The decimal string representation preserves the complete unsigned
64-bit range. Minimum rates cannot exceed configured maximum rates. A minimum
rate requests an equipment capability; it does not reserve capacity in Peios
or enforce a principal-wide aggregate bandwidth limit.

`VlanId` is a numeric untagged assignment. `VlanName` and tagged or untagged
memberships use the distinct RFC 4675 attributes; they are not alternate
spellings of the numeric tunnel assignment. A numeric VLAN and a second
tunnel assignment cannot coexist. Named filters refer to filters installed on
the equipment. Explicit filter rules accept the supported NAS-Filter-Rule
grammar, with one complete rule per list item. Roles, isolation, QoS, and
IPv4 DNS need an explicit equipment mapping.

Addresses, canonical prefixes, routes, MTU, and tunnel parameters apply to
gateways that understand them. A route contains a destination, a gateway, and
an optional numeric metric. A prefix with host bits is refused. IPv4 netmasks
must be contiguous. Pool references do not allocate leases or control a
bridged Wi-Fi client's DHCP state. Management settings require an appropriate
management Service-Type; they do not grant a local Peios token.

`AccountingInterimSeconds` requests a NAS update interval of at least 60
seconds. It does not alter the ledger's durability rules. `ServiceLabel` is
retained local authorization metadata unless an explicit mapping also sends
it to the equipment. It never replaces the server's accounting correlation.

## 11.2 Timers and allowances

RADIUS provides one Session-Timeout and its Termination-Action. Choose a
profile reauthentication interval, or a session timeout with a disconnect or
reauthenticate action. A session timeout defaults to disconnect. Configuring
both interval settings is refused because they cannot be independent wire
timers. Idle timeout is separate and concerns inactivity after admission; the
daemon's similarly named conversation timeout bounds the authentication
exchange itself.

The network's reauthentication cap can shorten the profile timer. Principal
allowances can shorten it again. The accounting proof retains the configured
cap separately from the shorter reply, so an allowance countdown does not
create repeated policy-change commands. Disconnect expiry does not prevent
another successful authentication. Use cumulative principal allowances for
limits that span multiple successful authentications.

## 11.3 Configuring a profile

CLI and GXWI use the same validation and complete-profile selection:

```sh
radius access-profile create Guests --set VlanId=20 \
    --set IdleTimeoutSeconds=300 --set DownloadBitsPerSecond=10000000 \
    --set UploadBitsPerSecond=2000000
radius access-profile set PROFILE-GUID \
    --set 'FilterRules=["permit in 6 from any to assigned 80,443"]'
radius access-profile unset PROFILE-GUID DownloadBitsPerSecond
```

Replace `PROFILE-GUID` with the created identity. List input accepts a JSON
array when an item contains commas; simple lists also accept comma-separated
items. GXWI uses one list item per line. Clearing an optional field removes
the saved value. Saving still requires a valid complete profile; for example,
remove its expiry action when removing its associated session timeout.

The rate example requires an equipment mapping before admission can succeed.
A valid logical setting that cannot be encoded for the actual client refuses
the connection before quota reservation. It is never silently omitted.

## 11.4 Equipment mappings

The client's existing `DynamicAuthorizationProfile` also supplies its
`authorization` mapping. Its definition contains three maps: `settings` for
admission encodings, `live` for qualified CoA settings, and `clear` for
explicit removal values. A missing setting uses its defined standard encoding.
An empty encoding list explicitly marks a setting unsupported. Vendor-only
settings have no guessed default. Encodings are bounded data, not executable
plugins.

Generate the WISPr rate template with:

```sh
radius dynamic-profile template wispr
```

GXWI offers the same template while creating a Session Control Profile. It
changes the draft only. The template encodes upload and download using vendor
14122 attributes 7 and 8. It declares no qualified live rate support. It is
an attribute template, not a claim that a particular AP enforces those rates.

A custom mapping can describe integer, boolean, text, address or prefix
encodings. Integer conversion uses an exact divisor: values that would round
or overflow are refused. Text and decimal-text encodings can add bounded
prefixes and suffixes. For example, a synthetic equipment definition could
contain:

```json
{
  "authorization": {
    "settings": {
      "DownloadBitsPerSecond": [
        {
          "target": {"vendor": 12345, "attribute": 1},
          "format": "decimal-text",
          "divisor": 1000,
          "prefix": "rate=",
          "suffix": "k"
        }
      ]
    },
    "live": [],
    "clear": {}
  }
}
```

This is the authorization portion of a full Session Control Profile
definition. It is not a recipe for real equipment. Standard type checks,
protected targets, conflicting attribute owners, and the complete reply budget
apply to every mapping. A reply accepts at most 96 authorization attributes
and 2400 encoded bytes; credentials and protocol fields remain server-owned.

## 11.5 Explaining and changing established access

Explain Policy shows the selected logical settings. Supplying a single
`Client.Id` fact also compiles an authorization plan with that client's saved
mapping. The plan distinguishes unsupported settings and missing client
selection. It does not authenticate, check every admission gate, send a
packet or prove enforcement. Operational diagnostics record an assignment
fingerprint over the selected VLAN and complete compiled authorization,
without adding raw filter or extension values to events.

An automatic or manual CoA compares complete authorization settings. Changed
settings need declared live support. A removal needs an explicit reset of the
original recorded attribute; omission never means reset. A changed attribute
identity requires fresh authentication. Management protocol and transport
protection changes cannot be sent in CoA. Equipment that replaces an entire
list must be qualified for that replacement behavior.

A recipe that cannot express the new authorization uses the existing
configured fallback and its separate permissions. An ACK records what was
requested and acknowledged, not proof that every setting was enforced. The
issued baseline, desired settings, last acknowledged request, and limited NAS
observations remain distinct. See
[Session Controls](/peios/reference/radius/session-controls.md).

## 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](https://www.rfc-editor.org/rfc/rfc2865.html),
[RFC 3580](https://www.rfc-editor.org/rfc/rfc3580.html),
[RFC 4675](https://www.rfc-editor.org/rfc/rfc4675.html),
[RFC 4849](https://www.rfc-editor.org/rfc/rfc4849.html),
[RFC 6911](https://www.rfc-editor.org/rfc/rfc6911.html), and
[RFC 5607](https://www.rfc-editor.org/rfc/rfc5607.html).
