# Watches

---

# Watches

_Peios Kernel / Internals / LCS / Watches_

> Find the Peios kernel articles about watches.

Use these articles to understand watches in the Peios kernel.

- [The Watch Model](</kernel/internals/lcs/watches/the-watch-model.md>)
- [Event Records](</kernel/internals/lcs/watches/event-records.md>)
- [Dispatch](</kernel/internals/lcs/watches/dispatch.md>)
- [Queues and Overflow](</kernel/internals/lcs/watches/queues-and-overflow.md>)

---

# The Watch Model

_Peios Kernel / Internals / LCS / Watches_

> A persistent subscription to changes on an open key, following inotify rather than the Windows model — what it observes, its event types and filters.

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

A watch is a persistent subscription to changes on an open key. It
follows the inotify model rather than the Windows one: once armed, it
stays armed until the fd closes, and events keep arriving without
re-registration. <a id="cite-watch.model.persistent-until-fd-close"></a>
`RegNotifyChangeKeyValue` is single-shot, and the window between
receiving a notification and re-registering is a window in which
changes are missed; a persistent watch has no such window.

A watch is armed by `REG_IOC_NOTIFY` on a key fd, which requires
`KEY_NOTIFY` in the fd's granted mask. Arming takes a filter — a bitmask
of event categories — and a subtree flag. After arming, the fd is
pollable: `EPOLLIN` reports pending events, and `read()` returns
structured records. <a id="cite-watch.model.armed-fd-is-pollable"></a>

Each fd carries at most one watch. <a id="cite-watch.model.one-watch-per-fd"></a>

Arming an already-armed fd replaces the filter and the subtree setting
and leaves queued events in place. <a id="cite-watch.model.rearm-replaces-filter-and-keeps-queue"></a>

Arming with a filter of zero disarms: the watch is removed and every
pending event is discarded. <a id="cite-watch.model.zero-filter-disarms-and-discards"></a>
To watch one key under two different filters, open it twice.

Arming a watch on a key that is already orphaned fails with `ENOENT`. A
watch armed before the key was orphaned stays armed ([Deletion and Orphans](</kernel/internals/lcs/data-model/deletion-and-orphans.md#trm-5-2-9>)).

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

## What a watch observes

Events describe changes to **effective** state, not to layer mechanics.
A watcher sees that a value changed; it does not see which layer won,
or that a layer was deleted. <a id="cite-watch.model.reports-effective-state-not-layer-mechanics"></a>
Removing a hiding entry that was concealing a lower-precedence key
produces `SUBKEY_CREATED`. Removing a whole layer is recovery dispatch
rather than a diff, and reaches a watcher as `OVERFLOW` ([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)). The layer
system is not visible through a watch at all.

The events are computed by diffing the effective state before the
mutation against the effective state after it, which is what makes this
true by construction rather than by careful case analysis. <a id="cite-watch.model.computed-by-diffing-effective-state"></a>

A change that replaces the key at a child name with a different key
object — different GUID, same name — produces `SUBKEY_DELETED` followed
by `SUBKEY_CREATED`, because that is what the diff says happened. <a id="cite-watch.model.key-replacement-is-delete-then-create"></a>

Only committed state is observable. Operations inside an uncommitted
transaction produce nothing; the whole set fires at commit ([Dispatch](</kernel/internals/lcs/watches/dispatch.md#trm-5-6-3>)).

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

## Event types

| Event | Code | Name field | Meaning |
|---|---|---|---|
| `REG_WATCH_VALUE_SET` | 1 | value name | The effective value at this name changed or appeared. <a id="cite-watch.model.event-value-set"></a> |
| `REG_WATCH_VALUE_DELETED` | 2 | value name | The effective value at this name disappeared. <a id="cite-watch.model.event-value-deleted"></a> |
| `REG_WATCH_SUBKEY_CREATED` | 3 | subkey name | A child key became visible. <a id="cite-watch.model.event-subkey-created"></a> |
| `REG_WATCH_SUBKEY_DELETED` | 4 | subkey name | A child key became invisible. <a id="cite-watch.model.event-subkey-deleted"></a> |
| `REG_WATCH_SD_CHANGED` | 5 | empty | The watched key's Security Descriptor was modified. <a id="cite-watch.model.event-sd-changed"></a> |
| `REG_WATCH_KEY_DELETED` | 6 | empty | The watched key itself became invisible. <a id="cite-watch.model.event-key-deleted"></a> |
| `REG_WATCH_OVERFLOW` | 7 | empty | Events were dropped; re-read to recover. <a id="cite-watch.model.event-overflow"></a> |

`VALUE_SET` fires when a value is written, and when a tombstone or
blanket tombstone is removed and a lower-precedence value surfaces. <a id="cite-watch.model.value-set-fires-on-write-unmask-or-layer-deletion"></a>

`VALUE_DELETED` fires when the last entry for a name goes away, when a
tombstone masks every entry, and when a blanket tombstone masks this
name. <a id="cite-watch.model.value-deleted-fires-on-last-entry-gone-or-masked"></a>

`SUBKEY_CREATED` and `SUBKEY_DELETED` cover both halves of the naming
model: a path entry appearing or being removed, and a hiding entry
being removed or created. <a id="cite-watch.model.subkey-events-cover-path-and-hiding-entries"></a>

The three no-name events carry no name, and that is enforced: a record
constructed with a name for `SD_CHANGED`, `KEY_DELETED` or `OVERFLOW`
is rejected rather than emitted. <a id="cite-watch.model.no-name-events-reject-a-name"></a>

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

## Filters

The filter selects event *categories*, not individual event types. <a id="cite-watch.model.filter-selects-categories"></a>

| Filter bit | Value | Admits |
|---|---|---|
| `REG_NOTIFY_VALUE` | `0x01` | `VALUE_SET`, `VALUE_DELETED` <a id="cite-watch.model.filter-value-admits-value-events"></a> |
| `REG_NOTIFY_SUBKEY` | `0x02` | `SUBKEY_CREATED`, `SUBKEY_DELETED` <a id="cite-watch.model.filter-subkey-admits-subkey-events"></a> |
| `REG_NOTIFY_SD` | `0x04` | `SD_CHANGED` <a id="cite-watch.model.filter-sd-admits-sd-changed"></a> |
| `REG_NOTIFY_ALL` | `0x07` | all three of the above <a id="cite-watch.model.filter-all-admits-all-three-categories"></a> |

`KEY_DELETED` and `OVERFLOW` are delivered unconditionally. They are
not in any category and no filter suppresses them. <a id="cite-watch.model.key-deleted-and-overflow-bypass-the-filter"></a>
The first tells a watcher its key is gone, and the second tells it that
what it has been told is incomplete. Neither is something a watcher can
usefully opt out of.

A filter containing an undefined bit is rejected. <a id="cite-watch.model.undefined-filter-bit-rejected"></a>

A subtree flag other than 0 or 1, or a non-zero padding byte in the
argument structure, is rejected the same way. <a id="cite-watch.model.subtree-flag-must-be-zero-or-one"></a>

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

## Blanket tombstones

A watcher never learns that a blanket tombstone exists. <a id="cite-watch.model.blanket-tombstone-never-surfaces-as-such"></a>

When one is written, LCS works out which values it newly masks and
emits one `VALUE_DELETED` per name; when one is removed, one
`VALUE_SET` per name that became visible. <a id="cite-watch.model.blanket-tombstone-expands-to-per-value-events"></a>
The per-value view is the only view.

---

# Event Records

_Peios Kernel / Internals / LCS / Watches_

> Events read from the key fd with read() — the record layout, why not every subtree record carries a path, and forward compatibility.

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

These registry watch records are notifications, not KMES events. They have
no MessagePack payload, KMES envelope, or kernel-stamped emitter identity.
Use them to discover changes that require a fresh read, not as an audit
trail. The `.evman` event catalog does not define this binary interface.

Events are read from the key fd with `read()`. A single call returns as
many complete events as fit in the caller's buffer; an event is never
split across two calls. <a id="cite-watch.record.read-returns-whole-events-only"></a>

If the buffer cannot hold even the first queued event, `read()` fails
with `EINVAL` — the buffer is too small to make progress, and the caller
has to try again with a larger one. <a id="cite-watch.record.buffer-too-small-is-einval"></a>

On an armed fd with an empty queue, `read()` blocks, or returns
`EAGAIN` under `O_NONBLOCK`. <a id="cite-watch.record.empty-queue-blocks-or-eagain"></a>

Only events that were copied out in full are dequeued. <a id="cite-watch.record.only-fully-copied-events-dequeued"></a>

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

## Layout

Every record begins with the same four fields. <a id="cite-watch.record.common-header-fields"></a>

| Offset | Size | Field |
|---|---|---|
| 0 | 4 | `total_len` |
| 4 | 2 | `event_type` |
| 6 | 2 | `name_len` |
| 8 | `name_len` | `name`, UTF-8 |

All integers are little-endian. <a id="cite-watch.record.integers-are-little-endian"></a>

`total_len` is the whole record including this header; it is how a
consumer advances to the next event, and it is the only safe way to do
so. <a id="cite-watch.record.total-len-covers-whole-record"></a>

A subtree watch's records carry additional fields after the name,
locating the key the change happened on relative to the watched key: <a id="cite-watch.record.subtree-records-carry-relative-path"></a>

| Size | Field |
|---|---|
| 2 | `path_depth` |
| `2 + n` each | `path_components`: `len` (u16) then that many UTF-8 bytes |

`path_depth` is the number of components from the watched key down to
the changed key; zero means the change was on the watched key itself. <a id="cite-watch.record.path-depth-counts-from-watched-key"></a>

The components are length-prefixed rather than joined with a separator,
because registry names can contain any Unicode character and value
names can contain backslashes — a concatenated path string would be
ambiguous. <a id="cite-watch.record.path-components-are-length-prefixed"></a>

The header offsets are ABI, named in `include/uapi/pkm/lcs.h` and listed in
[LCS ABI Reference](</kernel/userspace/native/lcs/generated-syscall-and-common-abi.md#trm-5-a>).

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

## Not every record on a subtree watch has a path

`OVERFLOW` records are emitted in the bare eight-byte form, on every
watch, whether or not that watch is a subtree watch. <a id="cite-watch.record.overflow-is-always-the-bare-form"></a>

`KEY_DELETED` is not: a subtree watcher receives it in the subtree
form, with a `path_depth` of its own. <a id="cite-watch.record.key-deleted-uses-the-subtree-form"></a>

A consumer of a subtree watch therefore cannot assume the subtree
fields are present on every record it reads. `total_len` is the cursor;
`path_depth` is read only when the record is long enough to hold it.

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

## Length limits

`name_len` and each component length are 16-bit. <a id="cite-watch.record.length-fields-are-16-bit"></a>

If an event's name or one of its path components is too long to be
represented, LCS does not emit a truncated or malformed record: it
substitutes or preserves an `OVERFLOW` for that watcher instead, which
is a statement the consumer already knows how to act on. <a id="cite-watch.record.unrepresentable-length-becomes-overflow"></a>

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

## Forward compatibility <a id="cite-watch.record.appended-fields-are-skipped-by-total-len"></a>

Future versions may append fields after `path_components`. An existing
consumer skips them, because it advances by `total_len`; a newer one
compares `total_len` against what it has parsed to discover whether the
optional fields are present. This is the whole extension mechanism, and
it is why the length field comes first.

---

# Dispatch

_Peios Kernel / Internals / LCS / Watches_

> Given a mutation, which armed watches hear about it — computed from object identity and ancestry, with depth, batching and recovery.

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

Dispatch answers one question: given a mutation on a key, which armed
watches hear about it? The answer is computed from object identity and
from ancestry captured at open time, never from a path string resolved
at the moment of the event. <a id="cite-watch.dispatch.computed-from-identity-and-captured-ancestry"></a>

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

## A watch is bound to an object

A watch is registered against the GUID on the fd it was armed through.
It fires for changes to *that object*. <a id="cite-watch.dispatch.registered-against-the-fd-guid"></a>

If a layer change causes a different key to become visible at the same
path, the watch does not move: the new key is a different object with a
different GUID, and nothing about the old watch refers to a name. <a id="cite-watch.dispatch.watch-does-not-follow-the-path"></a>

To follow the path rather than the object, a process detects the change
— through `KEY_DELETED` on the old object, or a subtree watch on the
parent — re-opens the path, and arms a new watch. This is the fd model
applied consistently: an fd is a capability bound to one identity.

The converse also holds. If a watched key is hidden, `KEY_DELETED` is
delivered, but the watch is not removed. <a id="cite-watch.dispatch.hiding-keeps-the-watch-armed"></a>

Should the hiding layer later be deleted, the key reappears at its
original path with the same GUID, and events resume. <a id="cite-watch.dispatch.events-resume-when-the-key-reappears"></a>
There is no re-emergence event; the watcher simply observes the key
being active again. <a id="cite-watch.dispatch.no-re-emergence-event"></a>

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

## The ancestor chain

Subtree dispatch needs to know where a key sits in the tree, and it
learns that once, at open.

Resolving a path walks it component by component, and the GUID at each
level is retained on the resulting fd as the **ancestor chain** —
root GUID through parent GUID to the key itself. <a id="cite-watch.dispatch.ancestor-chain-captured-at-open"></a>
It costs nothing extra: the walk had to resolve those components
anyway.

A relative open copies the parent fd's chain and extends it with the
components the relative walk resolved. <a id="cite-watch.dispatch.relative-open-extends-the-parent-chain"></a>

An open that followed a symlink records the chain of the *resolved*
path, so the fd's ancestry reflects the target's real position in the
tree, not the link's. <a id="cite-watch.dispatch.symlink-open-records-the-resolved-chain"></a>

Dispatch uses that captured chain and never re-resolves it. If an
ancestor in the chain is later hidden, deleted, orphaned, or replaced
at the same path by a different key, watches on the original ancestor
GUID still receive subtree events from descendants mutated through fds
opened through that chain. <a id="cite-watch.dispatch.stale-ancestor-still-receives-subtree-events"></a>

Watches on a new key that later appears at the same path receive
nothing from the old one. <a id="cite-watch.dispatch.new-key-at-the-same-path-receives-nothing"></a>

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

## The algorithm

Two structures back dispatch. The **watch map** is a hash map from GUID
to the watchers armed on it. The **subtree watch set** is a refcounted
hash set of the GUIDs that have at least one subtree watch, maintained
as watches are armed, re-armed, disarmed and closed.

For a mutation on key *B*, with *B*'s ancestor chain in hand:

1. Look up *B*'s GUID in the watch map and queue the event, with
   `path_depth` 0, to every watcher whose filter admits it. <a id="cite-watch.dispatch.direct-watchers-receive-depth-zero"></a>
2. Walk the ancestor chain outward from *B*'s parent. At each ancestor,
   skip it unless it is in the subtree watch set — that test is what
   makes the walk cheap. For an ancestor that is, queue the event to
   each of its watchers that armed with the subtree flag and whose
   filter admits it, with the path from that ancestor down to *B*. <a id="cite-watch.dispatch.subtree-watchers-receive-the-relative-path"></a>

The cost is O(depth) hash lookups, with no RSI round trips, no trie and
no string comparison. <a id="cite-watch.dispatch.costs-o-depth-hash-lookups-and-no-source-io"></a>
The path components handed to a subtree watcher are sliced out of the
resolved path already stored on the mutating fd.

Dispatch runs under a single global registry lock, so it is serialised
across the whole system rather than per hive or per source.

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

## Depth

`MaxSubtreeWatchDepth` bounds how far below a watched key a subtree
watch is told about. The default is 0, meaning unlimited. <a id="cite-watch.dispatch.depth-zero-means-unlimited"></a>

A non-zero value suppresses events whose path is longer than it,
limiting both noise and dispatch cost for a watch armed high in a
tree. <a id="cite-watch.dispatch.depth-limit-suppresses-deeper-events"></a>

The limit applies to watches held by userspace. LCS's own internal
watches are collected before the depth test and are not subject to it
([The Self-Watch](</kernel/internals/lcs/bootstrap/the-self-watch.md#trm-5-10-4>)).

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

## Transaction batches

Nothing inside an uncommitted transaction dispatches. <a id="cite-watch.dispatch.uncommitted-transaction-dispatches-nothing"></a>

At commit, and only when the source reports success, the transaction's
mutation log is walked in operation order and the whole set of events
is queued as one batch, under a single hold of the registry lock, so no
other operation interleaves with it. <a id="cite-watch.dispatch.commit-batch-queued-in-operation-order-without-interleaving"></a>

An aborted or failed transaction dispatches nothing and its log is
released. A transaction that timed out after its commit was dispatched
keeps its log, and a late `RSI_OK` still emits the batch ([Commit and Failure](</kernel/internals/lcs/transactions/commit-and-failure.md#trm-5-7-3>)).

A large transaction — a role installation writing thousands of values —
could otherwise fill a watcher's queue atomically. So the batch is
counted per watcher first: any watcher whose share exceeds
`MaxTransactionWatchEventBurst`, default 4096, receives exactly one
`OVERFLOW` and none of its individual events. <a id="cite-watch.dispatch.burst-cap-replaces-a-watchers-batch-with-one-overflow"></a>

That `OVERFLOW` is queued ahead of the batch, so it arrives before
whatever else that watcher is still owed. <a id="cite-watch.dispatch.burst-overflow-queued-ahead-of-the-batch"></a>

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

## Recovery dispatch

Some changes alter effective state for keys whose fds nobody holds and
whose descendants the kernel is retaining no context for. Deleting a
layer, changing its precedence, enabling or disabling it, and restoring
a subtree from a stream are all of this kind. <a id="cite-watch.dispatch.recovery-triggering-operations"></a>
Computing an exact diff would mean walking arbitrary parts of the tree
through the source.

LCS does not attempt it. It increments the generation number of every
hive the affected source backs and then queues a no-name `OVERFLOW` to
every armed watch on that source, which is the notification for those
changes. <a id="cite-watch.dispatch.recovery-bumps-generation-and-queues-overflow"></a>
The watcher re-reads, and can compare the generation number it last saw
against the current one ([Key Ioctls](</kernel/userspace/native/lcs/key-ioctls.md#trm-5-5-3>)) to tell whether an *ordinary* write
happened in between; after a recovery it cannot, because the bump is
deliberately conservative. The kernel does not know which hives a layer
operation touched — the source's delete-layer answer names only the
keys it orphaned, and a layer holding hiding or masked entries changes
effective state without orphaning anything — so it bumps every hive
rather than risk a watcher skipping a re-read its hive needed. The
consequence is always a spurious re-read, never a missed change.
<a id="cite-watch.dispatch.recovery-generation-bump-is-source-wide"></a>

Two properties of this delivery are worth stating. It is object-
semantic like every other dispatch — it walks the watch map, resolves
no paths — and it bypasses the filter, because `OVERFLOW` always does.
It does not disarm anything. <a id="cite-watch.dispatch.recovery-does-not-disarm"></a>

The scope is the **source**, not the hive. A source backing several
hives delivers `OVERFLOW` to watches on all of them, including hives
the operation did not touch, and bumps all of their generation
counters. <a id="cite-watch.dispatch.recovery-scope-is-the-source-not-the-hive"></a>
The generation counters are maintained per hive for ordinary writes;
recovery treats the source as the unit.

For a restore, recovery is published only after the source commit
succeeds. A restore that fails or aborts before commit emits nothing. <a id="cite-watch.dispatch.restore-recovery-published-only-after-commit"></a>

<a id="trm-5-6-3-7"></a>

## Source restart

When a source disconnects, watches stay armed and nothing is delivered;
operations needing the source return `EIO`. <a id="cite-watch.dispatch.disconnect-keeps-watches-armed-and-silent"></a>

`OVERFLOW` arrives on **re-registration**, not on disconnect, which is
the only ordering that works: a watcher told to re-read needs the
source to be there when it does. <a id="cite-watch.dispatch.overflow-arrives-on-re-registration"></a>

Existing fds resume without re-opening, and no watcher has to
re-arm. <a id="cite-watch.dispatch.fds-resume-without-re-arming"></a>

---

# Queues and Overflow

_Peios Kernel / Internals / LCS / Watches_

> Each armed fd has its own bounded queue and delivery is best-effort — what a full queue does, and what a watcher does about it.

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

Each armed fd has its own event queue, bounded by
`NotificationQueueSize` — default 256 events, configurable between 16
and 65536 ([Operational Parameters](</kernel/internals/lcs/bootstrap/operational-parameters.md#trm-5-10-3>)). <a id="cite-watch.overflow.each-fd-has-its-own-bounded-queue"></a>

Delivery is best-effort. A watcher that reads promptly sees every
change; one that falls behind is told that it has, rather than being
given a partial history it cannot distinguish from a complete one. <a id="cite-watch.overflow.delivery-is-best-effort"></a>

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

## What happens when the queue is full

When an event arrives for a full queue and no `OVERFLOW` is present:

1. The oldest queued event is dropped. <a id="cite-watch.overflow.full-queue-drops-the-oldest-event"></a>
2. An `OVERFLOW` record is queued in its place. <a id="cite-watch.overflow.full-queue-queues-an-overflow"></a>
3. The event that triggered this is **discarded**, not queued. <a id="cite-watch.overflow.triggering-event-is-discarded"></a>

Once an `OVERFLOW` is in the queue, subsequent events queue normally:
the oldest non-`OVERFLOW` event is dropped to make room and the new
event is added, so the single `OVERFLOW` is preserved and the queue
continues to carry the most recent history behind it. <a id="cite-watch.overflow.later-events-drop-the-oldest-and-preserve-the-overflow"></a>

A queue therefore holds at most one `OVERFLOW` at a time, and that is
an enforced invariant rather than a convention — an attempt to queue a
second is rejected as a bug. <a id="cite-watch.overflow.at-most-one-overflow-per-queue"></a>

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

## What a watcher does about it

`OVERFLOW` means the record it has is incomplete. There is no way to
learn what was dropped, and no attempt is made to describe it. <a id="cite-watch.overflow.dropped-events-are-not-described"></a>

The watcher re-reads the watched key, and its subtree if the watch is a
subtree watch, and continues from the state it finds. Events after the
`OVERFLOW` are complete again. <a id="cite-watch.overflow.events-after-an-overflow-are-complete"></a>

`REG_IOC_QUERY_KEY_INFO` reports a per-hive generation number
([Key Ioctls](</kernel/userspace/native/lcs/key-ioctls.md#trm-5-5-3>)) that makes this cheaper than it sounds: a watcher that
recorded the generation at its last full read can compare it with the
current one and skip the re-read entirely if nothing committed in
between.

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

## Memory

There is no registry-specific global cap on watch memory, and none is
needed. A watch costs at most `NotificationQueueSize` queued events, a
watch requires an fd, and a process holds at most `RLIMIT_NOFILE` fds.
The product of the two is the bound, and it is enforced by machinery
that already exists. <a id="cite-watch.overflow.no-global-cap-beyond-queue-size-times-fd-limit"></a>

The same reasoning covers open key state: per-fd overhead — GUID,
granted mask, ancestor chain, watch state — multiplied by the fd limit.

LCS's own internal watches are outside this. They are delivered
synchronously through a kernel callback rather than queued, so the
queue limit does not apply to them ([The Self-Watch](</kernel/internals/lcs/bootstrap/the-self-watch.md#trm-5-10-4>)).
