08B.1 Kinds of State and Session Management

Agents & multimodalLesson 1 of 55,644 words6 parts
Module 08B · 0 of 5 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5

A chat that "remembers" is really a program that stores something between two requests. This lesson names the things worth storing (conversation state, workflow state and agent state), then builds the boring but critical machinery around them: session ids, tenant isolation, two-requests-at-once safety, expiry, and the choice between keeping state yourself or letting a provider keep it. You will build a small in-memory session store in plain Python, attack it with isolation and concurrency tests, and read real output. It is the first of four memory lessons: 08B.3 shrinks what a session holds, 08B.4 keeps facts across sessions, and 08B.5 covers failures, production stores and instruction files.

What you'll learn

  • The difference between conversation state, workflow state and agent state, who owns each, how long each lives, and why mixing them causes bugs
  • What a session is, what a good session id looks like, and the lifecycle of a session from creation to deletion
  • How to keep many users and many tenants apart: identity comes from your auth layer, one error for "not found" and "not yours", and tests that try to break isolation
  • What goes wrong when two requests hit the same session at once (the lost update) and three ways to prevent it: a lock, a version check and a per-session queue
  • Idle expiry vs absolute expiry, and how a session cleans itself up
  • Server-side vs client-held state with the two primary providers: OpenAI's previous_response_id chaining and Conversations API, and Anthropic's stateless Messages API (as of 1 December 2026)

What you don't need

  • API keys. The session store and all tests are standard-library Python and run offline with real output. No provider code runs in this lesson: Part 5 only makes the decision and links to the mechanics.
  • Docker, Redis or any database. The store is a dict behind a lock. Where state lives in production is 08B.5, Part 2.
  • The mechanics of each provider's conversation API. Lesson 03.2, Part 7 owns those. This lesson uses them to decide where the truth lives.

Setup

Python 3.11 or newer and nothing else. No packages are needed for the offline code:

bash
mkdir session-state && cd session-state
# nothing to install

The code is three files that sit next to each other: sessions.py (the library), test_sessions.py (isolation, expiry and concurrency tests) and state_kinds.py (the three kinds of state in one example). Run them with python3 <file>.


What you must be able to do after this lesson#

  • Classify a piece of state as conversation, workflow or agent state, and say which one must survive both a compaction and a restart
  • Build a session store with random ids, tenant-scoped reads, copies instead of live objects and one error for "not found" and "not yours"
  • Write tests that try to break tenant isolation, expiry and erasure, using a fake clock
  • Prevent a lost update with a version check, a lock or a per-session queue
  • Set idle and absolute timeouts and a sweep that physically deletes expired sessions
  • Decide between client-held and server-held conversation state, and record provider ids for erasure and replay

Why this matters for an AI engineer#

A language model remembers nothing between calls (02.7, Part 3). Everything that feels like memory is state that your system stored and sent back. The first memory bugs you will meet are not clever AI problems. They are ordinary state problems: user A seeing user B's chat, a turn that vanished because two requests raced, a session that never expires, a refund that ran twice after a restart.

You'll hear... You'll understand it after...
"Is that conversation state or workflow state?" Part 1: Three kinds of state
"Put the session id in a cookie, not in the prompt." 2.2 What a session id must be
"Tenant isolation is a correctness requirement, not a feature." Part 3: Many users and many tenants
"Users double-clicked send and we lost a message." Part 4: Two requests, one session
"When does a session end?" 2.3 The lifecycle of a session
"Do we need a database if we use previous_response_id?" Part 5: Server-held or client-held state
"How do we test that tenants cannot see each other?" 3.3 Attack your own isolation, Part 6: Evaluate it

Part 1: Three kinds of state#

1.1 Why the word "state" is not enough#

"State" in an LLM application means three different things that people lump together. Each has a different owner, a different lifetime and a different rule for what happens when it grows too big.

1.2 Conversation state, workflow state, agent state#

Conversation state Workflow state Agent state
What it holds What was said: user and assistant messages, tool calls and tool results Where a business process is: current step, order id, amount, approvals, idempotency keys What the running agent is doing inside one run: scratchpad, plan, step counter, budget used
Example "I want a refund for A17" / "Found it, $40" step=awaiting_payment_provider, refund_id=None steps_used=4, "order verified, waiting on provider"
Owner The chat layer Your business code (a state machine) The agent loop
Shape A list of messages, loosely typed text A small typed record, validated A grab bag the loop needs, often private
Lifetime A session, then trimmed or summarised Until the process finishes (can be days) One run; disposable
Can it be rewritten? Yes. You trim, summarise and redact it (08B.3) Only through defined transitions Yes, rebuilt from the other two if lost
Source of truth for business facts? No. Text can be summarised away or misread Yes No
If you lose it The bot forgets the chat A customer is refunded twice or never The run restarts from the workflow step

The row to remember is "source of truth for business facts". Never let the model's reading of the chat be the only record that a refund was approved. Write the fact into workflow state, in code, when it happens.

Lesson 08F.11 teaches how one framework (LangGraph) stores graph state and checkpoints. 08C.3 teaches durable execution without a framework. This lesson stays one level below both: what is stored, who may read it, how long it lives.

1.3 The three kinds in one example#

state_kinds.py uses the session store from Part 2 (printed there in full). A refund conversation is built up, then two things happen to it: the conversation is compacted, and the agent process restarts.

python
# state_kinds.py: three kinds of state in one refund conversation, and what each one survives
from sessions import SessionStore, append_turn

store = SessionStore()
s = store.create("acme", "user_1")

# Conversation state: what was said. Rewritable (trim, summarise); never the source of truth for business facts.
for role, text in [("user", "I want a refund for order A17"),
                   ("assistant", "Found A17, $40. Shall I submit the refund?"),
                   ("user", "yes please")]:
    s = append_turn(store, s.session_id, "acme", "user_1", role, text)

# Workflow state: where the business process is. Small, typed, durable, owned by your code.
s = store.get(s.session_id, "acme", "user_1")
s.workflow = {"flow": "refund", "order_id": "A17", "amount_cents": 4000,
              "step": "awaiting_payment_provider", "refund_id": None, "idempotency_key": "refund:A17:4000"}
s = store.save(s, expected_version=s.version)

# Agent state: what the running agent is doing inside one run. Disposable; rebuilt from the other two.
s = store.get(s.session_id, "acme", "user_1")
s.agent = {"run_id": "run_9", "steps_used": 4, "scratchpad": "order verified; waiting on provider"}
s = store.save(s, expected_version=s.version)

def survives(label, session):
    print(f"{label:<34} messages={len(session.messages)} workflow.step={session.workflow.get('step')!s:<26} agent={session.agent or '{}'}")

survives("before anything happens", s)

# 1. Compaction of the conversation: messages shrink, the business fact is untouched.
c = store.get(s.session_id, "acme", "user_1")
c.messages = [{"role": "system", "content": "Summary: user asked refund for A17 ($40) and confirmed."}]
c = store.save(c, expected_version=c.version)
survives("after compacting the conversation", c)

# 2. The agent process crashes: agent state is lost, workflow state tells us where to resume.
r = store.get(c.session_id, "acme", "user_1")
r.agent = {}
r = store.save(r, expected_version=r.version)
survives("after the agent process restarts", r)
print("resume from step:", r.workflow["step"], "| reuse idempotency key:", r.workflow["idempotency_key"])
Output · real, python3 state_kinds.py4 lines
before anything happens            messages=3 workflow.step=awaiting_payment_provider  agent={'run_id': 'run_9', 'steps_used': 4, 'scratchpad': 'order verified; waiting on provider'}
after compacting the conversation  messages=1 workflow.step=awaiting_payment_provider  agent={'run_id': 'run_9', 'steps_used': 4, 'scratchpad': 'order verified; waiting on provider'}
after the agent process restarts   messages=1 workflow.step=awaiting_payment_provider  agent={}
resume from step: awaiting_payment_provider | reuse idempotency key: refund:A17:4000

Read the three lines. Compacting changed messages from 3 to 1 and nothing else. The restart wiped agent and nothing else. The workflow step and the idempotency key survived both, which is why the restarted agent can resume without charging the customer twice (08A.7 explains idempotency keys).

1.4 Rules of thumb#

  • Store facts as workflow state, not as chat. Amounts, ids, approvals and decisions go into typed fields.
  • Derive agent state, do not trust it. If a run can be rebuilt from workflow state plus a short summary, a crash costs nothing.
  • Keep the three in separate fields, as Session does below, so that a trim of the chat can never delete a business fact.
  • Do not put secrets in any of them unless you encrypt them and have a reason (08B.5).
  • Memory across sessions is a fourth thing. Facts that outlive a session (a user's language, an old incident) belong to long-term memory (08B.4, 08B.2).

Part 2: Sessions#

2.1 What a session is#

A session is the container for one user's ongoing interaction with your app: one chat thread, one coding task, one support case. The session id is the label on the container. Your server receives a request, finds the session by id, loads its state, does the work, saves the state, and answers.

2.2 What a session id must be#

  • Random and unguessable. Use secrets.token_urlsafe(16) (128 bits of randomness), never a counter, a timestamp or user_id + "_chat". A guessable id lets one user try another's.
  • Opaque. The id carries no meaning. Do not encode the email, the tenant or the date in it.
  • Not personal data. It will appear in logs, URLs and error messages. Providers also ask you not to send personal data in identifiers: see 03.2, 10.2.
  • A lookup key, never a credential on its own. Knowing the id must not be enough. The store also checks that the authenticated tenant and user own it (Part 3).
  • Separate from your auth token. Logging in proves who someone is. A session id picks which conversation they mean. One user can have many sessions.

2.3 The lifecycle of a session#

stateDiagram-v2
    [*] --> Active: create
    Active --> Active: request (resets idle timer)
    Active --> Idle: no requests
    Idle --> Active: request before idle limit
    Idle --> Expired: idle limit reached
    Active --> Expired: absolute limit reached
    Active --> Closed: user ends chat
    Expired --> Deleted: sweep
    Closed --> Deleted: retention rule met
    Deleted --> [*]

Two clocks matter:

  • Idle timeout (sliding). The session ends after N minutes with no activity. Each request moves the deadline. Typical for chat. This stops forgotten sessions from living forever.
  • Absolute timeout (fixed). The session ends N hours after creation, however busy it is. This limits how long a stolen session id stays useful and how large a history can grow.

Use both. Idle alone lets a busy bot keep a session for months. Absolute alone logs out an active user in the middle of a task.

What happens at expiry is a product decision. Options: delete everything; keep the workflow state but drop the chat; archive a summary into long-term memory (08B.4) and delete the rest. Whatever you pick, write it down as a retention rule (08B.5, Part 2).

2.4 The session store#

Here is the whole library. Read it top to bottom: the dataclass holds the three kinds of state, get enforces ownership and expiry, save refuses stale writes, delete_user is erasure and sweep is cleanup.

python
# sessions.py: an in-memory session store with tenant isolation, expiry and version checks
from __future__ import annotations

import copy
import secrets
import threading
import time
from dataclasses import dataclass, field
from typing import Callable


class SessionNotFound(Exception):
    """Raised for unknown, expired AND foreign sessions: the caller cannot tell which."""


class VersionConflict(Exception):
    """Raised when someone else changed the session since you read it."""


@dataclass
class Session:
    session_id: str
    tenant_id: str
    user_id: str
    created_at: float
    last_active: float
    version: int = 0
    messages: list[dict] = field(default_factory=list)      # conversation state
    workflow: dict = field(default_factory=dict)            # workflow state
    agent: dict = field(default_factory=dict)               # agent state


class SessionStore:
    def __init__(self, idle_ttl: float = 1800, absolute_ttl: float = 8 * 3600,
                 clock: Callable[[], float] = time.time) -> None:
        self.idle_ttl, self.absolute_ttl, self.clock = idle_ttl, absolute_ttl, clock
        self._data: dict[str, Session] = {}
        self._lock = threading.Lock()

    def create(self, tenant_id: str, user_id: str) -> Session:
        now = self.clock()
        s = Session(secrets.token_urlsafe(16), tenant_id, user_id, now, now)
        with self._lock:
            self._data[s.session_id] = s
        return copy.deepcopy(s)

    def _expired(self, s: Session) -> bool:
        now = self.clock()
        return now - s.last_active > self.idle_ttl or now - s.created_at > self.absolute_ttl

    def get(self, session_id: str, tenant_id: str, user_id: str) -> Session:
        """tenant_id and user_id come from your auth layer, never from the request body."""
        with self._lock:
            s = self._data.get(session_id)
            if s is None or s.tenant_id != tenant_id or s.user_id != user_id:
                raise SessionNotFound(session_id)           # same error for "not yours"
            if self._expired(s):
                del self._data[session_id]                  # lazy cleanup
                raise SessionNotFound(session_id)
            return copy.deepcopy(s)                         # callers get a copy, not the live object

    def save(self, updated: Session, expected_version: int) -> Session:
        """Compare-and-set: the write succeeds only if nobody saved since you read."""
        with self._lock:
            s = self._data.get(updated.session_id)
            if s is None or s.tenant_id != updated.tenant_id or s.user_id != updated.user_id:
                raise SessionNotFound(updated.session_id)
            if s.version != expected_version:
                raise VersionConflict(f"stored v{s.version}, you read v{expected_version}")
            updated.version = expected_version + 1
            updated.last_active = self.clock()
            self._data[s.session_id] = copy.deepcopy(updated)
            return copy.deepcopy(updated)

    def delete_user(self, tenant_id: str, user_id: str) -> int:
        """Erasure: remove every session of one user in one tenant."""
        with self._lock:
            doomed = [k for k, s in self._data.items()
                      if s.tenant_id == tenant_id and s.user_id == user_id]
            for k in doomed:
                del self._data[k]
            return len(doomed)

    def sweep(self) -> int:
        """Background cleanup of expired sessions that nobody asked for again."""
        with self._lock:
            doomed = [k for k, s in self._data.items() if self._expired(s)]
            for k in doomed:
                del self._data[k]
            return len(doomed)


def append_turn(store: SessionStore, session_id: str, tenant_id: str, user_id: str,
                role: str, text: str, retries: int = 10) -> Session:
    """Read, change, save with a version check; on conflict re-read and try again."""
    for _ in range(retries):
        s = store.get(session_id, tenant_id, user_id)
        v = s.version
        s.messages.append({"role": role, "content": text})
        try:
            return store.save(s, expected_version=v)
        except VersionConflict:
            continue
    raise VersionConflict("gave up after retries")

Four design choices are worth naming:

  1. get takes tenant_id and user_id as required arguments. There is no get(session_id). A forgotten filter is the most common cause of leaks, so the API makes forgetting impossible.
  2. One error for "unknown", "expired" and "not yours". If a stranger gets "forbidden" for a real id and "not found" for a fake one, they can test which ids exist. One error hides the difference.
  3. get returns a copy. Code that edits the returned object cannot change the store by accident. Changes only happen through save.
  4. save is compare-and-set on version. Part 4 explains why.

Part 3: Many users and many tenants#

This part extends 08B.2, Part 5 (namespaces and access control for memory records) one level down, to the session store, and adds attack tests you can run.

A tenant is one customer organisation in a multi-customer product (a "workspace" or "account"). A user belongs to a tenant. Isolation means a request from tenant A can never read, write or even detect tenant B's data. This is the same discipline as multi-tenant retrieval (06.6, Part 3) and multi-tenant memory (08B.2, Part 5). Sessions are where it starts.

3.1 Identity comes from auth, never from the request#

The scope (tenant_id, user_id) is resolved by your authentication layer before any LLM code runs. It is then passed down as plain arguments. The model never sees it and can never change it. If the model can call a tool with a user_id argument, it can read other users' data. A tool that needs the current user takes it from the run context, not from model output (08A.2).

3.2 Same error, same shape, same timing#

When a lookup fails, the caller should learn nothing about why. SessionNotFound covers three cases. In a web app, return the same HTTP status and body for all three.

3.3 Attack your own isolation#

The test file below tries to break the store the way a curious user would: a stolen session id presented by another tenant, the same user_id in two tenants, a different user in the same tenant, and edits to returned objects. It also checks expiry and erasure with a fake clock, an object you control so a test can "wait" 30 minutes in zero seconds.

python
# test_sessions.py: tenant isolation, expiry, and the two-requests-per-session race
import threading

from sessions import SessionNotFound, SessionStore, VersionConflict, append_turn


class FakeClock:
    def __init__(self) -> None:
        self.now = 1_000_000.0
    def __call__(self) -> float:
        return self.now


def check(name: str, ok: bool) -> None:
    print(f"{'PASS' if ok else 'FAIL'}  {name}")
    assert ok, name


clock = FakeClock()
store = SessionStore(idle_ttl=600, absolute_ttl=3600, clock=clock)

# 1. Tenant isolation: same user_id in two tenants, and a stolen session id
a = store.create("acme", "user_1")
b = store.create("globex", "user_1")
check("session ids are different and unguessable-looking", a.session_id != b.session_id and len(a.session_id) >= 20)
try:
    store.get(a.session_id, "globex", "user_1")      # globex presents acme's session id
    check("foreign tenant cannot read a session", False)
except SessionNotFound:
    check("foreign tenant cannot read a session", True)
try:
    store.get(a.session_id, "acme", "user_2")        # same tenant, other user
    check("other user in same tenant cannot read it", False)
except SessionNotFound:
    check("other user in same tenant cannot read it", True)
check("owner can read it", store.get(a.session_id, "acme", "user_1").session_id == a.session_id)

# 2. Callers get copies: editing a returned object does not change the store
copy1 = store.get(a.session_id, "acme", "user_1")
copy1.messages.append({"role": "user", "content": "not saved"})
check("returned objects are copies", store.get(a.session_id, "acme", "user_1").messages == [])

# 3. Expiry: idle timeout slides, absolute timeout does not
clock.now += 500
append_turn(store, a.session_id, "acme", "user_1", "user", "still here")      # activity resets idle
clock.now += 500                                                               # 1000s since creation, 500 idle
check("activity keeps an idle session alive", store.get(a.session_id, "acme", "user_1").version == 1)
clock.now += 700                                                               # now 1200s idle, limit is 600
try:
    store.get(a.session_id, "acme", "user_1")
    check("idle timeout expires the session", False)
except SessionNotFound:
    check("idle timeout expires the session", True)

c = store.create("acme", "user_3")
for _ in range(8):                                                             # busy for 4000s, limit is 3600
    clock.now += 500
    try:
        append_turn(store, c.session_id, "acme", "user_3", "user", "ping")
    except SessionNotFound:
        break
try:
    store.get(c.session_id, "acme", "user_3")
    check("absolute timeout ends even a busy session", False)
except SessionNotFound:
    check("absolute timeout ends even a busy session", True)

# 4. Two requests for one session at the same moment
def race(save_fn) -> int:
    s = store.create("acme", "user_4")
    barrier = threading.Barrier(2)
    def request(text: str) -> None:
        mine = store.get(s.session_id, "acme", "user_4")      # both read version 0
        barrier.wait()                                          # force the unlucky interleaving
        mine.messages.append({"role": "user", "content": text})
        save_fn(mine)
    ts = [threading.Thread(target=request, args=(t,)) for t in ("first", "second")]
    [t.start() for t in ts]; [t.join() for t in ts]
    return len(store.get(s.session_id, "acme", "user_4").messages)

def blind_save(sess):                       # a store with no version check: last write wins
    with store._lock:
        store._data[sess.session_id] = sess

print("turns kept with blind overwrite:", race(blind_save), "(two were sent)")

conflicts = []
def checked_save(sess):
    try:
        store.save(sess, expected_version=0)
    except VersionConflict as e:
        conflicts.append(str(e))
print("turns kept with a version check:", race(checked_save), "| rejected:", conflicts)

# 5. The retry helper makes both turns land
s = store.create("acme", "user_5")
ts = [threading.Thread(target=append_turn, args=(store, s.session_id, "acme", "user_5", "user", t))
      for t in ("one", "two", "three", "four")]
[t.start() for t in ts]; [t.join() for t in ts]
final = store.get(s.session_id, "acme", "user_5")
check("four parallel appends with retry all land", len(final.messages) == 4 and final.version == 4)

# 6. Erasure and sweep
g = store.create("globex", "user_5")          # same user_id, different tenant
check("delete_user removes only that user's sessions in that tenant",
      store.delete_user("acme", "user_5") == 1 and store.get(g.session_id, "globex", "user_5"))
clock.now += 10_000
print("sweep removed", store.sweep(), "expired sessions")
Output · real, python3 test_sessions.py13 lines
PASS  session ids are different and unguessable-looking
PASS  foreign tenant cannot read a session
PASS  other user in same tenant cannot read it
PASS  owner can read it
PASS  returned objects are copies
PASS  activity keeps an idle session alive
PASS  idle timeout expires the session
PASS  absolute timeout ends even a busy session
turns kept with blind overwrite: 1 (two were sent)
turns kept with a version check: 1 | rejected: ['stored v1, you read v0']
PASS  four parallel appends with retry all land
PASS  delete_user removes only that user's sessions in that tenant
sweep removed 4 expired sessions

The two lines starting "turns kept" are explained in Part 4. Everything else passed: the foreign tenant, the other user and the same-name user in a second tenant all fail to read a session that is not theirs, and erasing one user in one tenant left the same-named user in another tenant alone.

3.4 Where leaks really happen#

Passing these tests does not make a system safe. Real leaks hide in places the store does not control:

  • Caches. A response cache keyed by the prompt alone serves tenant A's answer to tenant B when the prompts match. Put tenant_id in every cache key (03.7, 11B.3).
  • Logs and traces. Messages in logs outlive the session. Redact them and give them their own retention rule (11A.3).
  • Vector indexes and long-term memory. Retrieval must filter by scope before ranking (08B.2, 5.1).
  • Background jobs. A worker that processes "all sessions" may mix scopes. Pass scope into each job.
  • Provider-side copies. store=True on OpenAI creates a second copy of the conversation under the provider's retention (Part 5).
  • Shared mutable defaults. A module-level list reused across requests is shared across tenants. Create state per session.

Part 4: Two requests, one session#

Deep-dive

This part extends 03.2, 5.6 ("serialize writes per conversation") with the race itself, three ways to prevent it, and a test that forces the bad ordering.

4.1 The lost update#

Users double-click send. Mobile apps retry on a flaky network. A webhook and a human reply arrive together. Now two requests for the same session run in parallel:

  1. Request A reads the session (version 0, no messages).
  2. Request B reads the session (version 0, no messages).
  3. A appends "first" and writes.
  4. B appends "second" and writes, overwriting A's write.

One turn is gone, and no error was raised. This is a lost update. It is a plain concurrency bug, but with LLMs it is more harmful because each request can take many seconds, so the window is wide, and a lost tool result can leave the history in a shape the provider rejects (03.2, Part 4).

4.2 Three ways to prevent it#

Approach How it works Good for Watch out for
Lock per session Take a lock for the session id before reading, release after saving One server process, short critical sections Holding a lock during a 30-second model call blocks the user's next click. Lock around read-modify-write only, not around the model call
Optimistic version check Read with a version number. Save only if the stored version is unchanged. On conflict, re-read and retry Many servers, short writes. The default choice Retries must re-apply the change to fresh state, not resend the stale object
Queue per session Requests for one session go through one ordered worker (a queue keyed by session id) Agent runs that take minutes, "one run at a time per session" Needs a queue; decide what to do with a message that arrives mid-run (queue it, reject it, or interrupt)

In a real database the version check is one statement: UPDATE sessions SET ... , version = version + 1 WHERE id = ? AND version = ?. If zero rows changed, someone else won (08B.5 shows the conceptual SQL and DynamoDB condition).

A separate question: what should happen when a second message arrives while the first is still being answered? Three honest options: queue it behind the first, reject it with "still working", or cancel the first and start over. Pick one on purpose. The long-running case is covered in 08A.13.

4.3 Watching it happen#

The race section of test_sessions.py uses a threading.Barrier to force the unlucky ordering every time, so the result does not depend on luck. It runs the same race against a store with no version check and against save, then fires four parallel append_turn calls (which retry on conflict). Look back at the output in 3.3:

  • With a blind overwrite, 1 turn kept out of 2 sent: the lost update.
  • With the version check, one request was rejected (stored v1, you read v0). Nothing was silently lost. The rejected request must read again and retry, which append_turn does automatically.
  • Four parallel append_turn calls all landed, and the final version was 4.

4.4 Idempotent requests#

Retries also come from clients. Give every user message a client-generated request id and store the ids you have processed. A retried request with a seen id returns the stored answer instead of calling the model and running tools again. This is the same idea as idempotency keys for tools (08A.7), applied one level up.


Part 5: Server-held or client-held state#

Reference

So far you hold the state. Providers can hold some of it for you. Lesson 03.2, Part 7 owns the mechanics (OpenAI store, previous_response_id and the Conversations API, Anthropic's stateless Messages and beta message threads), and 03.2, 7.10 has the full comparison table and a runnable "chain when you can, replay when you can't" sample. This part keeps only what matters for session design, checked against the official docs on 1 December 2026 (they will change):

  • Anthropic Messages is stateless by default. You send the full history each request, so your session store is the only copy. The beta message threads are a short-lived cache, not durable state: a thread expires 5 minutes after its last request (03.2, 7.7).
  • OpenAI can hold the transcript. previous_response_id chaining keeps responses for 30 days by default, the Conversations API has no 30-day expiry, and chaining does not save money: all previous input tokens in the chain are still billed as input. Top-level instructions apply only to the request that sends them, so send them every time.
  • store defaults to true on OpenAI Responses. If you do not write store=False you have chosen a 30-day provider-side copy of the conversation without deciding to. Write store= explicitly and document why.
  • Make your store the source of truth. Use server-side chaining as an optimisation, keep your own copy so you can replay if a provider id expires, and record the provider's ids in a provider_state field of your session so one user's erasure request reaches every copy.
  • Provider-side state holds conversation state only. It does not hold your workflow state, and it does not turn a transcript into memory about the user. Workflow state stays in your store in every design, and facts that outlive a session still need the machinery of 08B.4.

Part 6: Evaluate it#

State bugs are cheap to test and expensive to find in production. This part says what to measure for sessions and state, then links to the evaluation lessons. Start with the concepts, then the tooling.

Concept lessons (read these first)

What to measure for sessions and state

Question Metric Pass rule
Can one tenant or user read another's session? Canary leak count 0 across all probes
Is any turn lost under parallel requests? Turns kept / turns sent 100%, or the loser gets a clear conflict
Does expiry fire? Reads of an expired session that succeed 0
Does erasure erase? Records found for an erased user, in the store, in logs and in provider objects 0
Does workflow state survive compaction and restart? Workflow fields equal before and after Equal

A tiny eval you can run now. Inputs: the fixtures in test_sessions.py (two tenants, one stolen id, two racing requests, one expired session). Metric: count of FAIL lines plus the "turns kept" ratio under the version check. Pass rule: zero failures and, for every racing pair, either both turns kept or exactly one explicit conflict. That is already a regression suite: put it in CI and add a case each time a bug is found.

DeepEval lessons (required track)

Inspect lessons (optional)

The revision-1 bullet for this whole item, stated once here and repeated in each of the memory lessons (08B.3, 08B.4 and 08B.5): evaluating memory and compaction (write and read quality, compaction fidelity, long-session tests) links to 10A.11 for the concepts and to 10B.4, 10B.6 and 10B.15 §10.3 for the tooling.


Common misconceptions#

  • "The model keeps the conversation." It does not. Something outside the model stores and resends it (Part 5).
  • "A random session id is enough to protect it." Knowing an id must never be sufficient. Check tenant and user on every read.
  • "previous_response_id means we do not need a database." It means the provider holds a transcript under its retention rules. Workflow state, erasure and portability still need your store.
  • "Chaining makes long chats cheaper." OpenAI's docs say previous input tokens in the chain are billed as input tokens.
  • "Locking the session around the whole request is safe." It also freezes the user's next click for the length of a model call. Lock or version-check the read-modify-write, not the model call.
  • "Expiry deletes the data." Marking something expired and physically deleting it are different events (08B.5).
  • "Conversation state is where the business facts live." It is the least reliable place for them. Use workflow state.

Key takeaways#

  • Keep conversation, workflow and agent state in separate fields. Compaction touches only the first. A restart should lose only the third.
  • A session id is random, opaque, not personal data and not a credential by itself. Identity comes from auth and is passed as required arguments.
  • Return one error for unknown, expired and foreign sessions, return copies not live objects, and test isolation with attacks.
  • Use a version check (or a lock, or a queue) so two requests for one session cannot silently overwrite each other.
  • Use an idle timeout and an absolute timeout, plus a sweep that physically deletes.
  • Make your store the source of truth. Treat provider-held state (previous_response_id, Conversations, message threads) as an optimisation, and write store= on purpose.

Terms introduced in this lesson#

Term Meaning
Conversation state The messages, tool calls and tool results of a chat; for the model's eyes and rewritable
Workflow state A typed record of where a business process is; the source of truth for business facts
Agent state What a running agent holds inside one run (scratchpad, plan, budget); disposable
Session One user's ongoing interaction with an app, identified by a session id
Session id A random, opaque lookup key for a session; never a credential by itself
Tenant One customer organisation in a multi-customer product
Tenant isolation The guarantee that one tenant cannot read, write or detect another's data
Idle timeout Expiry after a period without activity; the deadline slides with each request
Absolute timeout Expiry a fixed time after creation, regardless of activity
Lost update Two parallel read-modify-write operations where the second silently erases the first
Optimistic concurrency Saving only if a version number is unchanged; otherwise reject and retry
Compare-and-set An atomic "write if the current value is what I read" operation
Request id A client-generated id that lets the server recognise a retried request
Server-held state Conversation history kept by the provider (previous_response_id, Conversations, message threads)
Client-held state Conversation history kept by your app and resent each turn
Fake clock A controllable time source so tests can "wait" instantly

Exercises#

  1. Absolute vs idle. Add a close(session_id, ...) method that marks a session closed (so get raises SessionNotFound) but keeps its workflow for 7 days for audit. Hint: add a closed_at field and let sweep delete only when closed_at is older than the retention period; keep the same single error for callers.
  2. A third kind of conflict. Change append_turn so that on conflict it gives up immediately when the other writer changed workflow["step"], and retries only when the other writer changed messages. Hint: compare workflow between your read and the fresh read before re-applying.
  3. Request ids. Add seen_request_ids to the session and make append_turn return the previous result when it receives an id it has already processed. Test with a double-submit. Hint: store a small dict request_id -> version_after and bound its size.
  4. Per-session queue. Replace the version check with a per-session queue.Queue and one worker thread per active session. Show that four parallel appends all land, in arrival order. Hint: create the worker lazily in a dict[session_id, Queue] guarded by the store lock and stop it on expiry.
  5. Provider ids and erasure. Extend Session with provider_state: dict and write erase_everywhere(store, tenant, user, delete_openai_response) that returns the list of provider objects the caller still has to delete. Hint: iterate the user's sessions before delete_user; collect response or conversation ids first, because deleting the session also deletes the ids you need.
  6. Fake clock for a provider TTL. Simulate OpenAI's 30-day response retention: a ProviderStore that returns an error for a previous_response_id older than 30 days. Make your app fall back to replaying its own history. Hint: catch the error, rebuild input from session.messages, and record the new response id.

Check yourself#

  1. What is the difference between conversation state, workflow state and agent state, and which one must survive both a compaction and a process restart?
  2. Why should a business fact such as "refund approved" be written to workflow state instead of being left in the chat?
  3. Name four properties a good session id has.
  4. Why does the store return the same error for an unknown session and for someone else's session?
  5. Where must tenant_id and user_id come from, and why must they not come from the model or the request body?
  6. Describe the lost-update race with two requests and say how a version check changes the outcome.
  7. Compare a per-session lock, an optimistic version check and a per-session queue: one strength and one risk each.
  8. What is the difference between an idle timeout and an absolute timeout, and why use both?
  9. Per the docs checked on 1 December 2026, is Anthropic's Messages API stateful? What does OpenAI's previous_response_id change about billing and about instructions?
  10. Why is "your store is the source of truth" the safer default, and what extra fields should your session keep when you do use provider-side chaining?

Further resources#


← Module 08A: Agent Foundations | Module 08B overview | 08B.2 — Memory for Agents: Short-Term and Long-Term →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close