# How Apache Maka Uses Event Sourcing for Agent Runtime Persistence

> Discover how Apache Maka leverages event sourcing with an immutable SQLite log to create a single source of truth for agent runtime persistence and state.

- Repository: [The Apache Software Foundation/maka](https://github.com/apache/maka)
- Tags: internals
- Published: 2026-09-12

---

**Apache Maka implements event sourcing by storing every interaction as an immutable `RuntimeEvent` in an append-only SQLite log, making the event stream the single source of truth while deriving all current state through projections.**

Apache Maka's runtime architecture treats the event log as the primary source of truth rather than maintaining mutable state. According to the [Maka Backend Architecture](https://github.com/apache/maka/blob/main/ARCHITECTURE.md), the system captures every model message, tool invocation, and permission decision as durable events that can be replayed to reconstruct any past state.

## Core Architecture of the Event-Sourced Runtime

### The Runtime Event Log

At the heart of Apache Maka's event sourcing implementation is a **single append-only event log** persisted in SQLite. The `runtime_events` table stores every occurrence as a `RuntimeEvent` structure defined in [`packages/core/src/runtime-event.ts`](https://github.com/apache/maka/blob/main/packages/core/src/runtime-event.ts). Because the log is immutable and never rewritten, the system maintains a complete audit trail of every session.

The storage layer provides atomic append operations through `SQLiteRuntimeStore` in [`packages/storage/src/sqlite-runtime-store.ts`](https://github.com/apache/maka/blob/main/packages/storage/src/sqlite-runtime-store.ts). Each event carries a monotonic `event_seq` identifier that enforces ordering and enables deterministic replay across distributed components.

### SessionManager and AgentRun Lifecycle

The **SessionManager** and **AgentRun** classes own the execution lifecycle, including turns, runs, and continuations. Rather than maintaining state in memory, these components read the immutable prefix of the log to reconstruct the current context. This approach ensures that even after a crash, the system can resume from the exact sequence of events that preceded the failure.

When generating prompts or determining the next action, the runtime queries the event log through `readRuntimeEvents`, applying each event chronologically to build an in-memory representation of the conversation state.

### Runtime Host and Projections

The **Runtime Host** acts as the sole write authority for a given state root, ensuring that all clients (Desktop, TUI, CLI, and bots) interact with a single consistent event stream. All derived views—UI panels, prompt builders, and recovery snapshots—are **projections** computed from the event log.

Because state is derived rather than stored, projections can be rebuilt at any time without data loss. This separation between the write model (event log) and read models (projections) follows classic event sourcing patterns and guarantees that all clients see a consistent history.

## Event Flow and Persistence Model

The workflow follows a strict append-only pattern:

1. **Client request** triggers the Runtime Host to create a new `RuntimeEvent` (e.g., a model message).
2. **Host appends** the event to the SQLite `runtime_events` table via `appendRuntimeEvent`.
3. **SessionManager reads** the immutable prefix to build context and generate the next prompt.
4. **Projections update** UI panels and transcript views based on the same log sequence.

```typescript
// Append a new RuntimeEvent (simplified)
import { RuntimeEvent, canonicalizeRuntimeEventForStorage } from '@maka/core/runtime-event';
import { SQLiteRuntimeStore } from '@maka/storage/sqlite-runtime-store';

async function recordModelMessage(
  store: SQLiteRuntimeStore,
  sessionId: string,
  runId: string,
  msg: string,
) {
  const event: RuntimeEvent = {
    id: crypto.randomUUID(),
    ts: Date.now(),
    type: 'modelMessage',
    payload: { text: msg },
    // …other required metadata (sessionId, turnId, etc.)
  };

  // The store ensures the event is durable and appended atomically.
  await store.appendRuntimeEvent(event);
}

```

## State Reconstruction and Crash Recovery

Apache Maka leverages the immutable event log for **deterministic replay** and crash recovery. Because each event carries a monotonic sequence number, the system can load a session's history and apply events sequentially to rebuild transcripts or resume interrupted runs.

The `decodeRuntimeEvent` function deserializes stored events, allowing the runtime to project the current state without maintaining separate state snapshots. This design also enables **multi-agent scheduling**, where child sessions emit events stored in the same log, letting the Agent Graph coordinate work without duplicating state across processes.

```typescript
// Re‑playing events to rebuild a session’s context
import { SQLiteRuntimeStore } from '@maka/storage/sqlite-runtime-store';
import { decodeRuntimeEvent } from '@maka/core/runtime-event';

async function loadSessionHistory(store: SQLiteRuntimeStore, sessionId: string, runId: string) {
  const rawEvents = await store.readRuntimeEvents(sessionId, runId);
  const events = rawEvents.map(decodeRuntimeEvent);

  // Apply each event to rebuild the in‑memory state (e.g., a transcript)
  const transcript: string[] = [];
  for (const ev of events) {
    if (ev.type === 'modelMessage') {
      transcript.push(`🧠 ${ev.payload.text}`);
    } else if (ev.type === 'toolResult') {
      transcript.push(`🔧 ${ev.payload.result}`);
    }
    // …handle other event types
  }
  return transcript;
}

```

## Summary

- **Append-only log**: Apache Maka stores all runtime interactions as immutable `RuntimeEvent` entries in SQLite, ensuring a durable, ordered history.
- **Source of truth**: The event log in `runtime_events` table is the authoritative state; all other representations are derived projections.
- **Crash resilience**: The system recovers by replaying events from the immutable prefix, guaranteeing exactly-once semantics for session restoration.
- **Multi-client consistency**: The Runtime Host serializes all writes, ensuring that Desktop, TUI, CLI, and automated agents share a consistent event stream.
- **Deterministic replay**: Monotonic `event_seq` identifiers enable reproducible session debugging and multi-agent coordination without state duplication.

## Frequently Asked Questions

### How does Apache Maka handle crash recovery without losing state?

Apache Maka recovers from crashes by loading the immutable prefix of the `runtime_events` table and replaying events sequentially. Because the event log is never modified or truncated, the system can reconstruct the exact state that existed before the crash by re-applying events through `readRuntimeEvents`. This approach eliminates the need for complex state synchronization or snapshot management.

### What makes the RuntimeEvent structure suitable for event sourcing?

The `RuntimeEvent` type defined in [`packages/core/src/runtime-event.ts`](https://github.com/apache/maka/blob/main/packages/core/src/runtime-event.ts) encapsulates every domain change as a self-contained record with a unique ID, timestamp, event type, and payload. Each event includes session metadata and a monotonic sequence number, satisfying the requirements for immutable, ordered events that can be stored via `appendRuntimeEvent` and later decoded with `decodeRuntimeEvent` for state reconstruction.

### Can multiple clients interact with the same session simultaneously?

Yes, the **Runtime Host** acts as the sole write authority for a given state root, ensuring that all clients—including Desktop, TUI, CLI, and bots—append events to the same SQLite log. Because reads are performed against the immutable event history, all clients see a consistent view of the session state without conflicts or race conditions.

### How does event sourcing benefit multi-agent workflows in Maka?

Event sourcing enables **multi-agent scheduling** by storing child session events in the same append-only log as parent sessions. The Agent Graph can schedule work across distributed processes without duplicating state, since each agent simply appends events to the shared log. This design allows deterministic replay of complex agent interactions and simplifies coordination through the monotonic `event_seq` ordering.