How Apache Maka Ensures Session and Run State Consistency: Immutable Logs and Transactional Recovery
Apache Maka guarantees session and run state consistency by treating an immutable runtime-event log as the single source of truth, orchestrating all mutations through a transactional SessionManager, and enabling strict recovery validation that replays events to reconstruct exact state after crashes.
Apache Maka implements a robust consistency model that prevents state divergence across crashes, restarts, and concurrent clients. The architecture centers on an append-only event log and strict transactional boundaries that ensure every UI, CLI, or TUI client sees the same session and run state. This design creates multiple projections of a single immutable history rather than maintaining separate mutable state copies.
The Immutable Runtime-Event Log
At the core of Maka’s consistency guarantee is an append-only event log that records every interaction without modification. Each model message, tool call, permission decision, and turn completion is persisted as an immutable event. This log serves as the absolute source of truth for reconstructing any session or run state.
The event schema is defined in packages/runtime-host/src/protocol/runtime-policy.ts, which enforces the append-only policy that prevents historical mutation. Because the runtime never updates existing log entries—only appends new ones—the system maintains a complete audit trail that eliminates the possibility of silent state corruption or lost updates.
SessionManager: The Consistency Gatekeeper
The SessionManager acts as the public façade that orchestrates sessions and mediates all state changes. Located in packages/runtime/src/session-manager.ts, this component validates every mutation against the current log before persisting changes. When "strict recovery" is enabled, the manager enforces an additional validation guard at line 1407 that insists the recovery store composition matches the in-memory manager state exactly.
All clients—including the Desktop GUI, TUI, and CLI—interact with session state exclusively through this manager. The SessionManager exposes methods like startSession(), runTurn(), and commit() that wrap business logic with validation logic, ensuring no client can bypass the consistency checks or write inconsistent state directly to storage.
Transactional Persistence with SQLite
Maka persists state through two complementary storage mechanisms that are only ever updated through the SessionManager. The runtime.sqlite file holds the live, canonical record of a workspace, while additional JSON stores maintain configuration, connection catalogs, and credential vaults.
The SQLite implementation in packages/storage/src/sqlite-store.ts provides transactional guarantees. Every write operation occurs within a database transaction that also appends a corresponding event to the immutable log. This atomicity ensures that either both the state change and its audit event persist, or neither does, preventing partial writes that could lead to inconsistent recovery states.
Recovery and Replay Mechanism
When a turn finishes, the Runtime Host flushes pending events to the SQLite log and closes the session. If a crash or interruption occurs, the SessionManager can rebuild the exact session state by replaying the log events in sequence.
The recovery process, demonstrated in the test suite at packages/runtime/src/__tests__/session-manager.test.ts, supports a "strict recovery" mode that validates the recovered state against the expected composition. If the persisted store does not match the manager's internal representation—for example, if events are missing or out of sequence—the recovery operation throws an error rather than proceeding with potentially divergent state. This strict validation ensures that no client can operate on stale or corrupted session data.
Practical Implementation: Code Examples
The following TypeScript example demonstrates how to initialize the SessionManager and execute a turn with automatic logging:
import { SessionManager } from '@maka/runtime';
// Create a new SessionManager (deps are usually injected by the host)
const manager = new SessionManager({
store: mySQLiteStore,
backends: runtimeBackends,
newId: () => crypto.randomUUID(),
now: () => Date.now(),
});
// Start a new session (the manager validates and logs the start)
const session = await manager.startSession({
model: 'gpt-4o',
tools: ['websearch', 'file-write'],
});
// Run a turn – every action is recorded in the immutable log
await manager.runTurn(session.id, async (ctx) => {
const response = await ctx.model.chat('Summarize the repo');
ctx.logEvent({ type: 'model-response', payload: response });
});
// After the turn, the manager persists the log entry and updates SQLite
await manager.commit(session.id);
To recover state after a crash, instantiate the manager with a recovery store and invoke the replay method:
import { SessionManager } from '@maka/runtime';
import { createRecoveryStore } from '@maka/storage';
const recoveryStore = createRecoveryStore('runtime.sqlite');
const manager = new SessionManager({
store: recoveryStore,
backends: runtimeBackends,
newId: () => crypto.randomUUID(),
now: () => Date.now(),
});
// Replay the log to restore the exact prior state
await manager.recover(); // throws if strict‑recovery validation fails
Summary
- Immutable event log: All interactions append to an unchangeable log in
runtime.sqlite, creating a complete history that serves as the single source of truth. - Transaction boundaries: The
SessionManagerwraps every state mutation and its corresponding log entry in an atomic SQLite transaction. - Strict recovery validation: At
packages/runtime/src/session-manager.tsline 1407, the system validates that recovered state matches the expected manager composition, rejecting any divergent stores. - Replay capability: After crashes, the system reconstructs exact session state by replaying events from the immutable log rather than relying on potentially stale snapshots.
Frequently Asked Questions
How does Maka recover session state after a crash?
Maka recovers by replaying the immutable runtime-event log from runtime.sqlite. The SessionManager.recover() method reads each event in chronological order and reconstructs the session state step-by-step. If strict recovery is enabled, the system validates that the reconstructed state matches the expected composition at line 1407 of session-manager.ts, throwing an error if any discrepancy indicates corruption or missing events.
What is strict recovery mode in SessionManager?
Strict recovery is a validation mode that enforces an exact match between the persisted store and the SessionManager's internal state representation. When enabled, the recovery process checks that the sequence of events in the SQLite store produces a state composition identical to what the manager expects. Any mismatch—such as missing events, extra events, or out-of-order entries—causes the recovery to fail with an error, preventing operation on potentially inconsistent data.
Why does Maka use SQLite for the canonical session store?
Maka uses SQLite because it provides ACID transactional guarantees that align with the consistency model. The packages/storage/src/sqlite-store.ts implementation ensures that state updates and their corresponding log appends occur atomically. This prevents the partial-write scenarios common in file-based storage, where a crash could leave state and log out of sync. SQLite’s transactional integrity is essential for the strict recovery checks that validate session consistency.
How does the immutable log prevent state divergence?
The immutable log prevents divergence by eliminating update and delete operations on historical data. Since every interaction appends a new event rather than modifying existing state, all clients—whether Desktop, TUI, or CLI—derive their current view by applying the same sequence of events. This append-only design, enforced by the schema in packages/runtime-host/src/protocol/runtime-policy.ts, ensures that every client sees identical session and run state regardless of when they connect or how many crashes occur.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →