Events
Single-page view · as markdown
Events Overview
Peios / Developing for Peios / Events
KMES is Peios's event system, and it is the sole event path on the system.
Audit records, subsystem events, and your own application events all travel
the same way: the kernel stamps each event with trusted metadata and writes it
into a per-CPU, lock-free ring buffer, and consumers drain those rings. This
section teaches both sides — producing and consuming — through
event.h and
msgpack.h.
What an event is #
An event has two parts:
- Kernel-stamped metadata you cannot forge — a
CLOCK_REALTIMEtimestamp, a per-CPU monotonic sequence number, the CPU id, an origin class, and identity GUIDs (the effective token, the true token, and the process). This is the trustworthy skeleton: when you consume an event, you know who emitted it and when, because the kernel wrote that, not the emitter. - A payload — a single MessagePack value that you define. This is your event's actual content.
The event type names the kind of event. It's a dotted name made of your
package name, what the event is about, and what happened, such as
org.example.backup.snapshot.created. Its fields follow one vocabulary shared
by every emitter on the system.
Naming and Shaping Events
explains how to choose both.
Payloads are MessagePack, and you own them #
The kernel does not build or interpret payloads — it only structurally
validates them on emit (one well-formed MessagePack value, within size and
nesting limits). So userspace owns encoding and decoding, and the SDK ships a
MessagePack codec whose
validator's acceptance is matched to the kernel's check. Build a payload with
the writer, and a successful peios_mp_writer_bytes (or peios_mp_validate)
establishes structural validity. Emission still checks size limits,
permissions, rate limits, and the other requirements of the event interface.
Per-CPU rings and lost events #
Events live in per-CPU ring buffers — one ring per logical CPU, lock-free so producers never block on consumers. Two consequences shape how you consume:
- You drain per CPU. To see everything, run a reader per CPU (discover the count by attaching upward from CPU 0 until it fails).
- Rings can lap. If you don't drain fast enough, new events overwrite old
ones you haven't read. The per-CPU
sequencenumbers are contiguous, so a gap in the sequence means events were lost — and the reader tracks that count for you.
Privileges #
The two sides are gated separately:
- Emitting requires
SeAuditPrivilege. - Consuming (attaching to a ring) requires
SeSecurityPrivilege.
Two ways to consume #
The SDK offers a high-level reader that hides the entire lock-free drain —
barriers, lapping recovery, lost-event accounting, buffer-resize handling, and
the wait — behind a simple next/wait loop. That's what almost everyone
should use. There is also a low-level ring API for callers who need to
drive the drain inside their own event loop. Both are covered in consuming
events.
Where to go in this section #
- Naming and Shaping Events — design the type, fields, tier, and catalog entry before emitting it.
- Emitting events — build a payload and emit individual events or batches.
- Consuming events — drain the rings with the high-level reader (and, briefly, the low-level ring).
event.handmsgpack.h— the exhaustive reference.
Naming and Shaping Events
Peios / Developing for Peios / Events
Design an event around an occurrence an operator needs to identify, query, or investigate. A shared naming scheme and field vocabulary let the same filters and access policies work across components and language SDKs.
The example is a backup package named org.example.backup. It records each
attempt to create a snapshot archive. The
event specification owns the
rules; this guide applies them to an emitter's design.
Before you start #
- Identify the package that owns the event and the operation it describes.
- Inspect the installed event catalog with
evmanfrom Peiosutils. - Identify which facts your component observes and which it receives as claims.
Choose an event rather than a log or metric #
- Ask whether an operator would act on the information. Developer narrative belongs in a log.
- Ask whether one occurrence matters by itself. If only the trend matters, publish a metric instead.
A failed snapshot matters individually, so the backup attempt is an event. The daily amount of backed-up data is a metric. A trace of internal function calls is developer logging. See Event Classification and Tiers.
Name the operation #
-
Start with the owning package name.
-
Add nouns from general to specific where the grouping supports a useful filter or policy boundary.
-
End with a past-tense description of the operation:
org.example.backup.snapshot.created
Use one type for success and failure. A failed creation still uses this type,
with outcome.success = false; do not add a parallel snapshot.failed type.
Use lowercase kebab-case segments, such as copied-up. Short platform roots,
such as kacs, are reserved. Package-name roots and the remaining segments
have their own grammar in Event Types.
Reuse the field vocabulary #
-
Search existing definitions before adding fields:
-
Choose fields by their role:
subjectfor who acted,objectfor what was acted on,sourceanddestinationfor endpoints, andoutcomefor the result. -
If no existing field has the required meaning, define a field beneath the owning package name and its role.
The snapshot uses shared fields plus one package-owned identifier:
| Field | Meaning in the snapshot event |
|---|---|
object.kind | file |
object.file.path | Archive path |
object.file.size | Archive size in bytes, present on success |
object.org.example.backup.snapshot.id | Stable snapshot identifier |
operation.duration | Elapsed nanoseconds |
outcome.success | Whether creation succeeded |
outcome.reason | A declared reason when it failed |
outcome.errno | Negative error number when applicable |
The package owns object.org.example.backup.snapshot.id; it references the
other definitions rather than redefining them. If many components need the
same missing concept, propose a shared field instead of giving it several
incompatible names.
Do not duplicate the timestamp, sequence, or identity fields already stamped in the event header. Use binary security identifiers for principals rather than account names. Omit a field for which no value is available; do not substitute nil, an empty string, or zero. A real zero, such as an empty file's size, remains a meaningful value.
Match the declared wire types #
Choose the encoding from the catalog definition, not from how a value is displayed:
| Value | MessagePack encoding |
|---|---|
| Security identifier (SID) | Binary SID bytes |
| Globally unique identifier (GUID) | 16 raw bytes |
| Timestamp | Unsigned nanoseconds since the Unix epoch |
| Duration | Unsigned nanoseconds |
| Boolean | Boolean value |
| String enumeration | Declared kebab-case string |
| Numeric enumeration | Declared unsigned numeric value |
| Error number | Signed negative integer |
A numeric enumeration is not interchangeable with a string enumeration. Follow the declared field type and its list of values. See Values for the full encoding rules.
Represent dotted paths as nested maps. object.file.path means an object
map containing a file map containing a path key. A literal key named
object.file.path is not that hierarchy. The package-owned identifier has
its own nested object → org → example → backup → snapshot → id
path.
Record the outcome #
- Set
outcome.successto the result of the operation. - On failure, supply a declared
outcome.reason, such asdisk-full. - Include
outcome.errnoonly when an error number applies. Record its negative form, such as-ENOSPC.
The reason is a stable filtering value. Free-form explanation belongs in
outcome.detail when the catalog allows it; consumers should not parse that
text as a replacement for the reason. Describe required and conditional
fields in the fragment so both successful and failed attempts remain valid.
See Outcomes.
Choose the tier and apply policy #
Use standard for ordinary operational records, including this snapshot.
Use verbose for investigation detail and debug for developer detail;
those tiers are off by default. Reserve essential for rare, critical
occurrences or events already governed by their own configuration, such as
access auditing. Essential does not mean that every program's diagnostics
are unconditionally important.
Emission policy is rooted at Machine\Generic\Events, with one key per
segment. This package's subtree is
Machine\Generic\Events\org\example\backup. Check policy before building
and emitting a nonessential record. Consumer-side filtering does not replace
that decision. Read Emission Policy
for inheritance, failure handling, and interactions with other audit controls.
Publish the definition and check the result #
- Describe the event and package-owned field in an
.evmanfragment. - Specify the tier and each field's required, optional, or conditional presence.
- Lint it with the intended catalog and test actual encoded events against it.
- Include the fragment in the package alongside the emitter.
Writing evman Pages contains the matching snapshot fragment and the validation workflow. Keep it as the format example rather than maintaining a second copy here. Emitting Events builds the corresponding payload with the C SDK and explains individual and batch submission.
A well-formed MessagePack value is not necessarily a catalog-conforming event. Check that successful and failed fixtures contain every required field with the declared type, that absent values are omitted, and that queries can reach the nested paths. A successful encoding or emission call does not prove those semantic properties.
If your daemon guards access to its own objects, pass an audit context to the kernel access check instead of inventing a competing access-denial event. Access Decisions explains how the descriptor and audit policy control those records.
Emitting Events
Peios / Developing for Peios / Events
Use the C SDK to encode an event payload and submit it to the kernel. Choose the type and its catalog definition first; the example follows Naming and Shaping Events. The event and MessagePack headers define the complete API.
Before you start #
- Install matching Peios SDK headers and libraries.
- Run emission calls on a Peios kernel with
SeAuditPrivilegeavailable as required by the access policy. - Install the matching
.evmanfragment and select the declared tier. - Include
<peios.h>,<errno.h>,<stdint.h>, and<string.h>in the example's translation unit.
Check emission policy #
- Open a
peios_event_policyhandle at startup and handle allocation failure. - Before constructing a payload, call
peios_event_policy_enabledwith its type name and declared tier. - If the result is
0, skip the event. If it is-1, handle the failure according to the policy interface rather than treating it as permission. - Close the handle when the emitter shuts down.
The handle caches decisions and watches registry changes. Its check does not make a later emit operation atomic with a policy update. Essential types are always on at this layer; their own audit or reporting controls still apply. See Emission Policy.
Build a complete payload #
The following helper builds a successful snapshot event matching the fragment in Writing evman Pages. Supply a valid UTF-8 archive path, a 16-byte snapshot identifier, the archive size, and the elapsed nanoseconds. The helper returns an owned writer that the caller must free.
static peios_mp_writer *
A map count is the number of key/value pairs. A dotted catalog path becomes
a chain of nested maps, including each segment of the package-owned field.
Writer errors are sticky: check peios_mp_writer_bytes before using its
result.
Structural validation does not check catalog meaning or guarantee emission.
For a failed snapshot, keep the same type and identifier. Omit the unknown
archive size, write outcome.success = false, and include a declared reason.
Add a negative outcome.errno when one applies. Adjust the file and
outcome map counts to match the fields actually written. Do not append a
second outcome map or another top-level value to an already completed payload.
Submit and release the payload #
After a successful policy check, call the helper and submit its bytes:
static int
The bytes are borrowed from the writer until it is changed or freed. The submission copies them before returning. The length-counted UTF-8 type is nonempty; the terminating NUL is not part of the name on the wire.
Handle emission errors, including invalid input, insufficient privilege, oversized payloads, and rate limiting. A successful encoding does not bypass those checks. On success, the kernel supplies trusted header metadata and marks the origin as userspace. Your payload remains the emitter's assertion.
Batch high-rate events #
peios_event_emit_batch accepts an array of peios_event_entry values and
reports the accepted prefix through its emitted output. Count is bounded by
KMES_BATCH_MAX_ENTRIES and cannot be zero.
If an entry fails, earlier entries can already have been emitted. Do not
replay that prefix as though the batch were a transaction. Rate-limit refusal
is the special all-or-nothing case: EAGAIN accepts no entries in that batch.
Keep all names and payload buffers valid until the call returns.
See Batch Emit for the complete signature and error contract. Shared timestamp capture and wakeup work make batching useful when the application naturally has multiple events ready; avoid delaying important events merely to fill a batch.
Check the result #
- Decode a portable fixture and verify its field paths and wire types against the catalog, including the required snapshot identifier.
- Test successful and failed operation payloads separately.
- In a permitted Peios test environment, confirm policy-controlled omission, emission results, and the record observed by a consumer.
Consuming Events explains the read side. A codec test on another kernel verifies encoding only, not Peios emission or identity stamping.
Consuming Events
Peios / Developing for Peios / Events
Consuming events means draining the per-CPU ring buffers. The SDK's high-level
reader hides all the hard parts, so most consumers are a short loop. This
guide shows that loop and how to parse what you read;
event.h has the full API.
Consuming requires SeSecurityPrivilege.
The reader loop #
Open a reader for a CPU, then loop next/wait:
peios_event_reader *r = ;
if
for
;
peios_event_reader_next returns 1 (event filled), 0 (nothing available —
call wait), or -1 (error). peios_event_reader_wait blocks until events
arrive or the timeout elapses (negative = forever). The reader handles the
memory barriers, lapping recovery, buffer-resize handling, and futex wait
internally — you alternate the two calls.
Parsing an event #
Each struct peios_event gives you the trusted metadata by value and the
payload as a MessagePack value. Parse it with a
reader:
void
The lifetime rule #
In libpeios 0.5.12 and later, ev->event_type and ev->payload point
into a private reader snapshot. Kernel overwrites cannot change those
bytes. The pointers remain valid until the next read or reader closure.
Copy anything you need to retain beyond that lifetime.
Draining every CPU #
Rings are per-CPU, so one reader sees only one CPU's events. To consume the whole machine, run a reader per CPU — typically one thread each. Discover the CPU count by attaching upward until it fails:
uint32_t ncpu = 0;
for
/* now spawn one peios_event_reader per cpu in [0, ncpu) */
Watching for loss #
If a consumer falls behind, the producer laps it and events are lost. Poll
peios_event_reader_lost
to see the cumulative count of lost events (derived from sequence gaps). A
rising number means you aren't draining fast enough — process events more
cheaply, hand off to a worker, or accept the loss deliberately.
The low-level ring #
If the reader's loop doesn't fit your event model — you want the ring
integrated into an existing epoll/state-machine loop, driving the read
position yourself — the low-level ring
API exposes the
mapping directly: peios_event_ring_map, the position accessors
(write_pos/tail_pos/generation), peios_event_ring_event_at to parse a
slot, and peios_event_ring_wait to sleep. It's more bookkeeping (you own the
read position and the empty/lapping/generation checks) for more control. Reach
for it only when you need to; the high-level reader is the right default.
Next #
event.hreference — the full reader and ring APIs, and everystruct peios_eventfield.- Auditing — the operator-side view of the event and audit stream.
Rust Query Clients
Peios / Developing for Peios / Events
The eventd-client Rust crate provides query framing and client lifecycle
handling. It shares access-right constants with the daemon so that clients
can describe policy without implementing the authorization decision.
The default access feature includes the local access-policy helpers.
Query-only consumers can turn off default features without changing the
server's authorization of their queries.
Finite queries #
query returns the complete result after the server's terminal response.
A server error discards the accumulated initial records. The call blocks,
so a graphical client must keep it off its interface thread.
The result is a vector in client memory. Server resource limits do not make that client allocation a fixed-size buffer. Choose bounded queries or use the wire interface when an application needs a different storage strategy.
wire::Connection::bounded(stream, max_frame_bytes) rejects an oversized
response-frame length before reserving its body. A rejected frame ends the
connection. Reconnect instead of trying to skip the body. The bound applies
to encoded frame bytes; decoded values and retained result collections need
separate memory bounds. Connection::new retains its protocol-sized bound.
Streaming queries #
Tail reads a STREAM query on a worker thread. It reports the complete
initial result, live batches, and the reason the stream ended. Dropping the
handle shuts down the connection and releases the receiving channel.
The channel capacity bounds queued reports, not their total bytes. A client that stops consuming reports eventually stops reading the socket, and the server can disconnect it. A client must handle that end state; reconnecting does not provide a resume cursor.
Query text and policy #
Use the crate's text helpers to quote values when constructing queries.
Do not concatenate untrusted strings as query syntax.
The access module can describe relevant registry policy to a person.
Only eventd, using kernel access checks and the socket peer token,
authorizes a query. A client's policy preview cannot replace that check.
See the manual's client library reference for lifecycle and wire details.