Event Logs for Lossless AI Agent Sessions: Design Essentials for Multi-View Consistency

    Large language models lack internal memory across inference turns, often leading to silent context loss and inconsistent data views between the model, user interfaces, and debugging tools. This article explores how adopting event sourcing with an append-only event log establishes a single source of truth for AI agent sessions. It covers designing pure projections for model inputs, enforcing traceability invariants, and the practical benefits and implementation trade-offs of this architecture.

    1. The Root Cause: Context Should Not Be the Sole Source of Truth

    When a large language model performs inference, it can only read the input provided by the caller. It has no cross-turn internal storage, so “memory” is essentially text reassembled by the runtime framework each turn.

    Many frameworks take a direct approach: maintain a message array and send the entire array to the model each turn. This works fine in short conversations, but as tasks grow longer, problems emerge:

    • The context window has an upper limit, forcing the framework to prune old messages.
    • Pruning is often silent, with no error thrown and no record left behind.
    • Tool call return results can be long, getting truncated to just the first few lines.
    • Historical summaries are repeatedly overwritten, causing early decision rationale to disappear.

    From the model’s perspective, it can only answer based on the current input. Pruned content is absent, so the model naturally cannot reference it. When a user asks, “What was the result of the previous step?”, the model gives a vague answer, manifesting as “amnesia.”

    The root cause lies in data ownership. The truth is stored in a mutable, lossy place, meaning any pruning rewrites history.

    2. Multi-View Inconsistency: Another Symptom of the Same Flaw

    A single conversation typically has several types of readers:

    1. The model, which requires a compressed message list.
    2. The user interface, which needs the full display sequence and execution status.
    3. Developers, who need to replay the entire process when issues arise.

    If each view maintains its own copy of the data, they will quickly diverge. The tool results displayed in the UI might differ from the version the model received, and the step sequence seen during debugging might not align with the actual execution order. When troubleshooting, teams struggle to determine which data set is accurate.

    Multi-view inconsistency and memory loss often stem from the same design flaw: the lack of a single source of truth.

    3. Append-Only Event Stream: Centralizing Truth in One Place

    The solution is event sourcing. Instead of saving a conversation as a “current state,” it is recorded as a sequence of events ordered by occurrence. Events can only be appended, never modified or deleted.

    An event typically contains the following fields:

    • Sequence number (seq): monotonically increasing, used for sorting and positioning.
    • Type (kind): e.g., user message, assistant message, tool call, tool result, summary.
    • Payload: the specific content corresponding to the type.
    • Timestamp (ts): for auditing and timeline troubleshooting.

    Below is schematic code illustrating the data structure, not tied to any specific product interface:

    1. from dataclasses import dataclass, field
    2. from typing import Any
    3. import time
    4. @dataclass(frozen=True)
    5. class SessionEvent:
    6. seq: int # monotonically increasing sequence number
    7. kind: str # e.g., "user_message", "tool_result"
    8. payload: dict[str, Any] # content corresponding to the type
    9. ts: float = field(default_factory=time.time)
    10. class SessionLog:
    11. def __init__(self) -> None:
    12. self._events: list[SessionEvent] = []
    13. def append(self, kind: str, payload: dict[str, Any]) -> SessionEvent:
    14. event = SessionEvent(seq=len(self._events) + 1, kind=kind, payload=payload)
    15. self._events.append(event)
    16. return event
    17. def read_from(self, seq: int) -> list[SessionEvent]:
    18. return [e for e in self._events if e.seq > seq]

    This structure brings three direct benefits. First, history does not disappear when the context window fills up, because pruning only applies to projections, not the log. Second, each event has a fixed position, making replay results reproducible. Third, any view can be derived from the same data, requiring no additional synchronization.

    4. Projection: The Model Sees Derived Results

    The log is for storage; the model’s input is a projection. Projections should be designed as pure functions: input an event sequence, output a message list. It does not modify the log or depend on external mutable state, ensuring the same log always yields the same input.

    1. def project_messages(events: list[SessionEvent], max_tool_chars: int = 2000) -> list[dict]:
    2. messages = []
    3. for e in events:
    4. if e.kind == "user_message":
    5. messages.append({"role": "user", "content": e.payload["text"], "source_seq": e.seq})
    6. elif e.kind == "assistant_message":
    7. messages.append({"role": "assistant", "content": e.payload["text"], "source_seq": e.seq})
    8. elif e.kind == "tool_result":
    9. text = e.payload["output"][:max_tool_chars]
    10. messages.append({"role": "tool", "content": text, "source_seq": e.seq})
    11. elif e.kind == "summary":
    12. messages.append({"role": "system", "content": e.payload["text"], "source_seq": e.seq})
    13. # internal step markers and model-irrelevant events do not enter the projection
    14. return messages

    Projection rules dictate the shape of the context. Tool results can be truncated, a segment of history can be replaced by a summary, and internal markers can be omitted. These operations occur during the projection phase, while the original events remain completely intact.

    Compression itself should also be recorded as an event. When the conversation exceeds the window, the framework generates a summary event and notes the range of sequence numbers it covers. Subsequent projections use the summary to replace the original segment, while the full log remains traceable. This satisfies window limits while retaining auditability.

    The same log can also derive multiple views. The model view is trimmed and summarized; the UI view retains all user-visible events with status; the debug view displays events sequentially by sequence number. The three do not interfere with one another—modifying one does not affect the other two.

    5. Core Invariant: Model-Visible Content Must Be Recorded

    This principle can be summarized as: whatever the model can see must have already been written to the log.

    Its value lies in auditability. If a developer temporarily injects an instruction or data while assembling the prompt, subsequent anomalies cannot be traced in the log, leaving troubleshooting to guesswork.

    The correct approach is: when you need to add a new type of input to the model, first define a new event type, then write the corresponding projection rule. The new input also enters the log, making it replayable and inspectable.

    Below is a validation concept before sending a request, ensuring every model input can be traced back to a recorded event:

    1. def assert_traceable(messages: list[dict], events: list[SessionEvent]) -> None:
    2. valid_seqs = {e.seq for e in events}
    3. for m in messages:
    4. src = m.get("source_seq")
    5. if src is None or src not in valid_seqs:
    6. raise ValueError(f"Model input cannot be traced back to the log: {m}")

    This validation can be placed in unit tests or used as a runtime guard. The source of summary messages should record the range of sequence numbers they cover, which must be factored into the validation.

    6. Benefits of a Single Source of Truth

    Centralizing the truth in a single log yields several key benefits:

    • Consistency: The model, UI, and debugging tools read different projections of the same data, eliminating sources of divergence.
    • Recoverability: After a process crash, state can be reconstructed from the latest snapshot plus subsequent events.
    • Replayability: Given a sequence number, the exact input the model saw at that time can be precisely restored, facilitating issue reproduction.
    • Auditability: Every injected piece of content and every tool execution is recorded, keeping the process clear and inspectable.

    These benefits come with trade-offs. The log will grow continuously, requiring snapshot and segmentation strategies to control storage and processing time. Projection functions must be fast enough, or recalculating them each turn will become a bottleneck.

    7. Implementation Decisions

    1. Event schema versioning. Event types will evolve over time, so each event should carry a version number, with backward-compatible handling for older versions during projection.
    2. Side effects execute only once. Tool call requests and results are recorded separately. When replaying the log, use the recorded results instead of making new external system calls to avoid duplicate writes or double billing.
    3. Concurrent write constraints. When multiple executors append simultaneously, use the expected sequence number for optimistic concurrency control to prevent race conditions.