Append-Only Session Logs: Agent Memory and Consistent Views
An append-only event log separates an AI agent’s durable session history from its temporary model context. This article explains how deterministic projections, explicit compaction events, ordered writes, and replayable records support traceable memory and consistent model, UI, and debugging views, while outlining practical requirements for concurrency, recovery, observability, and testing.
AI agents often behave reliably in short conversations. During multi-step reasoning, tool use, and long-running tasks, however, they may contradict a conclusion confirmed just one turn earlier or respond as though it never existed.
This is often blamed on poor model memory. A more accurate diagnosis is that many runtimes have no independent memory layer. On each turn, the model receives only the context assembled for that request. Once that text is truncated, compressed, or replaced, the model no longer has access to the facts it contained.
A more reliable session architecture records what happened in an append-only event stream, then projects that stream into model messages, user interface views, and debugging replays. The goal is not to give the model mysterious long-term memory. It is to make its inputs traceable and ensure that every view comes from the same record.
1. Where Memory Loss Begins
Many frameworks store an entire conversation in a growing message array and use that array directly as model context. This works for short exchanges. As tasks get longer, earlier user messages, intermediate reasoning records, and tool results may be silently dropped to satisfy context limits. No error is raised, and the caller may not notice that part of the history has disappeared.
If the user then asks for the result of an earlier step, the model can only infer it from the remaining text. It has not forgotten something in durable storage: that storage never existed, and its context has already been rewritten.
The underlying problem is simple: context is both the only record of facts and a mutable, disposable view.
This also creates inconsistent views. A UI may maintain a separate summary state. A debugger may retain only the latest tool response. Retry logic may rewrite a message in memory. These become three independently maintained versions of the truth.
When compaction policies, truncation boundaries, or replay order differ, the UI, the model, and the audit record diverge. Troubleshooting can no longer answer a basic question: What exactly did the model see on this turn?
2. Put the Source of Truth in an Append-Only Log
The cleaner design separates storage from presentation. A session is a sequence of events appended in occurrence order, not a message array modified in place.
Each event contains at least a type, a monotonically increasing sequence number, and a payload. User input, assistant output, reasoning steps, tool calls, tool results, compaction markers, errors, and retries are recorded as events rather than hidden context mutations.
Append-only storage provides three immediate benefits:
- History is not overwritten. To remove content from future model context, append a compaction or view-trimming event that identifies the affected sequence boundary or range. Do not delete the original records.
- Order is replayable. Monotonically increasing sequence numbers make reconstruction independent of temporary in-memory objects.
- Failures remain traceable. Tool timeouts and truncation decisions stay in the log instead of disappearing with a failed request.
A minimal event structure might look like this:
Event {seq: monotonically increasing integertype: user_message | assistant_message | tool_call | tool_result | compaction | errorpayload: structured content corresponding to the event typets: occurrence timestamp}
There is one write path: append a record of what happened. There can be multiple read paths, each mapping the log into the view required by a particular consumer.
3. The Model Receives a Projection, Not the Stored Session
Before each model call, the runtime derives a message list from the event stream according to explicit rules. The model does not own the session object or accumulate durable memory locally. Its context is always a fresh projection of the log.
Projection rules should be defined centrally rather than scattered across string-building code. For example:
- User messages and final assistant responses are visible by default.
- Tool calls and their results are retained together, avoiding a call without its corresponding result.
- Long histories are compacted by first appending a compaction event, then substituting a summary for the folded range during projection.
- If system instructions change, the change is recorded as an event before the instructions appear at the beginning of the message list.
- Debugging notes, billing information, and internal routing markers are excluded from the model view by default.
One rule should be a hard invariant: anything visible to the model must already be recorded in the log.
To introduce a new kind of model input, define its event type first, then render it through the projection function. Do not inject unlogged text immediately before a call. Otherwise, the UI, replay, and audit views will omit something the model actually read, making production issues difficult to reproduce.
Projection must also be deterministic. The same log, rules, and cutoff sequence number must produce the same message list. Retries, replays, and comparison experiments depend on this property. A projection that relies on the current time, random sampling, or partially built objects in a process-local cache breaks that consistency.
4. Why This Addresses Both Memory and View Consistency
Memory loss occurs when earlier facts disappear from their only record. An event stream preserves those records. Compaction appends a new event and changes subsequent projections rather than deleting history.
Audits and replays can still access the original text, while the model receives a representation that fits its context budget. The appearance of remembering comes from retaining important facts in the projection, not from the model acquiring persistent storage.
Inconsistent views arise when multiple mutable copies evolve independently. With a single source of truth, model messages, the conversation UI, the event timeline, and debugging replays become different projection functions over the same log.
The UI can collapse tool details. The model can retain structured results. A debugger can expand every event. All of them still share the same sequence-number space. When they differ, investigators can compare projection rules and cutoff sequence numbers instead of guessing which cache is correct.
These problems are two consequences of the same design mistake: treating a temporary view as the authoritative record. Once facts are anchored in an append-only log, views can be tailored to different consumers without overwriting one another.
5. Preserve Important Facts During Projection and Compaction
Context limits are real. Durable history does not make model context unlimited. Context reduction should therefore be an explicit operation, not the silent removal of entries from the beginning of an array.
Useful strategies include:
- Sliding retention. Keep user goals and assistant conclusions from recent turns, while summarizing older raw tool output.
- Promoting key facts. Record task goals, constraints, and confirmed intermediate conclusions as separate events. Prioritize them during compaction so large tool responses do not displace them.
- Paired trimming. Retain or fold a tool call and its result together. Avoid leaving an incomplete history in which the model sees a call but no result.
- Reversible folding. Store the covered sequence range in the summary event. Replay tools can expand the original records when needed, even if the default projection does not.
- Observable truncation. Append a
compactionortruncationevent containing the reason and retained range. Monitoring can then detect unexpectedly short contexts.
The projection logic can be expressed simply:
deriveMessages(log, rules):visible = []folded = rules.foldedRanges(log)for event in log:if event.seq in folded: continueif rules.visibleToModel(event):visible.append(render(event))return visible
Compaction quality determines what the agent can still use. Summaries should preserve decisions, essential inputs and outputs, and unfinished work—not just conversational filler.
If a summary will be read by the model, it must first be appended as an event. The same invariant applies: visible means recorded.
6. Writes, Concurrency, and Recovery
Append-only storage does not eliminate ordering requirements. A single writer must assign sequence numbers within a session, or a linearizable log component must guarantee append order.
For concurrent tools, record that each call was issued before recording its result. Two executors must not modify the same message text simultaneously.
The durable log should serve as the session’s commit record. After a process crash, recovery starts from the last successfully appended event, not a partially assembled context in memory.
Idempotency matters as well. Tools may be retried, so events must distinguish a retry of the same call from a new user-initiated call. Otherwise, projections may include duplicate results or treat a failed retry as a new fact.
In multi-instance deployments, session affinity or an external log service that serializes writes can preserve ordering. The essential requirement is to avoid giving each instance its own message array that can diverge from the others.
Object storage can hold large raw tool outputs, with references and summaries stored in the log. Message queues can decouple asynchronous tool-completion notifications. These supporting components should not fragment the authoritative session record across disconnected caches.
7. Observability and Testing
The value of this architecture becomes especially clear during troubleshooting. For a poor response, investigators should be able to identify:
- The cutoff sequence number.
- The projected message list.
- The folded history ranges.
- Whether a tool result arrived too late to be included.
Useful monitoring signals include event append latency, projected context length per turn, compaction frequency, tool failure rate, and anomalies such as an empty projection or a sudden drop in context length.
Projection tests do not require a live model. Given an event fixture and a set of rules, tests can assert message counts, order, and important fields.
Additional cases should verify that goals and constraints survive compaction. These guard against later rule changes that accidentally trim essential facts. Replay tests should also confirm that UI and model projections interpret sequence numbers consistently.
8. Limits and Operational Boundaries
An append-only log improves the durability of session records and consistency across views. It does not automatically improve model reasoning.
Incorrect summaries, erroneous tool results, or overly aggressive projection rules can still give the model a misleading view. The log grows over time, so it needs retention policies, access controls, and sensitive-data redaction. Secrets and personal information in tool responses should not be copied unchanged into long-term storage or model context.
Nor does every internal detail need to be exposed to the model. Projection determines visibility; anything exposed must first be recorded. State that exists only in process memory should not influence model inputs or the UI without being captured in the shared record.
9. Conclusion
Memory loss in long-running agent tasks is often an architectural problem: a context buffer that can overflow is treated as the only source of truth.
An append-only session event stream provides a more reliable foundation. Model inputs, UI views, and debugging replays are derived from the same log, while explicit compaction events replace silent truncation. This preserves traceable history and keeps different views aligned.
Three invariants anchor the design:
- Sequence numbers increase monotonically.
- Everything visible to the model is already recorded.
- Projections are deterministic and replayable.
Context budgeting, concurrent tool execution, recovery, and monitoring should all build around that shared source of truth—not create another mutable session copy that can quietly diverge.
