Agent Session Architecture: Solving Memory Loss and View Inconsistency with Event Logs
Long-running agent sessions often suffer from two recurring problems: the model appears to "forget" earlier context, and different components of the system (UI, debugging tools, audit logs) end up with inconsistent views of what happened. This article explains why treating the message array as both storage and context view causes these issues, and proposes an append-only event log architecture where a single event stream serves as the source of truth. It covers how model context becomes a derived projection of the log, how context compaction can be made traceable instead of destructive, key engineering principles for event design, handling of retries and concurrency, and the governance requirements for storing sensitive session data.
1. The Problem Long Sessions Tend to Hide
In multi-turn conversations, automated coding, tool calling, and task orchestration, systems often need to run for extended periods. A single task may involve dozens or even hundreds of interaction turns, interspersed with file reads, command execution, API calls, result validation, and human confirmation steps.
Many developers building this kind of system for the first time reach for an intuitive approach: push every message into an array, and feed that array back into the model as context on the next call. This works fine for short conversations, but as the message count grows, two fundamental problems surface.
The first is memory loss. Context length always has a ceiling, so the system eventually has to truncate, compress, or replace older content. If old messages are simply deleted from the one array that holds everything, the model can never see that information again. Users experience this as the model “forgetting” earlier conclusions, but more precisely, the model never had independent memory in the first place. It just stopped receiving the relevant input.
The second is view inconsistency across components. The same session typically needs to serve multiple consumers:
- The model needs a message list.
- The UI needs a timeline.
- The debugging system needs tool calls and their results.
- The audit module needs a complete record of actions.
- The analytics module needs task, step, and timing data.
If each of these components maintains its own state, the content the model sees, the content the UI displays, and the content in the logs can easily contradict each other. For example, the UI might show that a tool call succeeded while the debug log has no matching result, or the model’s context might contain a summary with no way to trace it back to its source.
The real problem to solve isn’t “how do we give the model permanent memory.” It’s how to build a reliable factual layer for the session, and let different consumers derive the view they need from that same set of facts.
2. The Core Idea: An Event Log as the Single Source of Truth
A more robust design models the session as an append-only stream of events.
Append-only means that once a historical event is written, it is never changed in place. New state changes are expressed by adding new events, not by overwriting old data. If a tool call fails and is retried, the system shouldn’t modify the original failure record. It should add a new retry event instead.
An event typically includes at least the following fields:
Event {id: unique identifiersequence: monotonically increasing sequence numbertype: event typetimestamp: time the event was generatedpayload: event datametadata: source, associated task, trace information, etc.}
Event types can be designed around the needs of the system, for example:
- Session start
- User input
- Model response
- Task start and end
- Step creation and completion
- Tool call
- Tool result
- Human confirmation
- Error and retry
- Context compaction
- State marker or system notification
Together, these events form a time-ordered record of the session. It isn’t the context required for any single model call; it’s the system’s complete account of what actually happened.
The key distinction: the log stores facts, and the context serves the current round of reasoning. The two should not be conflated.
3. What the Model Sees Is a Projection of the Log
The message list the model receives each turn can be understood as a view derived from the event log. Based on the current task, the context budget, and the rendering rules, the system filters, merges, summarizes, and orders historical events to produce the input for that turn.
This process can be expressed in pseudocode:
def derive_context(events, budget, policy):selected = select_relevant_events(events, policy)compacted = compact_old_events(selected, budget, policy)messages = render_as_messages(compacted)return messages
derive_context does not modify the original log. Even if an older event isn’t selected for the current turn, it still exists; it’s simply not in the model’s visible range right now.
This gives an important guarantee:
Anything the model can see must be traceable back to the session log.
Call this principle “visible means logged.” If the system needs to add a new prompt, a tool result, or a piece of state information to the model’s context, it should first write that as an explicit event to the log, then let the projection process render it into context. Nothing should be spliced into a call chain as untracked text midstream.
This brings three direct benefits.
Context can change; facts don’t disappear arbitrarily
Context is a constrained resource that can be compressed and reorganized. The log is a factual store that should remain as complete as possible. Even if the model can’t currently see a historical event, the system can still query it, re-summarize it, or render it into another view later when needed.
Different components share a consistent data source
The UI, the model, the debugging module, and the audit module no longer each maintain their own version of “what happened in the session.” Instead, they generate different presentations from the same event stream. The views can differ, but the underlying facts stay consistent.
System behavior becomes replayable
As long as the event record is complete enough, the system can reconstruct the state at any point in time, check exactly what the model saw at that moment, analyze why a particular tool call happened, and trace the origin of a state change.
4. Why Append-Only Fits Long-Running Tasks Better
A traditional mutable array usually mixes “current context” with “historical fact” together. Once the array is truncated, the deletion affects both the model’s input and the system’s own record of history.
An append-only log separates these two concepts:
Full event stream├── Model context view├── UI view├── Debug replay view├── Audit view└── Analytics view
Different views can use different strategies. For example:
- The model view prioritizes relevance and context length.
- The UI prioritizes readability and interaction state.
- The debug view prioritizes raw inputs, outputs, and error traces.
- The audit view prioritizes non-repudiation, chronological order, and the acting party.
- The analytics view prioritizes task duration, step counts, and failure rates.
If every view depends directly on a single message array that gets truncated, any optimization made to the model’s context risks breaking the other views. An event log decouples “what gets stored” from “what gets displayed,” letting the system evolve each independently.
5. Context Compaction Is Not the Same as Deleting History
Long sessions inevitably need compaction, but compaction should be designed as a traceable, derived process rather than a silent deletion.
A more robust approach:
- Keep the original events.
- Select a range of older events.
- Generate a summary according to explicit rules.
- Write a “summary generated” event.
- Replace part of the original content in the model’s view with the summary.
- Keep the start and end sequence numbers the summary covers, for traceability.
The structure might look like this:
SummaryEvent {covers_from: starting event sequence numbercovers_to: ending event sequence numbersummary: summary contentgenerated_by: generation method}
It’s worth noting that a summary is not the fact itself; it’s a compressed representation of the fact. It may omit details, and it may introduce bias depending on how it was generated. That’s why a summary must carry its coverage range, and why the system must still be able to re-read the original events when necessary.
In higher-stakes scenarios, key facts can also be stored separately in structured form, such as:
- Confirmed user constraints
- Completed steps
- Current file versions
- Tool execution results
- Pending items
- Failure reasons and retry counts
This way, the model’s context can draw on both natural-language summaries and structured state, reducing the risk that a summary drops a critical fact.
6. Engineering Principles for Designing Events
Event types should express facts, not UI actions
“The user clicked a button” is typically a UI action. “The user confirmed an operation” is closer to a business fact. Event design should describe system state changes, not bind itself to a particular page implementation.
Events should be immutable wherever possible
If a historical record turns out to be wrong, add a correcting event rather than editing the old one directly. This preserves the full history of how things evolved, which matters for auditing and debugging.
Relationships must be explicit
Tool calls and their results, tasks and their steps, retries and the original failures they’re tied to, should all be linked through explicit identifiers. Relying on chronological order alone creates ambiguity under concurrent execution.
Sequence numbers must be stable
Timestamps can collide, and distributed environments can introduce clock skew. The system should use a monotonically increasing sequence number or another stable ordering mechanism to guarantee reproducible event order.
Writing and projection must be separate steps
Context should only be derived after an event has been successfully written to the log. Don’t temporarily splice content into a model request and backfill the log afterward; doing so breaks the guarantee that everything visible to the model is traceable.
7. Handling Failures, Retries, and Concurrency
When a tool call fails, the system shouldn’t simply overwrite the original result. A more reasonable event sequence looks like this:
ToolCallToolResult(status=failed)RetryRequestedToolCallToolResult(status=success)
This makes it possible to answer questions like:
- What parameters did the first call use?
- Why did it fail?
- Was there a retry?
- Did the parameters change on retry?
- Which call produced the final successful result?
For concurrent tasks, the event stream also needs to record task identifiers, parent-child step relationships, and execution batches. Multiple steps may produce interleaved events, but every event should still be traceable to a specific task context. Sorting purely by global timestamp, without that context, may make it impossible to reconstruct the full history of a particular subtask.
8. How This Architecture Improves Debugging and Auditing
When a system produces a wrong decision, the most important question isn’t just what the final response was; it’s reconstructing the actual input to that decision:
- What historical events existed at that point?
- Which events were projected into context?
- What content was summarized or trimmed?
- Was the tool result complete?
- What actions did the system take after the model’s output?
If context was assembled ad hoc with no record of how, these questions usually can’t be answered with any confidence; they become guesswork. With an event log, the system can store the projection rule version, the time the context was generated, and the range of input events used, getting much closer to a full post-mortem.
It’s worth emphasizing that an event log doesn’t automatically guarantee correctness. It solves traceability and consistency. Projection strategy, summary quality, access control, and data security still need to be designed separately.
9. Security and Governance Requirements for Deployment
Session logs may contain user input, sensitive data, file contents, and tool execution results, so the data structure alone isn’t enough; governance matters too:
- Mask or encrypt sensitive fields.
- Restrict read access to different event types based on role.
- Define clear retention periods for raw logs versus model context.
- Validate the safety of results returned by external tools.
- Guard against logs being polluted by malicious content.
- Record the projection rule version and summary version used.
- Establish clear processes for deletion, archiving, and compliance requests.
In particular, “complete record” should not be confused with “unlimited retention.” Engineering teams need to balance traceability, privacy protection, storage cost, and access efficiency.
10. Conclusion: Reframing Memory as a Data Architecture Problem
What looks like a model “forgetting” is often not a sudden drop in capability. It’s the context system losing, truncating, or hiding historical facts. If a context array is used as both the storage layer and the display layer, long-running tasks will eventually run into memory fragmentation and view inconsistency.
A more reliable approach is a layered architecture:
Event log: stores factsProjection layer: generates different viewsModel context: serves current reasoningUI and debugging: serve display and diagnostics
Under this design, the historical record is append-only, replayable, and traceable. Context can be compressed dynamically based on budget. Different components can derive their own views from the same factual source. The system can also clearly explain why a given piece of information was visible to the model, when it was compacted, and how to recover it.
Ultimately, the core challenge in long-running agent sessions isn’t giving the model human-like permanent memory. It’s building a reliable external system of record, and using an explicit, auditable projection mechanism to decide what the model should see on each turn.
