# Sources

---

# Sources

_Peios Kernel / Internals / LCS / Sources_

> Find the Peios kernel articles about sources.

Use these articles to understand sources in the Peios kernel.

- [The Source Model](</kernel/internals/lcs/sources/the-source-model.md>)
- [Registration and Slots](</kernel/internals/lcs/sources/registration-and-slots.md>)
- [Request Dispatch](</kernel/internals/lcs/sources/request-dispatch.md>)
- [Validation](</kernel/internals/lcs/sources/validation.md>)
- [Failure and Late Responses](</kernel/internals/lcs/sources/failure-and-late-responses.md>)

---

# The Source Model

_Peios Kernel / Internals / LCS / Sources_

> A source is a userspace process holding registry data and answering LCS over RSI — the trust boundary, and why loregd is not special.

<a id="trm-5-8-1"></a>

A source is a userspace process that holds registry data and answers
LCS's questions about it over the Registry Source Interface. LCS is
source-agnostic: it does not know or care how a source stores anything.

The division is the sixth semantic rule ([Overview](</kernel/internals/lcs/start-here/overview.md#trm-5-1>)). A source stores path
entries, key records, value entries and blanket tombstones, and returns
**all** of them on request. <a id="cite-source.model.returns-all-entries"></a>

It does not evaluate access, resolve layers, dispatch watches, interpret
paths beyond the parent and child names it is given, or see the identity
of any caller. LCS does all of that. <a id="cite-source.model.does-no-policy"></a>

A source may back several hives; a hive is backed by exactly one source
([Hives and Routing](</kernel/internals/lcs/data-model/hives-and-routing.md#trm-5-2-1>)).

<a id="trm-5-8-1-1"></a>

## The interface is specified elsewhere

The RSI — its channel, framing, operations, error vocabulary, and the
obligations binding on a conforming source — is a normative
specification, because the userspace side is a role a third party can
implement. It is a chapter of PSPK, and it is where the wire format
lives.

This section covers the kernel's side: how LCS admits a source, how it
dispatches requests and accounts for them, what it refuses to believe,
and what it does when a source dies or answers late.

<a id="trm-5-8-1-2"></a>

## The trust boundary

Sources are in the TCB. LCS trusts the data a source returns —
descriptors, values, symlink targets, key metadata — because it has no
independent copy of any of it. <a id="cite-source.model.lcs-trusts-source-data"></a>

A compromised source therefore has complete control over access
decisions for its hives. It can return a permissive descriptor for any
key and AccessCheck will grant access that should have been denied. LCS
validates that responses are structurally correct, but it cannot detect
data that is well-formed and wrong: a descriptor granting Everyone
`KEY_ALL_ACCESS` on a sensitive key is a perfectly valid descriptor.

Three consequences are worth naming specifically.

**Layer table poisoning.** A compromised source backing `Machine\` can
fabricate the `Precedence` and `Enabled` values under
`Machine\System\Registry\Layers\`, and so control which layer wins
every resolution contest system-wide. The `SeTcbPrivilege` check at
write time does nothing about a fabricated read.

**Layer authorization bypass.** The same source can return permissive
descriptors for layer metadata keys, granting any process write access
to any layer ([Writing Into a Layer](</kernel/internals/lcs/layers/writing-into-a-layer.md#trm-5-3-4>)).

**`SeRestorePrivilege` implies descriptor control.** Restore replaces a
subtree including every descriptor in it, so granting
`SeRestorePrivilege` effectively grants `WRITE_DAC` and `WRITE_OWNER`
over everything in reach of a restore. <a id="cite-source.model.restore-implies-descriptor-control"></a> Operators should
understand it that way.

The mitigations are operational rather than architectural: sources run
with tightly scoped privileges, protected by descriptors on their
service definitions, and managed by peinit with Process Integrity
Protection where available. LCS emits audit events for every source
data validation failure. A harder guarantee — checksumming descriptors
LCS computed during inheritance and verifying them on retrieval — is
possible but not implemented.

<a id="trm-5-8-1-3"></a>

## loregd is not special <a id="cite-source.model.loregd-is-not-special"></a>

loregd is the first source and the one that provides `Machine\` and
`Users\` at boot, which puts it on the critical path to a running
system. Nothing in LCS knows that. Its details are its own manual's
business; what LCS requires of it is exactly what it requires of any
source.

---

# Registration and Slots

_Peios Kernel / Internals / LCS / Sources_

> Reaching LCS through /dev/pkm_registry — what registration validates, how source slots work, and resuming one that went Down.

<a id="trm-5-8-2"></a>

A source reaches LCS through `/dev/pkm_registry`. The device's `open()`
handler checks the calling thread's effective token for an **enabled**
`SeTcbPrivilege` and returns `EPERM` without it, so an unprivileged
process cannot obtain an fd to the device at all. <a id="cite-source.register.open-requires-enabled-setcbprivilege"></a>

Having opened it, the source issues `REG_SRC_REGISTER`, naming the
hives it backs, the root GUID of each, the highest sequence number it
has persisted, and per-hive flags and scope GUID. On success it enters
the request loop: `read()` for requests, `write()` for responses.

<a id="trm-5-8-2-1"></a>

## What registration validates

- Every hive name is valid and is not the reserved `CurrentUser`
  ([Hives and Routing](</kernel/internals/lcs/data-model/hives-and-routing.md#trm-5-2-1>)). <a id="cite-source.register.hive-name-valid-and-not-currentuser"></a>
- No route identity — the folded name paired with its scope — collides
  with one held by another **Active** source. <a id="cite-source.register.no-route-identity-collision"></a>
- Private hive collisions are scoped: the same name in different scopes
  is fine ([Private Hives](</kernel/internals/lcs/data-model/private-hives.md#trm-5-2-2>)). <a id="cite-source.register.private-hive-collisions-are-scoped"></a>
- A hive's root GUID is not nil. <a id="cite-source.register.root-guid-not-nil"></a>
- The root GUIDs within one request are distinct from each other. <a id="cite-source.register.root-guids-distinct-within-request"></a>
- A hive without `RSI_HIVE_PRIVATE` carries no scope GUID. <a id="cite-source.register.scope-guid-only-for-private-hive"></a>
- No unknown flag bits are set. <a id="cite-source.register.no-unknown-flag-bits"></a>
- The hive count is within `MaxHivesPerSource` (64), and the source
  count is within `MaxRegisteredSources` (32). Either limit is `ENOSPC`;
  a zero hive count is `EINVAL`. <a id="cite-source.register.hive-and-source-counts-are-enospc"></a>
- The reported maximum sequence can be advanced past without
  overflowing 64 bits, or registration fails `EOVERFLOW` and the source
  is never made Active ([The Sequence Counter](</kernel/internals/lcs/layers/the-sequence-counter.md#trm-5-3-7>)). <a id="cite-source.register.max-sequence-overflow-is-eoverflow"></a>

Root GUIDs are checked for uniqueness within one request, and against
every existing slot, Active or Down: a request whose root GUID is
already the root of a differently-named hive is refused `EEXIST`. A
same-named hive is decided by the identity rules above instead. The
already-registered state is also checked for consistency, and a table
that ever held two hives with one root would fail that check on every
later registration and path walk, which is why admission refuses it. <a id="cite-source.register.root-guids-compared-across-slots"></a>

<a id="trm-5-8-2-2"></a>

## Source slots

Successful registration creates a **source slot**: the kernel object
owning one connection and the hive set registered on it. <a id="cite-source.register.success-creates-a-slot"></a>

Each registered hive has a stable identity — its folded name, its
visibility, its scope GUID for a private hive, and its root GUID. <a id="cite-source.register.hive-identity-fields"></a>

**Down slots keep their identities reserved.** A crash or an fd close
marks the slot Down; it does not unregister anything and does not
retire any hive identity. <a id="cite-source.register.down-slot-keeps-its-identities"></a>

Slots are never freed, and collision checks see Down slots as well as
Active ones. <a id="cite-source.register.collision-checks-see-down-slots"></a>

Status is a property of the slot, not of an individual hive. A source's
hives go Down together. <a id="cite-source.register.status-is-per-slot"></a>

<a id="trm-5-8-2-3"></a>

## Resuming a Down slot

A new process may take over a Down slot if it holds `SeTcbPrivilege`
and registers **exactly the same hive set**: the same folded name,
visibility, scope GUID and root GUID for every hive, and the same
number of them. Partial resume is rejected. <a id="cite-source.register.resume-requires-exact-hive-set"></a>

The distinction between the failures matters. A request whose only
mismatch is stale identity data — a different root GUID for an
otherwise-matching hive — fails `ESTALE`. <a id="cite-source.register.stale-root-guid-is-estale"></a>

Other partial or malformed resume attempts fail `EINVAL`. <a id="cite-source.register.other-resume-mismatch-is-einval"></a>

`EEXIST` is reserved for a collision with an **Active** slot; it never
comes from a Down-slot collision. <a id="cite-source.register.eexist-only-from-active-collision"></a>

When both an Active collision and a stale Down slot apply, `EEXIST`
wins. <a id="cite-source.register.eexist-wins-over-estale"></a>

New hives cannot be added by mutating a Down slot during a resume — the
hive set has to match exactly, so a superset simply fails, and a new
hive needs a new slot. There is no implicit retirement of a Down slot;
retiring one would need an explicit administrative operation, and none
exists. <a id="cite-source.register.no-implicit-down-slot-retirement"></a>

A replacement source is authenticated by `SeTcbPrivilege`, not by
process identity. Nothing records a pid, and nothing could usefully:
process identity does not survive a crash and restart. <a id="cite-source.register.resume-authenticated-by-privilege-not-pid"></a>

<a id="trm-5-8-2-4"></a>

## Coming back

On a successful resume the slot becomes Active, its restart generation
advances, and LCS replays any layer deletions that were pending. <a id="cite-source.register.resume-activates-slot-and-replays"></a>

LCS then delivers `OVERFLOW` to every armed watch on that source
([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)).

Existing key fds resume working without being reopened. Each carries
the restart generation it last saw; when it notices a change it
re-reads its key and continues. <a id="cite-source.register.key-fds-survive-a-resume"></a>

If the key's GUID no longer exists in the restarted source — the
database was restored from an older backup, say — that first operation
returns `ENOENT` and the fd is marked orphaned. <a id="cite-source.register.missing-guid-after-resume-orphans-fd"></a>

---

# Request Dispatch

_Peios Kernel / Internals / LCS / Sources_

> The RSI is multiplexed — request ids and matching, the single deadline covering three waits, and requests with no caller.

<a id="trm-5-8-3"></a>

The RSI is multiplexed. LCS sends concurrent requests tagged with
request ids and matches responses back to the kernel threads waiting on
them. A source may process requests in any order. <a id="cite-source.dispatch.responses-may-arrive-in-any-order"></a>

Request ids are allocated per connection, strictly increasing, and
**never reused** while the connection lives — including after a
timeout. <a id="cite-source.dispatch.request-ids-never-reused"></a>

The id is allocated inside the queue lock, after the in-flight limit has
been checked, so a caller queued waiting for a slot does not hold one
yet. <a id="cite-source.dispatch.id-allocated-after-the-limit-check"></a>

`MaxConcurrentRSIRequests`, default 256, bounds how many requests may
be dispatched and awaiting a response at once. <a id="cite-source.dispatch.max-concurrent-bounds-in-flight"></a> It is back-pressure for
a slow source.

<a id="trm-5-8-3-1"></a>

## One deadline covers three waits

`RequestTimeoutMs`, default 30 seconds, is measured from the point a
kernel operation first attempts to **reserve an in-flight slot**, after
local validation and access checks have already passed. One deadline is
computed there and reused for all three legs: waiting for a slot,
waiting for the source to read the queued request, and waiting for the
response. <a id="cite-source.dispatch.one-deadline-covers-three-waits"></a>

If the deadline expires before a slot is reserved, the caller gets
`ETIMEDOUT` and **no request is sent**. <a id="cite-source.dispatch.timeout-before-a-slot-sends-nothing"></a>

If it expires after dispatch, the caller gets `ETIMEDOUT` and
late-response handling applies ([Failure and Late Responses](</kernel/internals/lcs/sources/failure-and-late-responses.md#trm-5-8-5>)). <a id="cite-source.dispatch.timeout-after-dispatch-is-etimedout"></a>

The deadline is checked before admission is attempted, not only after a
contention round is lost. <a id="cite-source.dispatch.deadline-checked-before-admission"></a> It used to be the latter, which meant a request
finding a slot immediately free was dispatched with an already-expired
deadline and timed out in the wait leg instead — so the rule above held
only under contention, the one case where it is hardest to observe.

<a id="trm-5-8-3-2"></a>

## Timed-out requests keep their slot

For every dispatched request LCS keeps a **request record** until a
matching response is processed or the connection is torn down. <a id="cite-source.dispatch.record-kept-until-response-or-teardown"></a>

The record holds the request id, the operation code, the transaction
id, the key GUID it concerns, the runtime limits in force, and any
retained effect the kernel will need if the source later reports
success. <a id="cite-source.dispatch.record-contents"></a>

When the deadline expires after dispatch, LCS detaches the waiting
caller from the record and returns `ETIMEDOUT`. <a id="cite-source.dispatch.timeout-detaches-caller-from-record"></a>

A signal that interrupts the wait after dispatch detaches the caller
the same way, and the call fails with `EINTR` or is restarted. As after
a timeout, the source may still apply the request when it answers. A
response that completed before the caller could be detached wins: the
caller gets that response's result, with the signal still pending. <a id="cite-source.dispatch.completion-beats-a-signal"></a>

**The record stays in the in-flight table and keeps counting against
`MaxConcurrentRSIRequests`.** A timeout does not free a slot; only a
response or a teardown does. <a id="cite-source.dispatch.timeout-does-not-free-a-slot"></a>

A source that accumulates timed-out requests can therefore exhaust its
own in-flight slots until it answers or disconnects. That is the
intended shape: a source that stops answering stops being usable.

<a id="trm-5-8-3-3"></a>

## Requests with no caller

LCS dispatches some requests with nobody waiting: `RSI_DROP_KEY` after
the last fd to an orphaned key closes ([Deletion and Orphans](</kernel/internals/lcs/data-model/deletion-and-orphans.md#trm-5-2-9>)), and
`RSI_ABORT_TRANSACTION` cleaning up source transaction state. <a id="cite-source.dispatch.callerless-requests-are-dispatched"></a>

Such a record occupies an in-flight slot and is retained like any
other, and its response is validated normally and released normally. <a id="cite-source.dispatch.callerless-record-occupies-a-slot"></a>

But it is **not** a late response, and the retained-effect recovery
rules do not apply to it merely because nobody is waiting. <a id="cite-source.dispatch.callerless-is-not-a-late-response"></a>

The kernel tracks the difference explicitly, with two booleans: whether
a waiter is attached now, and whether one was ever attached. A record
that never had a caller is not a timed-out request; only one whose
caller was detached after its deadline is. <a id="cite-source.dispatch.timed-out-means-caller-detached-after-deadline"></a>

This is load-bearing rather than pedantic. `RSI_DROP_KEY` is a mutating
operation, so without the distinction a perfectly ordinary answer to a
caller-less cleanup request would look like a mutation the kernel could
not account for, and would tear the source down.

<a id="trm-5-8-3-4"></a>

## The channel

`/dev/pkm_registry` is message-oriented. One `read()` returns exactly
one complete request; a buffer too small for the next one returns
`EMSGSIZE` **without consuming it**. <a id="cite-source.dispatch.read-returns-one-request-or-emsgsize"></a>

An empty queue blocks, or returns `EAGAIN` under `O_NONBLOCK`, or
returns 0 if the fd is closing. <a id="cite-source.dispatch.empty-queue-blocks-or-eagain"></a>

One `write()` submits exactly one complete response, and its length
must equal the response's own `total_len` exactly. <a id="cite-source.dispatch.write-submits-one-response-of-exact-length"></a>

`poll` reports the fd readable when a request is queued, writable while
the slot is Active, and `POLLHUP | POLLERR` when the slot is Down or
the fd is closing. <a id="cite-source.dispatch.poll-reports-queue-and-slot-state"></a>

An fd that is open but has not yet registered reports nothing at all. <a id="cite-source.dispatch.unregistered-fd-polls-nothing"></a>

Any rejected `write()` — short, over-long, an unknown or duplicate
request id, an operation code that does not match the request, a
response for another connection — returns `EINVAL` **and tears the
connection down**. <a id="cite-source.dispatch.rejected-write-is-einval-and-tears-down"></a> A source that cannot speak the protocol correctly is
not one whose other answers are worth believing.

<a id="trm-5-8-3-5"></a>

## Negotiated lifetime control

Sources may negotiate lifetime extension version 1 with `REG_SRC_NEGOTIATE`
before `REG_SRC_REGISTER`. Pass version 1, zero flags and zero session; the
kernel returns a nonzero session identifier unique to the open source file.
The RSI request and response frame layouts are unchanged. Sources that do not
negotiate retain the legacy protocol; current loregd requires this extension.
<a id="cite-source.dispatch.lifetime-extension-is-negotiated-before-registration"></a>

After reading a request and before responding, `REG_SRC_REQUEST_CONTEXT` takes
that session and request id and returns three absolute `CLOCK_MONOTONIC`
nanosecond timestamps: the request deadline, transaction lifetime deadline and
cleanup lease deadline. Zero lifetime means an operation-owned transaction
with no separate lifetime ceiling. Zero lease means there is no live transaction
owner. Request metadata remains queryable after caller detachment until the
response is accepted, so cleanup and late-response handling still work.
<a id="cite-source.dispatch.context-preserves-the-original-request-deadline"></a>

`REG_SRC_RENEW` takes the session and transaction id and returns the original
lifetime deadline plus a renewed cleanup deadline, at most five seconds from
now and never beyond the lifetime deadline. It succeeds only for an existing,
nonterminal transaction owned by a live file object or kernel operation on
this source session. Unknown, released, expired and foreign-session identities
return `ESTALE`. Once a lease expires, renewal cannot resurrect it. These
control ioctls consume no ordinary request slots, so request-queue saturation
does not starve renewal.
<a id="cite-source.dispatch.lease-renewal-requires-a-live-owner-and-session"></a>

Final owner release and abort prevent renewal before abort-message delivery.
Client lifetime expiration also prevents renewal. Sources must reject new
operations after expiry and serialize rollback with operations and commit;
an already-admitted commit must resolve its actual outcome. Lease cleanup
does not change the kernel's treatment of late commit responses ([Failure and Late Responses](</kernel/internals/lcs/sources/failure-and-late-responses.md#trm-5-8-5>)).
<a id="cite-source.dispatch.lease-expiry-does-not-infer-a-commit-outcome"></a>

---

# Validation

_Peios Kernel / Internals / LCS / Sources_

> LCS validates every response before using it — malformed data against malformed protocol, and the asymmetric extensibility between them.

<a id="trm-5-8-4"></a>

LCS validates every response before using it, and the failures split
into two categories with very different consequences. <a id="cite-source.validate.every-response-is-validated"></a>

<a id="trm-5-8-4-1"></a>

## Malformed data

The RSI message is structurally valid but its content is not: a
descriptor that will not parse, a value type that does not exist, a
sequence number that cannot be real, a metadata block that does not
cover the GUIDs it should.

- The request returns `EIO` to its caller. <a id="cite-source.validate.malformed-data-returns-eio"></a>
- An `lcs.source.response.rejected` audit event is emitted, naming the
  source slot and — where known — the hive, the request id, the
  operation code, the key GUID, and which of the twelve validation
  classes applies ([Audit](</kernel/internals/lcs/security/audit.md#trm-5-4-4>)). <a id="cite-source.validate.malformed-data-emits-an-audit-event"></a>
- **The source stays alive.** Corruption may be localised, and one bad
  key is not a reason to take a hive offline. <a id="cite-source.validate.malformed-data-keeps-the-source-alive"></a>

What is checked, by category:

- **Security Descriptors**, from lookups and from layer metadata
  refreshes, must parse and must satisfy the ACE mask rules of [Access Rights](</kernel/internals/lcs/security/access-rights.md#trm-5-4-2>). <a id="cite-source.validate.descriptors-must-parse"></a>
  A malformed layer metadata descriptor additionally leaves the
  previous known-good one cached ([Layer Metadata](</kernel/internals/lcs/layers/layer-metadata.md#trm-5-3-3>)).
- **Names** — layer names, key and child names, value names — must be
  valid under the ordinary rules for their kind. <a id="cite-source.validate.names-must-be-valid"></a>
- **Sequence numbers** must be below the next number LCS would
  allocate, and must not duplicate at the same precedence in a way that
  would decide a winner ([Resolution](</kernel/internals/lcs/layers/resolution.md#trm-5-3-6>)). <a id="cite-source.validate.sequence-number-checks"></a>
- **Payload shape** — an otherwise-matched response whose
  operation-specific payload is the wrong shape, carries trailing
  bytes, or encodes a path target invalidly. <a id="cite-source.validate.payload-shape-checks"></a>
- **Metadata closure** — a lookup or enumeration whose per-GUID
  metadata block has missing, duplicate, unreferenced or nil entries. <a id="cite-source.validate.metadata-closure-checks"></a>
  A HIDDEN entry must carry an all-zero GUID and contributes no
  metadata. <a id="cite-source.validate.hidden-entry-carries-a-zero-guid"></a>
- **Value payloads** — invalid types, a tombstone carrying data, data
  above `MaxValueSize`. <a id="cite-source.validate.value-payload-checks"></a>
- **Orphan lists** — a nil or duplicated GUID in an `RSI_DELETE_LAYER`
  response. <a id="cite-source.validate.orphan-list-checks"></a>
- **Status codes** outside the defined vocabulary. <a id="cite-source.validate.unknown-status-code"></a>

<a id="trm-5-8-4-2"></a>

## Malformed protocol

The message itself is structurally invalid: bad framing, a truncated
response, an unknown request id, a duplicate response, an operation
code that does not match the request.

This is treated as a source crash. The connection is torn down, the
in-flight table is destroyed with every waiter completed `EIO`, the
slot is marked Down, its hives become unavailable, and bound
transactions enter `SOURCE_DOWN`. <a id="cite-source.validate.malformed-protocol-is-treated-as-a-crash"></a>

There is one case where malformed *data* also takes the source down:
when the caller had already timed out and the operation was a commit or
a replayable mutation. At that point LCS cannot establish whether a
mutation was applied, and it cannot account for one it cannot describe
([Failure and Late Responses](</kernel/internals/lcs/sources/failure-and-late-responses.md#trm-5-8-5>)).

<a id="trm-5-8-4-3"></a>

## Asymmetric extensibility

Requests and responses do not extend the same way.

A **request** may carry trailing fields a source does not recognise; a
source skips them using `total_len`. <a id="cite-source.validate.requests-may-carry-trailing-fields"></a> That is how a new optional field
is added without an RSI version bump.

A **response** may not. LCS rejects any trailing bytes in a response
payload as malformed data. Forward compatibility on the response side
comes from new operations, not from extending existing payloads.

---

# Failure and Late Responses

_Peios Kernel / Internals / LCS / Sources_

> What happens when a source dies, and the late-response problem — a late error, a late successful read, and a late successful write.

<a id="trm-5-8-5"></a>

<a id="trm-5-8-5-1"></a>

## When a source dies

The connection closes unexpectedly, and:

1. The slot is marked Down and its hives become unavailable. <a id="cite-source.failure.slot-marked-down-hives-unavailable"></a>
2. Every pending request fails `EIO`, including ones queued but not yet
   delivered. <a id="cite-source.failure.pending-requests-fail-eio"></a>
3. **Open key fds stay valid.** An fd holds a GUID and a granted mask,
   and neither depends on the source. Operations needing a round trip
   return `EIO` until the source comes back. <a id="cite-source.failure.key-fds-stay-valid-round-trips-eio"></a>
4. Bound transactions enter `REG_TXN_SOURCE_DOWN`, their poll waiters
   are woken with `POLLERR | POLLHUP`, their mutation logs are
   released, and further use of those fds returns `EIO`. <a id="cite-source.failure.bound-transactions-enter-source-down"></a>
5. **Watches stay armed.** Watch state is kernel-side and does not
   depend on the source at all. <a id="cite-source.failure.watches-stay-armed"></a> Nothing is delivered during the window,
   and `OVERFLOW` arrives on re-registration rather than on disconnect
   ([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)).

Coming back is covered in [Registration and Slots](</kernel/internals/lcs/sources/registration-and-slots.md#trm-5-8-2>).

<a id="trm-5-8-5-2"></a>

## The late response problem

A caller that times out after its request was dispatched is gone, but
the request is not. The source may still apply the operation and answer
minutes later, and by then there is nobody to return a value to — while
the *kernel* still has work to do, because a mutation that succeeded
has to produce its generation increment and its watch events.

This is the most intricate part of LCS and the part with the most ways
to be subtly wrong.

A late response is validated exactly like an on-time one. <a id="cite-source.late.validated-like-an-on-time-response"></a> The rules
that follow apply **only** to a request whose caller was detached after
its deadline, never to one that never had a caller ([Request Dispatch](</kernel/internals/lcs/sources/request-dispatch.md#trm-5-8-3>)).

<a id="trm-5-8-5-2-1"></a>

### A late error <a id="cite-source.late.error-has-no-effects"></a>

The record is released. No watch events, no generation change, nothing.

<a id="trm-5-8-5-2-2"></a>

### A late successful read <a id="cite-source.late.read-is-validated-then-discarded"></a>

Validated, then discarded. There is nobody to give it to and nothing
about it changes kernel state.

<a id="trm-5-8-5-2-3"></a>

### A late successful mutation

The kernel-side effects that correspond to the mutation are applied
from the retained record: the hive generation increment, watch
dispatch, the layer metadata cache refresh, and — for a commit — the
transaction's batch effects and orphan tracking. <a id="cite-source.late.mutation-applies-retained-effects"></a>
The watch dispatch takes the recovery form: a watcher receives an
`OVERFLOW` ahead of the event itself ([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)).

Which mutations can actually be replayed is narrower than the set of
operations that count as mutating. A replayable effect is recorded for
`RSI_SET_VALUE` and `RSI_WRITE_KEY`, and only for non-transactional
calls. <a id="cite-source.late.replayable-effects-only-for-set-value-and-write-key"></a>

For the other mutating operations — creating, hiding or deleting a path
entry, creating or dropping a key, deleting a value entry, setting a
blanket tombstone, deleting a layer — no effect was retained, so a late
success is a mutation the kernel cannot account for. LCS tears the
source down and returns `EIO` rather than silently ignoring it. <a id="cite-source.late.unreplayable-mutation-tears-source-down"></a>

That is the conservative direction, and deliberately so: the
alternative is a committed change with no watch event and a stale
generation number, which nothing downstream could detect.

<a id="trm-5-8-5-2-4"></a>

### A late successful transaction operation

A late `RSI_BEGIN_TRANSACTION` has created transaction state in the
source that nobody will ever use, so LCS enqueues an
`RSI_ABORT_TRANSACTION` for that id. <a id="cite-source.late.begin-transaction-enqueues-an-abort"></a>

A late `RSI_ABORT_TRANSACTION` or `RSI_FLUSH` releases the record with
no effects. <a id="cite-source.late.abort-or-flush-releases-the-record"></a>

A late `RSI_COMMIT_TRANSACTION` is a mutating response and applies the
retained commit effects — the same generation update and the same watch
events an on-time commit would have produced. <a id="cite-source.late.commit-applies-retained-commit-effects"></a> Watchers may therefore
observe the effects of a transaction whose caller was told it timed
out ([Commit and Failure](</kernel/internals/lcs/transactions/commit-and-failure.md#trm-5-7-3>)).

<a id="trm-5-8-5-2-5"></a>

### A malformed late response

The ordinary malformed-data and malformed-protocol rules apply. But if
LCS cannot safely process the kernel-side effects of a
possibly-applied mutation because the request metadata it needs is
missing or invalid, it tears the source down and marks it Down rather
than ignoring the response. <a id="cite-source.late.unprocessable-effects-tear-source-down"></a>

A malformed late commit response takes the source down for the same
reason. <a id="cite-source.late.malformed-commit-tears-source-down"></a>

<a id="trm-5-8-5-3"></a>

## What a caller should conclude

`ETIMEDOUT` means *may or may not have completed*. A caller that needs
certainty reads state back before retrying. That applies to every
operation and, especially, to a transaction commit.

<a id="trm-5-8-5-4"></a>

## Fd lifecycle

Key fds and transaction fds are ordinary file descriptors, subject to
`RLIMIT_NOFILE`. There is no registry-specific fd accounting and no
registry-specific leak protection. <a id="cite-source.failure.no-registry-specific-fd-accounting"></a>

Process exit closes them through normal kernel cleanup: key fds
released and their watches removed, transactions aborted. <a id="cite-source.failure.process-exit-releases-fds"></a>

<a id="trm-5-8-5-5"></a>

## Memory

Registry kernel memory needs no global cap, because everything is
bounded by limits that already exist.

- **Watch queues:** `NotificationQueueSize` per queue, times
  `RLIMIT_NOFILE` queues per process.
- **Open key state:** per-fd overhead — GUID, granted mask, ancestor
  chain, watch state — times the same fd limit.
- **Layer table:** bounded by `MaxTotalLayers`, and per-value
  resolution cost by `MaxLayersPerValue`.
- **In-flight requests:** bounded per source by
  `MaxConcurrentRSIRequests`, and separately by the number of threads
  blocked on registry syscalls.
