Fix Agent Session Memory Loss with an Append-Only Event Log

    Agent models do not store memory between turns. This article explains why trimming a single context array causes apparent amnesia and conflicting views, and how an append-only event log with deterministic projections keeps one source of truth for the model, UI, debugging, and audit.

    1. Where memory loss comes from

    Most agent systems do not keep memory inside the model. On each turn, the model can read only the context the system assembles at that moment. That context is a temporary view, not internal model state.

    The problem is how the context is assembled. Many systems put the entire session into one length-limited array and pass that array to the model on every call. Short conversations work fine. Once a task grows—multiple reasoning turns, tool calls, and large results—the array exceeds its budget. The system usually drops the oldest messages or replaces the original text with a summary. This often happens with no error and no notice.

    Deleted content no longer exists for the model. If the user asks, “What was the result of that earlier query?”, the model can only guess or admit it does not know, because it no longer has that result. From the user’s point of view, the agent has lost its memory.

    The underlying design mistake is treating the context as the only record of facts. Context is mutable, finite, and subject to trimming. Facts stored only there will eventually be lost.

    2. Why multiple views drift apart

    Memory loss is only one side of the problem. The same session often has to be read by several roles:

    • The model needs a message list suitable for inference.
    • The user interface needs the full conversation and tool execution trace.
    • Developers need to replay what happened at each step.
    • Audit or billing may need call counts and elapsed time.

    If each view keeps its own state, updates drift. A typical case is a tool result that is already shown in the UI but never written into the model context because one branch did not run. The model then continues as if it does not know the result, while the UI shows that the result has already returned. Neither side is “wrong,” but the facts contradict each other.

    The root problem with multiple copies is that none of them is authoritative. When they disagree, the system cannot tell which one is correct.

    3. Core design of an event-stream approach

    The fix is to change the storage form: record the session as an append-only event stream, and derive every view from that stream.

    3.1 Event structure

    Each event should include at least:

    • Sequence number (seq): monotonically increasing, used to order events and support incremental reads.
    • Type (kind): for example, user message, model output, tool call, tool result, or turn start and end.
    • Payload: the concrete content of the event.
    • Ownership: the session, turn, and step the event belongs to, so it can be queried at the right granularity.

    Once written, an event is never modified or deleted. If earlier content is wrong, append a correction event instead of rewriting the original. The log itself is then the complete history.

    3.2 Projections: views derived from the log

    The model does not read the log directly. A projection function maps the event sequence to the message list the model may read on this turn. The projection must be deterministic: the same log always produces the same output. The UI, debugging tools, and audit modules each implement their own projections over the same log.

    3.3 Key invariant: if the model can see it, it has already been recorded

    This is the most important constraint in the design: anything the model can see must first be written to the log as an event.

    If the model needs a new kind of input—for example, a dynamic fragment of the system prompt or a retrieval result—define a new event type first, then render it as a message in the projection rules. Do not quietly concatenate an extra string while assembling the context. With this rule, any model call can be fully reproduced from the log.

    3.4 A single source of truth

    Facts are stored once, in the log. The model, UI, debugging, and audit all derive views from it. Disagreement between views can then come only from a bug in a projection rule, and projection rules can be checked directly with tests.

    4. Example code

    The code below is a minimal illustration. Names are schematic and do not match any specific product API.

    1. from dataclasses import dataclass
    2. from itertools import count
    3. from typing import Any
    4. ROLE_MAP = {
    5. "user_message": "user",
    6. "assistant_message": "assistant",
    7. "tool_result": "tool",
    8. }
    9. @dataclass(frozen=True)
    10. class Event:
    11. seq: int
    12. kind: str
    13. payload: dict[str, Any]
    14. class SessionLog:
    15. """Append-only session log; the single source of truth."""
    16. def __init__(self) -> None:
    17. self._events: list[Event] = []
    18. self._seq = count(1)
    19. def append(self, kind: str, **payload: Any) -> Event:
    20. event = Event(seq=next(self._seq), kind=kind, payload=payload)
    21. self._events.append(event)
    22. return event
    23. def snapshot(self) -> tuple[Event, ...]:
    24. return tuple(self._events)
    25. def project_messages(events: tuple[Event, ...]) -> list[dict[str, str]]:
    26. """Project the log into a message list the model can read.
    27. A compaction event changes only the projection, not the original events.
    28. """
    29. summary = None
    30. covers_until = 0
    31. for e in events:
    32. if e.kind == "compaction":
    33. summary = e.payload["text"]
    34. covers_until = e.payload["covers_until"]
    35. messages: list[dict[str, str]] = []
    36. if summary is not None:
    37. messages.append({"role": "system", "content": summary})
    38. for e in events:
    39. if e.seq <= covers_until or e.kind not in ROLE_MAP:
    40. continue
    41. messages.append({"role": ROLE_MAP[e.kind], "content": e.payload["text"]})
    42. return messages
    43. log = SessionLog()
    44. log.append("user_message", text="Check the status of order 1024")
    45. log.append("tool_result", text="Order 1024: shipped")
    46. log.append("assistant_message", text="Order 1024 has been shipped.")
    47. # Compaction affects only what the model sees; the log keeps the full history
    48. log.append(
    49. "compaction",
    50. text="The user previously asked about order 1024, which is shipped.",
    51. covers_until=3,
    52. )
    53. log.append("user_message", text="When was it shipped?")
    54. print(project_messages(log.snapshot()))

    The example makes a few points. First, projection is a pure function: a fixed input always yields a fixed output. Second, compaction is done by appending a new event; the original events stay in the log. Third, a UI or audit module can walk snapshot() directly and does not have to go through the model context.

    5. How the two problems are solved

    5.1 Memory loss

    When the context exceeds its budget, the system no longer deletes old messages. It appends a compaction event that records the summary and the sequence range it covers. On the next turn, the projection replaces messages in that range with the summary.

    Two things follow. The model still gets the important background, and context length stays under control. The original details are not lost: if a later step needs the exact tool result, it can be read from the log. If the summary is poor, the projection can be corrected and rerun without worrying that the source text has already disappeared.

    5.2 Inconsistent views

    Every view is projected from the same log. Once a tool result is written to the log, it appears in the model context, the UI, and the debug replay. There is no separate write path that one of them can miss.

    Consistency therefore becomes a question of whether the projection rules are correct. The team can test the projection functions: given a fixed event sequence, assert the model messages, the UI rendering, and the audit statistics.

    6. Engineering notes

    Concurrency and order. Sequence numbers within one session must increase strictly. A single process can use an in-memory counter. With multiple processes or instances, a single writer should assign sequence numbers, or optimistic concurrency control can use database transactions and a unique constraint.

    Storage. An event stream fits a store that supports appends and range reads by sequence number—for example, an event table in a relational database, or a general log store. What matters is durable writes and fast reads by session and sequence number.

    Incremental projection. Replaying from the first event every time becomes expensive as the session grows. Periodically store a projection snapshot with the last sequence number it covers, then process only newer events. A snapshot is derived data; if it is lost, it can be rebuilt from the log.

    Sensitive data. The log keeps inputs and outputs in full, so it may contain personal data or credentials. Redact before writing, or encrypt sensitive payloads and store them separately while keeping a reference in the log. Metadata required for audit can stay in the log.

    Event versions. Event types change as the product evolves. Include a schema version on events, and make the projection able to read older versions. Do not migrate old events by rewriting them; read them with compatible parsing logic.

    7. Common mistakes

    Treating the log as the context. The log grows without bound and cannot all be sent to the model. Put trimming and compaction in the projection layer, and keep the log complete.

    Writing UI state directly to save effort. If the UI changes state without going through the log, views diverge. Every state change should be written as an event first, then shown by projecting the log.

    Events that are too coarse or too fine. Too coarse—for example, packing a whole turn into one event—makes precise projection hard. Too fine—for example, one event per character—raises storage and read cost. A practical unit is usually one message, one tool call, or one result.

    Ignoring replay. A major value of an event stream is that it can be replayed. If projections are deterministic from the start, debugging is a matter of replaying the log to reconstruct exactly what the model saw.

    8. A migration path

    Migration can be staged.

    In the first stage, start writing events for existing sessions while keeping the current context array. This builds a complete history without changing live behavior.

    In the second stage, implement the projection function and switch model calls to a context derived from the log. Compare the old and new contexts, and use tests to confirm that the projection covers every message type.

    In the third stage, switch the UI, debugging, and audit to log projections. All views then share one source of data.

    Each stage needs its own checks. Replay tests can verify that the same log projects to the same result at different times. Consistency assertions can check that key events, such as tool results, appear in both the model view and the UI view. These checks catch missing projection rules before users see them.