How Apache Maka Ensures Safety During Replay with Phase 0
Apache Maka's Phase 0 validation layer rejects unsafe replayed events by verifying version consistency, enforcing forward progression, and guarding storage-level recovery.
Apache Maka implements a dedicated Phase 0 safety pipeline that intercepts replayed events before they mutate application state. This architecture, defined in the runtime model history and enforced across both UI and storage layers, ensures that only consistent, forward-moving events are applied to the current model snapshot. By validating event metadata and offsets before reconstruction begins, Phase 0 prevents state corruption and version drift during session recovery.
What Is Phase 0 in Apache Maka?
Phase 0 is the mandatory pre-replay safety stage that executes before any state reconstruction (Phase 1) occurs. According to the source code comments in [packages/runtime/src/model-history.ts](https://github.com/apache/maka/blob/main/packages/runtime/src/model-history.ts), this phase "ensures that any replayed events are safe and consistent with the current model." It acts as a gatekeeper, returning a boolean success flag or throwing a hard error that aborts the entire replay sequence.
The Safety-First Architecture
The Phase 0 design separates safety concerns from business logic. Instead of embedding checks within reducers or effect handlers, Maka centralizes validation in discrete functions like verifyReplaySafety and replaySafeDelta. This separation allows the runtime, storage engine, and UI components to share a single source of truth for what constitutes a valid replay sequence.
Core Safety Mechanisms in Phase 0
Version Consistency Validation with verifyReplaySafety
The primary Phase 0 check validates that each replayed event aligns with the current ModelSnapshot. The verifyReplaySafety function iterates through the event array and compares event versions against the snapshot's expected version.
// packages/runtime/src/model-history.ts
import { RuntimeEvent } from './runtime-event';
import { ModelSnapshot } from './model-snapshot';
export function verifyReplaySafety(events: RuntimeEvent[], snapshot: ModelSnapshot): boolean {
// Ensure that each event's metadata matches the snapshot's expectations
for (const ev of events) {
if (ev.type === 'model_update') {
if (ev.version !== snapshot.version) {
return false; // version mismatch indicates unsafe replay
}
}
// Additional safety checks can be added here
}
return true;
}
If any model_update event carries a version identifier that diverges from the snapshot, the function returns false, signaling the caller to abort the replay.
Forward Progression Guards with replaySafeDelta
UI components that stream incremental text or "thinking" events use replaySafeDelta to guarantee that replayed deltas move strictly forward. This prevents out-of-order or duplicate text injections that could corrupt the user interface state.
// packages/ui/src/live-turn-projection.ts
function replaySafeDelta(prevOffset: number | undefined, event: LiveTurnEvent) {
if (prevOffset === undefined) return null; // safety: no prior offset
if (event.type !== 'text') return null; // only text events considered
if (event.offset <= prevOffset) return null; // safety: ensure forward progression
return { delta: event.offset - prevOffset };
}
The function returns null when the event offset fails to advance beyond the previously recorded offset, effectively filtering stale or regressive updates before they reach the rendering layer.
Storage-Level Enforcement
The storage engine embeds Phase 0 checks directly into its recovery path. Before applying a persisted manifest, [packages/storage/src/sqlite-runtime-store.ts](https://github.com/apache/maka/blob/main/packages/storage/src/sqlite-runtime-store.ts) imports verifyReplaySafety and invokes it against the loaded event batch.
// packages/storage/src/sqlite-runtime-store.ts
import { verifyReplaySafety } from '../../runtime/src/model-history.js';
// During recovery...
if (start.replayManifestDigest !== claim.boundary.manifestDigest) {
// ... integrity checks ...
}
// Perform safety checks for replay integrity
if (!verifyReplaySafety(events, snapshot)) {
throw new Error('Replay safety violation');
}
This guard clause ensures that corrupt or mismatched event logs cannot poison the runtime state during database recovery.
Implementation Details and Integration
Developers integrating custom replay logic must invoke these Phase 0 validators before applying events. The recommended pattern involves three steps: capture the current ModelSnapshot, filter events through verifyReplaySafety, and transform incremental updates using replaySafeDelta when handling text streams.
Because these functions are pure and side-effect-free, they can run in both the main thread and Web Worker contexts without requiring mutable state access. This design supports Maka's distributed architecture where replay validation may occur on a background thread before the UI thread commits changes.
Summary
- Phase 0 is a mandatory pre-replay gate that runs before state reconstruction to validate event integrity.
verifyReplaySafetyenforces version alignment betweenRuntimeEventobjects and the currentModelSnapshot, rejecting mismatched sequences.replaySafeDeltaensures UI text events progress strictly forward, preventing duplicate or out-of-order updates.- Storage engines like
sqlite-runtime-store.tsharden recovery by throwing fatal errors when Phase 0 checks fail, protecting the system from state corruption.
Frequently Asked Questions
What triggers a Phase 0 safety violation in Apache Maka?
A violation occurs when a replayed event's version metadata does not match the current model snapshot's version, or when a text event's byte offset fails to advance beyond the previously processed offset. Either condition causes the validator to return false or null, aborting the replay.
How does replaySafeDelta prevent duplicate events?
The function compares the incoming event's offset property against the prevOffset stored from the last successful application. If the new offset is less than or equal to the previous value, the function returns null, signaling the caller to discard the event as stale or redundant.
Is Phase 0 executed only during crash recovery?
No. While Phase 0 is critical during storage recovery, the same validation functions run during live session replay and optimistic UI updates. This ensures consistency whether the system is restoring from disk or projecting real-time thinking streams.
Where is verifyReplaySafety defined and consumed?
The function is defined in packages/runtime/src/model-history.ts and consumed by the storage layer in packages/storage/src/sqlite-runtime-store.ts. It is also available for custom replay implementations that operate outside the standard storage engine.
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 →