Skip to content
Visual explainer 2h 30m to learn 4 steps

Agent run state, conversation history and long-term memory

Separate per-run state, conversation history, persisted workflow state and long-term memory with clear ownership, isolation and deletion.

By Invicly Tech, , in Generative AI, Agentic AI and RAG. About 10 minutes to read.

Topic 18 of 34

In short

An agent keeps four different kinds of state, and mixing them causes leaks and bugs. Per-run state lives for one request; conversation history lives for one session; persisted workflow state lets a long task pause and resume; long-term memory carries facts across sessions. Each needs a clear owner, an isolation key and a deletion rule.

Explained simply

An assistant has to remember things at different time scales. During one answer it tracks which tools it has called. During a chat it remembers what you said a minute ago. Some tasks wait days for approval. And some facts, like your preferred language, might be useful next month.

These are four different kinds of state. If you store them all in one place, things go wrong. Old tool results pile up, one user sees another's chat, or deleted data comes back.

The fix is to give each kind its own home, its own owner and its own lifetime. Per-run state disappears when the answer is done. Chat history expires after a while. Workflow state lasts until the task finishes. Long-term memory lasts until the user deletes it.

Every piece of stored state is tagged with who it belongs to: the tenant, the user and the session. Every read checks those tags. That is what keeps users apart.

Press Play on a diagram to walk through it one step at a time.

LayersFour kinds of agent state, shortest to longest lived
  1. 1
    Per-run state

    Steps, tool results, budgets; one request

  2. 2
    Conversation history

    Turns in one session; trimmed and expired

  3. 3
    Persisted workflow state

    Checkpoint to resume, e.g. awaiting approval

  4. 4
    Long-term memory

    Facts across sessions; owned by the user, deletable

CompareOwnership, isolation and deletion
Run and history
  • Owner: the request, then the session
  • Key: tenant, user, session
  • Run state dropped at the end
  • History expires, e.g. 30 days
Workflow state
  • Owner: the business process
  • Key: tenant and task ID
  • Lives until the task closes
  • Versioned checkpoints
Long-term memory
  • Owner: the user
  • Key: tenant and user
  • User can view and delete
  • Deletion covers every copy

In depth

Per-run state

Per-run state is everything the loop needs while answering one request: the question, the step count, budgets used, tool calls and their results, and the evidence gathered so far. Keep it in a typed object created at the start of the run and passed through the loop, not in global variables or module-level caches.

When the run ends, the object is dropped. What survives is a trace: step names, tool names, source IDs, timings and token counts, with sensitive text redacted. The final answer and its source IDs go into conversation history.

Because the object is created per request, two requests running at the same time never share counters or evidence. This also makes the loop easy to test: build a run state, feed it scripted model steps, inspect the result.

  • Typed object created per request
  • Budgets, steps, tool results, evidence
  • Never stored in globals
  • Dropped at the end; a redacted trace remains

Conversation history per session

Conversation history is the list of turns in one session: user messages, final answers and, if you choose, a short record of tool calls. Store it in a table keyed by tenant, user and session ID, and check all three on every read. A session ID alone should never be enough to load history.

History grows, and every turn is sent to the model again, so set a budget. Keep the last few turns in full and replace older ones with a short summary, or drop them. Store raw tool results only if you need them; usually the answer and its source IDs are enough.

Set an expiry, for example 30 days, and delete expired sessions with a scheduled job. Some hosted model APIs can also keep conversation state on their side; if you use that, its retention and deletion rules become part of your design.

FlowLoading history for a new turn
  1. 1
    Authenticate

    Get tenant and user from the session token

  2. 2
    Load by key

    tenant + user + session_id must all match

  3. 3
    Trim

    Recent turns in full, older ones summarised

  4. 4
    Add new turn

    Send within the token budget

  5. 5
    Save answer

    Text and source IDs, with expiry time

Persisted workflow state

Some tasks cannot finish in one request. A refund exception might need a manager's approval, which could take two days. Persisted workflow state is a checkpoint stored in the database: the task ID, current step, the data needed to continue, who it is waiting for and a deadline.

When the approval arrives, a worker loads the checkpoint, checks it is still valid, and continues. The checkpoint should be versioned, so a code change does not break old tasks, and every transition should be recorded, so you can see what happened.

Keep workflow state separate from chat history. The task belongs to the business process, not to the conversation, and it may outlive the session. Give it its own retention rule, often tied to the record it relates to, such as the ticket.

Long-term memory: ownership and deletion

Long-term memory stores facts across sessions, such as prefers answers in Spanish or works in the Lisbon office. It is personal data, so treat it that way. Store each memory with the user it belongs to, where it came from (which session and turn), when it was created and when it expires. Prefer explicit memories the user confirmed over facts the model inferred.

Never write tool results or retrieved documents into memory. They have their own permissions in the corpus, and copying them would bypass those checks later.

Deletion must be complete. If memories are copied into summaries, caches or an embedding index, delete those too, and write a test that creates a memory, deletes it and checks every store. Show users what is remembered and let them remove it.

  • One owner per memory: the user
  • Record provenance and expiry
  • Prefer confirmed over inferred facts
  • Never copy documents or tool results
  • Test deletion across every copy

Learn it in 4 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Define per-run state~40m
  2. 2
    Store conversation history per session~40m
  3. 3
    Persist workflow state~40m
  4. 4
    Scope and delete long-term memory~40m

Key points

  • Key every stored item by tenant, user and session so one user never reads another's state.
  • Per-run state is discarded at the end of the run, apart from a redacted trace.
  • Conversation history grows each turn, so trim or summarise it within a token budget.
  • Long-term memory needs consent, provenance, a retention period and a working delete.
  • Retrieved documents are not memory; they stay in the corpus with their own permissions.

Key terms

Tap a card to flip it. 0/5 known

Examples

Isolated history storage in PostgreSQL

Prerequisites: the local PostgreSQL from module 3. Step 1: create a history table with tenant, user and session columns and an expiry. Step 2: always read with all three keys. Step 3: run a test where user B supplies user A's session ID. Expected evidence: zero rows returned for user B. Cleanup: the scheduled delete removes expired rows; drop the table to undo the lab.

sql
CREATE TABLE chat_turns (
  tenant_id text NOT NULL, user_id text NOT NULL, session_id uuid NOT NULL,
  turn int NOT NULL, role text NOT NULL, content text NOT NULL,
  source_ids text[] NOT NULL DEFAULT '{}',
  expires_at timestamptz NOT NULL DEFAULT now() + interval '30 days',
  PRIMARY KEY (tenant_id, user_id, session_id, turn)
);
SELECT role, content, source_ids FROM chat_turns
WHERE tenant_id = $1 AND user_id = $2 AND session_id = $3
ORDER BY turn DESC LIMIT 6;
DELETE FROM chat_turns WHERE expires_at < now();

Deleting a memory everywhere

Scenario: a user asks the assistant to forget their office location. Step 1: the API deletes the memory row for that tenant and user. Step 2: it invalidates the cached profile summary that included the fact. Step 3: a test checks the memory table, the cache and the next prompt built for that user. Expected evidence: none of them contains Lisbon. If the test finds a copy, the deletion is incomplete and the release is blocked.

python
def test_forget_removes_every_copy(memory, cache, build_prompt):
    memory.add('acme', 'u1', 'office', 'Lisbon', source='s1#t4')
    memory.forget('acme', 'u1', 'office')
    assert memory.get('acme', 'u1', 'office') is None
    assert 'Lisbon' not in (cache.get('profile:acme:u1') or '')
    assert 'Lisbon' not in build_prompt('acme', 'u1', 'Where do I work?')

Quick reference

  • Per-run state: typed object per request; dropped at the end, redacted trace kept
  • History key: tenant + user + session; never load by session ID alone
  • Trim history to a token budget: recent turns in full, older ones summarised
  • Workflow state: versioned checkpoint for paused tasks, separate from chat
  • Long-term memory: user-owned, provenance, expiry, viewable and deletable
  • Never copy retrieved documents or tool results into memory
  • Test deletion across tables, caches, summaries and indexes

Common mistakes

  • Storing conversation history in a global dictionary keyed only by session ID that clients can guess.
  • Saving tool results that contain other users' data into long-term memory.
  • Deleting a user's memory rows but leaving copies in caches, summaries or embeddings.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Where should the count of tool calls made so far in this answer live?

Question 2

2Why is loading history by session ID alone risky?

Question 3

3Why should retrieved documents not be stored in long-term memory?

Question 4

4A refund exception waits for a manager for two days. What stores its progress?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    For each item, name the state type: tokens used so far, the user's last question, a task waiting for approval, the user's preferred language.

  2. Exercise 2medium

    Write a typed RunState class with budgets, counters and gathered source IDs, and a method that says whether another tool call is allowed.

  3. Exercise 3hard

    Write a test that two concurrent runs for different users never share history or run state.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is the model's context window a kind of memory?
Only for the current call. Anything you want later must be stored by your application and sent again.
Should the assistant remember things automatically?
Be careful. Facts the user confirms are safer than facts the model guesses, and users should be able to see and delete what is kept.
How long should I keep chat history?
As short as your use case allows, set as an explicit expiry. Many support tools keep days or weeks, not forever.

Go deeper

ShareXLinkedInWhatsApp