# What Is the Runtime Event Log in Apache Maka and Why Is It the Semantic Source of Truth?

> Discover the Apache Maka Runtime Event Log. This immutable ledger is the semantic source of truth for agent execution, ensuring consistent state and crash recovery for all system components.

- Repository: [The Apache Software Foundation/maka](https://github.com/apache/maka)
- Tags: deep-dive
- Published: 2026-08-26

---

**The Runtime Event Log in Apache Maka is an immutable, ordered ledger of canonical facts that serves as the single semantic source of truth for all agent execution state, enabling every system component to rebuild a consistent, crash-recoverable view of any interaction.**

The Runtime Event Log is the foundational data structure in the Apache Maka repository that records every interaction during an agent's execution lifecycle. Unlike traditional state management that mutates in-place records, Maka adopts a log-first architecture where all higher-level views—including UI state, model history, and recovery logic—are derived by projecting over this append-only ledger. This design ensures that every component operates from a consistent, reproducible record of what actually happened during a run.

## What Is the Runtime Event Log?

The Runtime Event Log is a single, ordered ledger of canonical **facts** that describes everything an agent does during execution. According to the architecture documentation in [`docs/architecture/runtime-core-architecture-draft.md`](https://github.com/apache/maka/blob/main/docs/architecture/runtime-core-architecture-draft.md), this includes user messages, model-generated text, tool calls, tool results, permission actions, usage information, and terminal outcomes.

Each entry in the log is a `RuntimeEvent` defined in [`packages/core/src/runtime-event.ts`](https://github.com/apache/maka/blob/main/packages/core/src/runtime-event.ts). These events are immutable—once written, they are never modified. This immutability allows the system to treat the log as a complete, auditable history that can be replayed or inspected without ambiguity.

## Why the Runtime Event Log Is the Semantic Source of Truth

### Single Source of Truth Through Event Sourcing

All higher-level state in Maka is derived by **projecting** over the immutable Runtime Event Log. The UI view, the model-history projector, the run-state, and recovery logic do not maintain independent authoritative state; instead, they consume the log to build their specific representations. Because the log never mutates past entries, every consumer can rebuild a consistent view of the system at any point in time. This mirrors the "log-first" principle used in event-sourcing systems such as Kafka and database write-ahead logs (WALs).

### Semantic Ordering and Identity Guarantees

Each `RuntimeEvent` carries explicit ordering metadata that establishes a total order of "what actually happened." Every event includes:
- A timestamp (`ts`) and sequence number (`event_seq`)
- Identity fields: `sessionId`, `runId`, `turnId`, and `invocationId`

This guarantees that projections can reconstruct the exact sequence of interactions without timing ambiguity, ensuring that model history and UI state remain synchronized.

### Durability and Crash Recovery

The Runtime Event Log is persisted in SQLite within the `runtime_events` table, as implemented in [`packages/storage/src/agent-run-store.ts`](https://github.com/apache/maka/blob/main/packages/storage/src/agent-run-store.ts). This durability ensures the log survives process crashes. During recovery, the system scans the ledger in [`packages/runtime/src/agent-run.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/agent-run.ts), verifies terminal facts, and reconstructs the exact interaction state. A restart never loses the semantics of the previous execution because the canonical facts remain intact in the database.

### Separation of Concerns

UI-oriented `SessionEvent`s, `StoredMessage`s, and `AgentRunStore` rows are **projections** built from the log. They are not authoritative and can be rebuilt from the `RuntimeEvent` ledger whenever needed. This architectural choice prevents divergent truth sources and simplifies reasoning about state changes, as implemented in [`packages/runtime/src/session-event-runtime-mapper.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/session-event-runtime-mapper.ts).

### Explicit Terminal Invariants

A run is considered finished only when a *terminal* `RuntimeEvent` is recorded with a status of `completed`, `failed`, `aborted`, or `cancelled`. The log-first invariant enforced in [`packages/runtime/src/runtime-kernel.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/runtime-kernel.ts) guarantees that a terminal run header cannot exist without a matching terminal fact in the ledger. This eliminates ambiguous "running forever" states and ensures that recovery logic can definitively determine whether an execution concluded successfully.

## How the Runtime Event Log Works in Practice

The production path through the runtime illustrates how the log functions as the central nervous system:

1. **Emission** – The model-tool loop in [`packages/runtime/src/ai-sdk-backend.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/ai-sdk-backend.ts) emits `SessionEvent`s as the agent executes.
2. **Translation** – The [`session-event-runtime-mapper.ts`](https://github.com/apache/maka/blob/main/session-event-runtime-mapper.ts) translates these legacy events into canonical `RuntimeEvent`s.
3. **Persistence** – `AgentRun` writes each `RuntimeEvent` to the `runtime_events` SQLite table, creating the durable ledger.
4. **Projection** – Consumers read the log to build specific views:
   - The **model-history projector** filters for non-partial, model-visible content to compose the next LLM request.
   - The **UI projection** builds the conversation view for the user interface.
   - **Recovery logic** re-examines the ledger after a crash to determine if a run completed, failed, or needs repair.

Because every consumer relies on the same ordered fact set, the Runtime Event Log remains the unambiguous semantic source of truth for all agent interactions.

## Working with Runtime Events: Code Examples

Below are minimal snippets that illustrate common interactions with the Runtime Event Log.

### Creating a Runtime Event

```typescript
import { createRuntimeEventId, RuntimeEvent } from './runtime-event';

// Example: a user-message event
const userMessage: RuntimeEvent = {
  id: createRuntimeEventId(),
  invocationId: 'inv-123',
  runId: 'run-456',
  sessionId: 'sess-789',
  turnId: 'turn-1',
  ts: Date.now(),
  partial: false,
  role: 'user',
  author: 'user',
  content: {
    kind: 'text',
    text: 'Find the failing tests in this project.',
    steering: true,
  },
};

```

### Checking Whether an Event Terminates an Invocation

```typescript
import { isTerminalRuntimeEvent } from './runtime-event';

if (isTerminalRuntimeEvent(userMessage)) {
  console.log('This event ends the run.');
}

```

### Projecting Model-History From the Log

```typescript
import { runtimeEventHasModelVisibleContent } from './runtime-event';
import { readRuntimeEvents } from './runtime-event-store'; // hypothetical API

async function buildModelHistory(runId: string) {
  const events = await readRuntimeEvents(runId);
  const visible = events
    .filter(e => !e.partial)
    .filter(runtimeEventHasModelVisibleContent);

  // Convert to provider-compatible message format
  return visible.map(e => ({
    role: e.role,
    content: e.content?.text ?? '',
  }));
}

```

### Recovering After a Crash

```typescript
import { recoverRunFromLedger } from './recovery'; // simplified API

async function recoverIfNeeded(runId: string) {
  const result = await recoverRunFromLedger(runId);
  if (result.needsRepair) {
    console.warn('Run was incomplete – applying failure state.');
  }
}

```

## Key Implementation Files

Understanding the Runtime Event Log requires familiarity with these specific source files in the Apache Maka repository:

- **[`docs/architecture/runtime-core-architecture-draft.md`](https://github.com/apache/maka/blob/main/docs/architecture/runtime-core-architecture-draft.md)** – Provides the high-level architectural rationale that establishes the Runtime Event Log as the canonical source of truth.
- **[`packages/core/src/runtime-event.ts`](https://github.com/apache/maka/blob/main/packages/core/src/runtime-event.ts)** – Defines the `RuntimeEvent` TypeScript contract, validation helpers, and utility functions including `isTerminalRuntimeEvent` and `runtimeEventHasModelVisibleContent`.
- **[`packages/runtime/src/session-event-runtime-mapper.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/session-event-runtime-mapper.ts)** – Maps legacy `SessionEvent`s to canonical `RuntimeEvent`s, ensuring the single truth source pattern is maintained.
- **[`packages/runtime/src/agent-run.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/agent-run.ts)** – Manages the durable envelope around a run and handles writing events to the ledger.
- **[`packages/runtime/src/runtime-kernel.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/runtime-kernel.ts)** – Orchestrates active execution, enforces terminal invariants, and coordinates the log-first workflow.
- **[`packages/runtime/src/ai-sdk-backend.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/ai-sdk-backend.ts)** – Implements the model-tool loop that produces the facts stored in the log.
- **[`packages/storage/src/agent-run-store.ts`](https://github.com/apache/maka/blob/main/packages/storage/src/agent-run-store.ts)** – Persists the `runtime_events` SQLite table that holds the ordered ledger.

## Summary

- The **Runtime Event Log** is an immutable, append-only ledger of canonical facts representing every action in an agent's lifecycle.
- It serves as the **single semantic source of truth**, with all other state (UI, model history, recovery) derived via projection.
- **Semantic ordering** via `event_seq`, timestamps, and identity fields ensures total ordering and reproducibility.
- **Durability** is achieved through SQLite persistence in the `runtime_events` table, enabling crash recovery without data loss.
- **Terminal invariants** prevent ambiguous run states by requiring explicit terminal events (`completed`, `failed`, `aborted`, `cancelled`) to finalize execution.

## Frequently Asked Questions

### How does the Runtime Event Log differ from traditional session storage?

Traditional session storage typically mutates records in place to reflect current state. In contrast, the Runtime Event Log never modifies existing entries; it only appends new canonical facts. This allows Maka to rebuild any historical state by replaying the log, whereas traditional storage would require complex versioning or audit trails to achieve similar reproducibility.

### What makes an event "terminal" in Maka's Runtime Event Log?

An event is terminal when its status is one of four definitive values: `completed`, `failed`, `aborted`, or `cancelled`. The `isTerminalRuntimeEvent` function in [`packages/core/src/runtime-event.ts`](https://github.com/apache/maka/blob/main/packages/core/src/runtime-event.ts) checks for these states. A run is only considered finished when such an event appears in the ledger, preventing ambiguity about whether an execution is still active.

### How does Maka ensure the Runtime Event Log survives process crashes?

The log is persisted to a SQLite database in the `runtime_events` table managed by [`packages/storage/src/agent-run-store.ts`](https://github.com/apache/maka/blob/main/packages/storage/src/agent-run-store.ts). Because writes to this table are atomic and durable, the ledger survives unexpected process termination. Upon restart, the recovery logic scans this table to reconstruct the exact state of any interrupted runs.

### Can I query the Runtime Event Log directly for debugging?

Yes, because the log is stored in SQLite, you can query the `runtime_events` table directly using standard SQL tools. Each row contains the full `RuntimeEvent` JSON along with indexing fields like `runId` and `sessionId`. This direct access allows developers to inspect the exact sequence of facts that led to a specific agent behavior or state.