# How Apache Maka Manages Session Lifecycle and Admission Control

> Apache Maka ensures session security with admission control and manages session lifecycle from startup to close. Learn how Maka reserves, admits, and isolates each session.

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

---

**The Apache Maka runtime host guarantees that only one root execution runs per session at any time through a strict admission control mechanism that reserves, admits, and isolates each session from startup to close.**

The Apache Maka runtime host is a long-lived process that owns a single State Root and executes all work for a session. According to the Apache Maka source code, the architecture deliberately separates the **process lifecycle**—managed by the **Host Kernel**—from the **business-logic lifecycle** implemented in Domain Modules. This separation creates a robust framework for session lifecycle management and atomic admission control that prevents concurrent execution conflicts.

## Session Lifecycle Stages

The Apache Maka runtime host defines five distinct stages that every session traverses from initialization to termination. These stages are documented in [`docs/architecture/runtime-host-architecture.md`](https://github.com/apache/maka/blob/main/docs/architecture/runtime-host-architecture.md) and enforced across the core server modules.

### 1. Startup

During **Startup**, the Host Kernel acquires an exclusive lease on the State Root, binds the Composition identity, and builds the fixed set of Domain Modules. The system recovers durable state from persistent storage, initializes internal schedulers, and publishes a *Ready* signal to indicate the host can accept work. This process ensures that all prerequisites for admission control are satisfied before any client requests arrive.

### 2. Request

In the **Request** stage, incoming client connections undergo authentication and validation. The runtime host enforces input size limits and permission checks before routing the request to either the Kernel or the appropriate Domain Module. This stage acts as the entry point to the admission control system.

### 3. Execution

The **Execution** stage begins when a Domain Module requests a **root execution** for the session. At this point, the **Hosted Execution Authority**—implemented in [`packages/runtime-host/src/server/hosted-execution-authority.ts`](https://github.com/apache/maka/blob/main/packages/runtime-host/src/server/hosted-execution-authority.ts)—performs the critical admission decision. This atomic operation reserves and admits the execution, creating three distinct handles: a **snapshot** of the current durable state, a **completion** handle that reports success, failure, or cancellation, and a **settled** signal indicating cleanup completion.

Admission **prevents** any other top-level Turn from starting until the current one closes or cancels, enforcing the invariant that one session has at most one root execution at any time.

### 4. Drain

During **Drain**, the runtime host stops accepting new work while allowing already-admitted executions to finish or reach a recoverable state. This graceful degradation ensures that active sessions complete their atomic operations without interruption while the system prepares for shutdown.

### 5. Close

In the **Close** stage, listeners stop accepting connections, Modules close in reverse initialization order, and all resources—including the State Root lease—are released. This final cleanup guarantees that no orphaned processes remain bound to the durable state.

## How Admission Control Works

**Admission control** in Apache Maka functions as the "traffic controller" for session execution. The process centers on the `HostedExecutionAuthority` class, which resides in [`packages/runtime-host/src/server/hosted-execution-authority.ts`](https://github.com/apache/maka/blob/main/packages/runtime-host/src/server/hosted-execution-authority.ts).

The admission workflow follows three strict steps:

1. **Reserve** – The authority reserves an exclusive execution slot for the session ID, effectively queueing the request against the State Root.
2. **Admit** – The system atomically admits the execution by creating an immutable snapshot of the durable state (Git/SQLite) and generating the completion and settled handles.
3. **Isolate** – The admission lock prevents any other root execution for the same session from starting until the current execution completes and the settled signal resolves.

This mechanism ensures that domain modules never encounter conflicting state mutations during concurrent operations.

### Code Example: Admitting a Session

The following TypeScript example demonstrates how Domain Modules interact with the admission authority:

```ts
import { HostedExecutionAuthority } from
  '../../packages/runtime-host/src/server/hosted-execution-authority';

async function startTurn(sessionId: string) {
  const authority = new HostedExecutionAuthority();

  // Attempt admission
  const { snapshot, completion, settled } = await authority.admitRootExecution(sessionId);

  console.log('Session admitted at snapshot:', snapshot);
  // Run the model / tools using the snapshot as the starting point …
  // When the run finishes:
  const result = await completion;          // resolves to success/failure/cancel
  await settled;                            // ensures all cleanup is done
  return result;
}

```

The function calls the single admission point, receives the three guarantees, runs the model, and finally waits for cleanup.

## Session Continuity and Client Observation

While executions run, the **Session Continuity Coordinator**—defined in [`packages/runtime-host/src/server/session-continuity-coordinator.ts`](https://github.com/apache/maka/blob/main/packages/runtime-host/src/server/session-continuity-coordinator.ts)—maintains live connections to clients. This component publishes canonical snapshots after each durable fact is appended, allowing clients to rebuild their current view after any disconnection without relying on in-flight messages.

Clients receive size-limited, ordered updates that guarantee eventual consistency with the host's durable state.

### Code Example: Subscribing to Session Updates

```ts
import { SessionContinuityCoordinator } from
  '../../packages/runtime-host/src/server/session-continuity-coordinator';

async function watchSession(sessionId: string) {
  const coordinator = new SessionContinuityCoordinator();

  const { snapshot, seq, handle } = await coordinator.subscribe(sessionId);
  console.log('Initial snapshot', snapshot);

  // Receive incremental updates
  handle.on('update', (event) => {
    console.log('Live update', event);
  });
}

```

This pattern enables resilient client implementations that survive network partitions without losing execution context.

## Key Source Files and Architecture

The session lifecycle and admission control implementation spans several critical files in the Apache Maka repository:

- **[`packages/runtime-host/src/server/host-kernel.ts`](https://github.com/apache/maka/blob/main/packages/runtime-host/src/server/host-kernel.ts)** – Manages the process lifecycle, acquires the exclusive lease on the State Root, handles listener setup, and orchestrates drain and shutdown sequences.
- **[`packages/runtime-host/src/server/host-composition.ts`](https://github.com/apache/maka/blob/main/packages/runtime-host/src/server/host-composition.ts)** – Builds the fixed set of Modules, binds the Composition identity, and manages module recovery during startup.
- **[`packages/runtime-host/src/server/hosted-execution-authority.ts`](https://github.com/apache/maka/blob/main/packages/runtime-host/src/server/hosted-execution-authority.ts)** – Implements the root execution admission contract, enforcing the reserve-admit-isolate sequence.
- **[`packages/runtime-host/src/server/session-continuity-coordinator.ts`](https://github.com/apache/maka/blob/main/packages/runtime-host/src/server/session-continuity-coordinator.ts)** – Publishes canonical snapshots and manages live update streams to connected clients.
- **[`docs/architecture/runtime-host-architecture.md`](https://github.com/apache/maka/blob/main/docs/architecture/runtime-host-architecture.md)** – Contains the high-level lifecycle table and admission semantics that guide the implementation.

## Failure Handling and Recovery

If the runtime host crashes, the design guarantees recoverable state. A new Host instance rereads the durable Stores (Git and SQLite) and repeats the recovery process until execution and Domain state converge. Admission failures—such as composition mismatches—are reported before any listeners start, preventing the system from entering a faulty state.

The atomic nature of the admission snapshot ensures that even during recovery, the host can determine exactly where each session terminated and whether cleanup completed via the **settled** signal.

## Summary

- The Apache Maka runtime host separates **process lifecycle** (Host Kernel) from **business-logic lifecycle** (Domain Modules) to create robust session management.
- **Admission control** guarantees only one root execution runs per session at any time through atomic reserve-admit-isolate operations in `HostedExecutionAuthority`.
- The five session stages—**Startup, Request, Execution, Drain, and Close**—provide clear boundaries for resource allocation and cleanup.
- **Session Continuity** provides clients with canonical snapshots and live updates, ensuring resilience against disconnections.
- All state transitions follow an **owner/authority model** where only one component may make specific transitions while the host is online.

## Frequently Asked Questions

### What happens if a client disconnects during a session execution?

The Apache Maka runtime host maintains session continuity through canonical snapshots published after each durable fact append. When a client reconnects, they receive the latest snapshot from the **SessionContinuityCoordinator**, allowing them to rebuild the current state without requiring the server to retain in-flight messages indefinitely.

### How does Apache Maka prevent concurrent executions of the same session?

The **HostedExecutionAuthority** enforces a strict admission control policy that reserves and admits only one root execution per session at a time. This atomic admission creates a lock that prevents any other top-level Turn from starting until the current execution completes and the **settled** signal resolves, as implemented in [`hosted-execution-authority.ts`](https://github.com/apache/maka/blob/main/hosted-execution-authority.ts).

### What occurs during the Drain stage of the session lifecycle?

During the **Drain** stage, the runtime host stops accepting new client requests while allowing already-admitted executions to finish or reach a recoverable checkpoint. This graceful degradation ensures active sessions complete their atomic operations before the host proceeds to the **Close** stage and releases the State Root lease.

### How does the runtime host recover from a crash?

If the host crashes, a new instance rereads the durable Stores (Git and SQLite) and repeats the recovery process until the execution and Domain Module states converge. The **settled** signal and durable snapshots allow the system to determine exactly where each session terminated and whether cleanup completed successfully.