# loregd

> The SQLite registry source: startup, storage, concurrency, and request handling.

---

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