Watches
Single-page view · as markdown
Watches
Peios Kernel / Internals / LCS / Watches
Use these articles to understand watches in the Peios kernel.
The Watch Model
Peios Kernel / Internals / LCS / Watches
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.
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.
Each fd carries at most one watch.
Arming an already-armed fd replaces the filter and the subtree setting and leaves queued events in place.
Arming with a filter of zero disarms: the watch is removed and every pending event is discarded. 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).
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.
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). 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 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.
Only committed state is observable. Operations inside an uncommitted transaction produce nothing; the whole set fires at commit (Dispatch).
Event types #
VALUE_SET fires when a value is written, and when a tombstone or
blanket tombstone is removed and a lower-precedence value surfaces.
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.
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.
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.
Filters #
The filter selects event categories, not individual event types.
| Filter bit | Value | Admits |
|---|---|---|
REG_NOTIFY_VALUE | 0x01 | VALUE_SET, VALUE_DELETED |
REG_NOTIFY_SUBKEY | 0x02 | SUBKEY_CREATED, SUBKEY_DELETED |
REG_NOTIFY_SD | 0x04 | SD_CHANGED |
REG_NOTIFY_ALL | 0x07 | all three of the above |
KEY_DELETED and OVERFLOW are delivered unconditionally. They are
not in any category and no filter suppresses them.
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 subtree flag other than 0 or 1, or a non-zero padding byte in the argument structure, is rejected the same way.
Blanket tombstones #
A watcher never learns that a blanket tombstone exists.
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.
The per-value view is the only view.
Event Records
Peios Kernel / Internals / LCS / Watches
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.
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.
On an armed fd with an empty queue, read() blocks, or returns
EAGAIN under O_NONBLOCK.
Only events that were copied out in full are dequeued.
Layout #
Every record begins with the same four fields.
| 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.
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 subtree watch's records carry additional fields after the name, locating the key the change happened on relative to the watched key:
| 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.
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.
The header offsets are ABI, named in include/uapi/pkm/lcs.h and listed in
LCS ABI Reference.
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.
KEY_DELETED is not: a subtree watcher receives it in the subtree
form, with a path_depth of its own.
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.
Length limits #
name_len and each component length are 16-bit.
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.
Forward compatibility #
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
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 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.
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.
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.
Should the hiding layer later be deleted, the key reappears at its original path with the same GUID, and events resume. There is no re-emergence event; the watcher simply observes the key being active again.
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. 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.
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.
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.
Watches on a new key that later appears at the same path receive nothing from the old one.
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:
- Look up B's GUID in the watch map and queue the event, with
path_depth0, to every watcher whose filter admits it. - 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.
The cost is O(depth) hash lookups, with no RSI round trips, no trie and no string comparison. 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.
Depth #
MaxSubtreeWatchDepth bounds how far below a watched key a subtree
watch is told about. The default is 0, meaning unlimited.
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.
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).
Transaction batches #
Nothing inside an uncommitted transaction dispatches.
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.
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).
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.
That OVERFLOW is queued ahead of the batch, so it arrives before
whatever else that watcher is still owed.
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. 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.
The watcher re-reads, and can compare the generation number it last saw
against the current one (Key Ioctls) 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.
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.
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.
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.
Source restart #
When a source disconnects, watches stay armed and nothing is delivered;
operations needing the source return EIO.
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.
Existing fds resume without re-opening, and no watcher has to re-arm.
Queues and Overflow
Peios Kernel / Internals / LCS / Watches
Each armed fd has its own event queue, bounded by
NotificationQueueSize — default 256 events, configurable between 16
and 65536 (Operational Parameters).
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.
What happens when the queue is full #
When an event arrives for a full queue and no OVERFLOW is present:
- The oldest queued event is dropped.
- An
OVERFLOWrecord is queued in its place. - The event that triggered this is discarded, not queued.
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 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.
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.
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.
REG_IOC_QUERY_KEY_INFO reports a per-hive generation number
(Key Ioctls) 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.
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.
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).