Peios Learn
Documentation

Peios

Peios Peios Kernel Universal Directory Project

Developer Tools

Trail Acta Provium clackatoo CAF GCSL Pekit

Applications

Framewright

Standards and Conventions

Standards and Conventions Peios Specifications
Peios

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:

  1. Kernel-stamped metadata you cannot forge — a CLOCK_REALTIME timestamp, 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.
  2. 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 sequence numbers 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.h and msgpack.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 evman from Peiosutils.
  • Identify which facts your component observes and which it receives as claims.

Choose an event rather than a log or metric #

  1. Ask whether an operator would act on the information. Developer narrative belongs in a log.
  2. 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 #

  1. Start with the owning package name.

  2. Add nouns from general to specific where the grouping supports a useful filter or policy boundary.

  3. 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 #

  1. Search existing definitions before adding fields:

    evman object.file
    evman -k snapshot
    
  2. Choose fields by their role: subject for who acted, object for what was acted on, source and destination for endpoints, and outcome for the result.

  3. 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:

FieldMeaning in the snapshot event
object.kindfile
object.file.pathArchive path
object.file.sizeArchive size in bytes, present on success
object.org.example.backup.snapshot.idStable snapshot identifier
operation.durationElapsed nanoseconds
outcome.successWhether creation succeeded
outcome.reasonA declared reason when it failed
outcome.errnoNegative 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:

ValueMessagePack encoding
Security identifier (SID)Binary SID bytes
Globally unique identifier (GUID)16 raw bytes
TimestampUnsigned nanoseconds since the Unix epoch
DurationUnsigned nanoseconds
BooleanBoolean value
String enumerationDeclared kebab-case string
Numeric enumerationDeclared unsigned numeric value
Error numberSigned 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 #

  1. Set outcome.success to the result of the operation.
  2. On failure, supply a declared outcome.reason, such as disk-full.
  3. Include outcome.errno only 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 #

  1. Describe the event and package-owned field in an .evman fragment.
  2. Specify the tier and each field's required, optional, or conditional presence.
  3. Lint it with the intended catalog and test actual encoded events against it.
  4. 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 SeAuditPrivilege available as required by the access policy.
  • Install the matching .evman fragment and select the declared tier.
  • Include <peios.h>, <errno.h>, <stdint.h>, and <string.h> in the example's translation unit.

Check emission policy #

  1. Open a peios_event_policy handle at startup and handle allocation failure.
  2. Before constructing a payload, call peios_event_policy_enabled with its type name and declared tier.
  3. 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.
  4. 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 *snapshot_payload(
    const char *path, const uint8_t snapshot_id[16],
    uint64_t size_bytes, uint64_t elapsed_ns)
{
    if (path == NULL || snapshot_id == NULL) {
        errno = EINVAL;
        return NULL;
    }
    peios_mp_writer *writer = peios_mp_writer_new();
    if (writer == NULL) return NULL;

    peios_mp_write_map(writer, 3);
    peios_mp_write_str(writer, "object", 6);
    peios_mp_write_map(writer, 3);
    peios_mp_write_str(writer, "kind", 4);
    peios_mp_write_str(writer, "file", 4);
    peios_mp_write_str(writer, "file", 4);
    peios_mp_write_map(writer, 2);
    peios_mp_write_str(writer, "path", 4);
    peios_mp_write_str(writer, path, strlen(path));
    peios_mp_write_str(writer, "size", 4);
    peios_mp_write_uint(writer, size_bytes);
    peios_mp_write_str(writer, "org", 3);
    peios_mp_write_map(writer, 1);
    peios_mp_write_str(writer, "example", 7);
    peios_mp_write_map(writer, 1);
    peios_mp_write_str(writer, "backup", 6);
    peios_mp_write_map(writer, 1);
    peios_mp_write_str(writer, "snapshot", 8);
    peios_mp_write_map(writer, 1);
    peios_mp_write_str(writer, "id", 2);
    peios_mp_write_bin(writer, snapshot_id, 16);

    peios_mp_write_str(writer, "operation", 9);
    peios_mp_write_map(writer, 1);
    peios_mp_write_str(writer, "duration", 8);
    peios_mp_write_uint(writer, elapsed_ns);
    peios_mp_write_str(writer, "outcome", 7);
    peios_mp_write_map(writer, 1);
    peios_mp_write_str(writer, "success", 7);
    peios_mp_write_bool(writer, true);

    if (peios_mp_writer_bytes(writer, NULL) < 0) {
        int saved_errno = errno;
        peios_mp_writer_free(writer);
        errno = saved_errno;
        return NULL;
    }
    return 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 emit_snapshot(const char *path, const uint8_t snapshot_id[16],
                         uint64_t size_bytes, uint64_t elapsed_ns)
{
    static const char type[] = "org.example.backup.snapshot.created";
    peios_mp_writer *writer = snapshot_payload(
        path, snapshot_id, size_bytes, elapsed_ns);
    if (writer == NULL) return -1;

    const void *payload = NULL;
    ssize_t length = peios_mp_writer_bytes(writer, &payload);
    int result = -1;
    if (length >= 0 && (uint64_t)length <= UINT32_MAX) {
        result = peios_event_emit(
            type, sizeof type - 1, payload, (uint32_t)length);
    } else if (length >= 0) {
        errno = EOVERFLOW;
    }
    int saved_errno = errno;
    peios_mp_writer_free(writer);
    errno = saved_errno;
    return result;
}

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 #

  1. Decode a portable fixture and verify its field paths and wire types against the catalog, including the required snapshot identifier.
  2. Test successful and failed operation payloads separately.
  3. 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 = peios_event_reader_open(cpu);
if (!r) { /* errno */ }

for (;;) {
    struct peios_event ev;
    int rc = peios_event_reader_next(r, &ev);
    if (rc == 1) {
        handle_event(&ev);                       /* got one */
    } else if (rc == 0) {
        peios_event_reader_wait(r, -1);          /* none right now — sleep */
    } else {
        break;                                   /* error */
    }
}
peios_event_reader_close(r);

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 handle_event(const struct peios_event *ev)
{
    /* Metadata is trustworthy — the kernel stamped it. */
    /* ev->timestamp, ev->sequence, ev->cpu_id, ev->origin_class,
       ev->process_guid, ev->effective_token_guid, ... */

    /* event_type and payload are NOT NUL-terminated — use the lengths. */
    static const char type[] = "org.example.backup.snapshot.created";

    if (ev->event_type_len == sizeof type - 1 &&
        memcmp(ev->event_type, type, sizeof type - 1) == 0) {

        struct peios_mp_reader mp;
        peios_mp_reader_init(&mp, ev->payload, ev->payload_len);

        ssize_t pairs = peios_mp_read_map(&mp);
        for (ssize_t i = 0; i < pairs; i++) {
            const char *key; ssize_t klen = peios_mp_read_str(&mp, &key);
            /* dispatch on key; read or peios_mp_skip(&mp) the value */
        }
    }
}

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 (;;) {
    uint64_t cap;
    int fd = peios_event_attach(ncpu, &cap);   /* low-level probe */
    if (fd < 0) break;                          /* EINVAL past the last CPU */
    close(fd);
    ncpu++;
}
/* 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.h reference — the full reader and ring APIs, and every struct peios_event field.
  • 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.

Peios Learn — documentation for Peios software.

Built with Trail.