Kinds of state: conversation, task, environment, long-term memory

Study time
≈ 2 h (estimate)
Needs
L3-M04-L05
Updated
2026-11-04

Progress is saved in this browser only. No account, nothing is sent to a server.

Draft · reviewed by AI, not yet by a person. Content may change. English translation: AI-assisted, not human-reviewed.
On this page

Module: L3-M05 · Duration: ~110 minutes (estimate, including the independent exercise) · Previous: L3-M04-L05 (the trajectory evaluator) · Next: L02

1. Introduction

The earlier modules graded one run: the scenario starts, the agent works, and you read the end state (L3-M03) and the path (L3-M04). A real chat assistant does not live in one run. A student gives their name at turn 1, sets a rule at turn 2, asks again at turn 30, closes the app, reopens it the next day, and another student uses the same service at the same moment. Each of those depends on a piece of state that lives in a different place, has a different lifetime, and breaks in a different way.

Anthropic's article on evals for agents says that conversational agents, unlike traditional chatbots, "maintain state, use tools, and take actions mid-conversation" [R1]. So a tester's first question is not "does the agent answer correctly" but "what does the agent remember, where, for whom, and for how long". This lesson answers that question for ThuVien Mini (a fictional product, now a chat assistant) with a state inventory and probes (questions that read state back) that show whether each piece of state survives a context trim, a new session, or another student asking. The product of the lesson: lab/state.py, the inventory data/inventory.json passing validate_inventory, and in §9 a survival table plus two inventory items you write yourself.

2. Learning objectives

  1. Distinguish the four kinds of state (conversation, task, environment, long-term memory) and derived state, and give an example of each in an agent. Read: §4.1.
  2. Describe a state item by its scope, key, lifetime and writers. Read: §4.2, §5.1.
  3. Write the items of a state inventory and fix them until validate_inventory reports no errors. Practice: §8.2 (part A), §9 (TODO 3).
  4. Run survival and locate, and explain why a probe must pass the control check before its result means anything. Read: §5.2. Practice: §8.2 (parts B, C), §9.
  5. Distinguish "the store has the data" from "the agent sees the data" when writing tests. Read: §6.1.

3. Prerequisites and tools

  • L1-M05-L05 (conversation state at the level of one follow-up turn: does the next turn still have the previous turn's context, §4.2), L3-M01-L02 (the agent loop), L3-M03-L04 (checking the end state in the environment), L1-M01-L02 (tokens and the context window). Code lab code-labs/l3-m05.
  • Terms kept apart. A session is a sequence of turns sharing one history, identified by a session id. The context is the list of messages the agent actually receives at a turn; it is rebuilt from the history every turn and can be shorter than the history (L02). A probe here is an ordinary question sent to the agent to read a piece of state back through its reply, not by reading the service's internals directly; it differs from the probes that measure judge bias in L2-M04-L03. State in this module is broader than the "loop state" (the ledgers in the sandbox) of L3-M01-L02.
  • The assistant in the lab is a rule-based, simulated program, not a language model: it answers only from that turn's context and from the session's tools. Every student, name, class and phone number is fictional.

4. Concepts

4.1 Four kinds of state, plus derived state

A chat agent has at least four kinds of state. In ThuVien Mini (lab/app.py):

Kind Example in the lab Where it lives When it is lost
Conversation "My name is Lumi.", "Only recommend story books." sessions[sid]["history"] when the session ends; partly when the context is trimmed
Task a borrow waiting for the student to answer "yes" sessions[sid]["task"] when the task finishes or the session ends
Environment books on loan, the phone number on file the library (App.loans, students.json) not lost with the session; changes when a tool writes
Long-term memory "Remember that my class is K7Q." App.memory lives across sessions until it is corrected or deleted

Platforms give these their own names. OpenAI's documentation says each text generation request is "independent and stateless", and an application builds a multi-turn conversation by sending the earlier messages again, or uses the Conversations API to store conversation state as an object with "its own durable identifier" [R2]. LangGraph separates two systems: a checkpointer stores the state of a thread ("short-term, thread-scoped memory"), a store keeps data across threads ("long-term, cross-thread memory") such as user preferences [R3]. Anthropic's article on context engineering describes structured note-taking ("agentic memory"): the agent writes notes outside the context window and pulls them back into the context later [R4]. The names differ, but the tester's questions are the same.

Besides these four kinds, the lab records derived state separately: copies or condensed versions of other state, such as this turn's context, a summary, and the reply cache. They are not a source of truth, but bugs like to hide there: a summary that loses a rule (L02), a cache that gives one student's answer to another (L04).

4.2 Three questions for each item: key, lifetime, writers

For each piece of state, ask three questions:

  1. Scope and key. Does it belong to a session (session), a student (student) or the whole service (service)? And by which key does the service find it: the session id, the student id, or a display name? An item that belongs to a student but is keyed by display name is shared by two students with the same name. That is a real bug in the lab (the memory_by_name variant, L04). In the lab, the display name is display_name in the profile (S0042 and S0518 are both "An"), which differs from the name a student introduces themselves with ("My name is Lumi.").
  2. Lifetime. Does it live for one turn (turn), one session (session) or permanently (persistent)? The conversation history lives one session; the context lives one turn; a loan is persistent.
  3. Writers. Who may write it: the student, the assistant, a tool, the school office? Each writer is a path by which wrong state can get in.

From those three answers the tests appear by themselves. A student item keyed by student id needs a test "another student does not see it". A session item needs a test "a new session does not see it" (or does, if that is the requirement). A persistent item written by the assistant needs a test "a correction replaces the old value" (L03). A state inventory is the list of those items, each with its test.

5. Technical deep dive

5.1 The state inventory and validate_inventory

data/inventory.json is the inventory of the service in the lab: eight items, each with id, kind, store, scope, key, lifetime, writers, test. validate_inventory(items) checks it and fails closed on missing or broken data: it returns a sorted list of error codes, empty when usable, and never raises (an id that is a list gives BAD_ID, not TypeError).

Code Meaning
NOT_A_LIST not a list, or empty
MISSING_FIELD an item lacks a field
BAD_ID id is not a non-empty string
DUPLICATE_ID two items share an id (compared after trimming whitespace at both ends, case-insensitive)
BAD_KIND, BAD_SCOPE, BAD_LIFETIME value outside the allowed list
NO_STORE, NO_WRITER, NO_TEST no store given, nobody writes it (or a writer is an empty string), or no test
NO_KEY a session or student item that does not name its key
KIND_NOT_COVERED:<kind> the inventory has no item of one of the four main kinds

Two rules are worth noting. A service-scoped (shared) item needs no key, because there is nothing to separate. And an inventory that leaves out a whole kind (usually long-term memory, because "we don't use it yet") is reported: if the product really has no long-term memory, write an item that says so and test it, instead of staying silent. The validator checks only the shape: a loan wrongly given service scope still passes, with no key needed; the reviewer has to read each scope.

5.2 survival and locate: ask the agent, then search the stores

survival(student, script, probes) runs script (the student's messages) in a fresh App, applies an event, then asks the probe question and checks whether the reply contains the expected text. Each (probe, event) pair runs in a fresh App, so the probes do not affect each other. The four events (state.EVENTS):

  • control: ask in the same session, change nothing. The control check: a probe that answers "no" here is a broken probe, not a finding.
  • trim: switch the context configuration to keep_system (keep system and memory messages, drop the oldest of the rest; details in L02) with a budget of 60 approximate tokens, then ask in the same session. Most of the history is trimmed out of the context.
  • new_session: the same student opens a new session and asks.
  • other_user: another student (S0107 by default; if it is the same as the script's student, survival raises ValueError) opens their own session and asks the same question. Here "yes" means the other student can see the expected reply; for state private to one student, "yes" is an isolation bug (L04).

locate(app, student, sid, value) works the other way round: it searches for the string value in a snapshot of the four kinds of state and returns the kinds that contain it. snapshot returns a deep copy, so a test that reads it cannot change the service.

The two tools answer different questions. survival tells you whether the agent can still use the information, seen from outside, as a user would. locate tells you where the information lives. A value can live in two places at once: the book id in "Borrow B005." is in both the conversation history and the task state.

6. QA perspective

6.1 The store having the data does not mean the agent sees it

Part B of the demo (§8.2) has one line worth remembering: class K7Q is written to long-term memory at turn 3, but after the context is trimmed (trim), the assistant answers "I do not know your class." Long-term memory is loaded into the context only when a session opens (a message with role memory); after a write in mid-session, the current session has only the student's sentence in the history, and that sentence gets trimmed. A new session does see it. A test that only reads the store (App.memory has class: K7Q) would pass; the user gets no answer.

Consequences for test design:

  • Test through behaviour first, read the store second. The probe tells you what the user experiences; locate explains why.
  • Every probe needs a control. The probe "rule (expects B003)" answers "no" at all four events, including control: B003 is on loan to another student, so the assistant never recommends it. Without a control column you would report "the rule is lost even when nothing is trimmed", a false finding.
  • Choose recognisable values. An unusual name (Lumi), an unusual class (K7Q) cannot appear in a reply by chance; L04 calls them canary values.
  • Task state is not in the context. The pending borrow survives a context trim (pending: trim=yes) because it lives in task, not in the history; but it is lost when a new session opens. If the product wants tasks to survive across sessions, that is a requirement that needs its own test.

7. Real-world scenarios

Scenario 1 (fictional): "But it remembers me". A parent reports that the assistant "forgets" their child's class after a long chat, but remembers it again the next day. The developers check the database: the class is stored correctly. The tester runs the survival table and sees exactly the class row of §8.2: trim=no, new_session=yes. The cause is that memory is loaded only when a session opens. The report proposes two options, each with a test: reload memory on write, or pin the memory message when trimming the context.

Scenario 2 (fictional): "The inventory has no cache". The team's first state inventory has only the four main items. In review, the tester asks "are replies cached, and what is the key". The cache is added as a derived item with the key (student id, question), with the test "another student asking the same question does not get the reply from this cache". L04 shows which bug that test catches.

8. Hands-on tutorial

8.1 Setup

cd academy-content/code-labs/l3-m05
python3 -m venv .venv && source .venv/bin/activate     # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt
python -m pytest            # 113 passed

8.2 Run the demo

python -m lab.demo l01

Output (copied from a real run on Python 3.14.6 and 3.12.3, Linux, 2026-11-04; both versions gave identical output). Every student and run is simulated:

A. the lab's state inventory (8 items) and validate_inventory
   history: kind=conversation scope=session key='session id + owner check' lifetime=session
   context: kind=derived scope=session key='session id' lifetime=turn
   summary: kind=derived scope=session key='session id' lifetime=turn
   pending_borrow: kind=task scope=session key='session id' lifetime=session
   loans: kind=environment scope=student key='student id of the session owner' lifetime=persistent
   profile: kind=environment scope=student key='student id of the session owner' lifetime=persistent
   long_term_memory: kind=memory scope=student key='student id' lifetime=persistent
   reply_cache: kind=derived scope=student key='(student id, question)' lifetime=persistent
   shipped: []
   no memory item: ['KIND_NOT_COVERED:memory']
   scope 'user': ['BAD_SCOPE']
   loans without a key: ['NO_KEY']
   two items called history: ['DUPLICATE_ID']
   an id that is a list: ['BAD_ID']
B. survival of S0042's facts (yes = the probe reply still contains the expected text)
   script: My name is Lumi. | Only recommend story books. | Remember that my class is K7Q. | Borrow B005. | Tell me about B002. | Tell me about B003.
   name: control=yes trim=no new_session=no other_user=no
   rule (expects B003): control=no trim=no new_session=no other_user=no
   rule (expects B007): control=yes trim=no new_session=no other_user=no
   class: control=yes trim=no new_session=yes other_user=no
   pending: control=yes trim=yes new_session=no other_user=no
   loan: control=yes trim=yes new_session=yes other_user=no
C. where each value lives after the script (locate)
   Lumi: ['conversation']
   story: ['conversation']
   K7Q: ['conversation', 'memory']
   B005: ['conversation', 'task']
   B006: ['environment']

Reading the output: part A: the lab's inventory is clean; five broken versions, one error each, are all caught with the right code (the id "History " still duplicates history; an id that is a list gives BAD_ID and does not raise). Part B: the name and the rule are conversation state, lost on a trim and in a new session; the probe "expects B003" is broken already at the control, the "expects B007" version is the right probe; the class (memory) is lost on a trim but present in a new session (§6.1); the pending borrow (task) survives the trim but not a new session; the loan of B006 (environment) survives everything. The other_user column is all "no": student S0107 sees nothing of S0042's. Part C: B005 lives in two places (the message in the history and the pending borrow); B006 lives only in the environment because the script never mentions it.

8.3 Try it yourself

Save this as try_l01.py in the lab's root folder (next to lab/), run python try_l01.py, then delete the file:

from lab import state as ST

script = ["My name is Tuan.", "Remember that my class is 4B.", "Borrow B002."]
probes = {"name": {"ask": "What is my name?", "expect": "Tuan"}, "class": {"ask": "What is my class?", "expect": "4B"}}
for variant in ("correct", "memory_by_name"):
    print(variant, ST.survival("S0042", script, probes, variant=variant, other="S0518"))
a, sid = ST.run_script("S0042", script)
snap = a.snapshot("S0042", sid)
print(snap["task"], snap["memory"], snap["environment"]["loans"])

Output (Python 3.14.6 and 3.12.3, Linux, identical):

correct {'name': {'control': True, 'trim': False, 'new_session': False, 'other_user': False}, 'class': {'control': True, 'trim': False, 'new_session': True, 'other_user': False}}
memory_by_name {'name': {'control': True, 'trim': False, 'new_session': False, 'other_user': False}, 'class': {'control': True, 'trim': False, 'new_session': True, 'other_user': True}}
{'pending': {'book': 'B002', 'requested_by': 'S0042'}} {'class': '4B'} ['B006']

Reading: the "other student" here is S0518, who also has the display_name "An" like S0042 (the name Tuan exists only in the conversation). With the correct service, S0518 does not see class 4B. With the memory_by_name variant (memory keyed by display name), the other_user column of class becomes True: an isolation bug that the inventory already predicted with the question "what is the key". The last line is the snapshot: the pending borrow of B002 in task, the class in memory, the existing loan B006 in the environment.

8.4 Run the lesson's tests

python -m pytest tests/test_l01_state.py -v

Result: 30 passed. Read test_survival_table_of_the_lesson (the part B table, with a comment on each row), test_each_broken_inventory_is_caught and test_the_helper_reads_only_its_context.

8.5 Troubleshooting

Symptom Cause Fix
A probe returns False even in the control column The expected text is wrong (the book is not on the shelf, the assistant does not understand the question) Fix the probe; read the other columns only when control is True
ValueError: unknown event An event outside state.EVENTS Use control, trim, new_session, other_user
The assistant answers "Sorry, I can only help with library books." A message outside the patterns the assistant understands Use the exact message patterns in lab/agent.py (docstring)
locate returns [] The value does not appear verbatim anywhere locate searches for the exact string, case-sensitive

9. Independent exercise

Problem: Student S0315 chats for seven turns (exercises/ex_state_l01.json): gives a name, sets two rules, asks the assistant to remember a class, asks to borrow a book, then asks about two books. The file has six probes, and describes two pieces of state not yet in the inventory (new_state).

Requirements: complete exercises/test_l01_state.py:

  1. TODO 1: SURVIVAL: for each probe, the four true/false values in the order control, trim, new_session, other_user. If a probe fails its control, record exactly that: the other columns of that row mean nothing.
  2. TODO 2: LOCATE: for the five values in values, the list of state kinds (sorted) that locate returns after the script.
  3. TODO 3: INVENTORY_EXTRA: one inventory item (all eight fields) for each piece of state in new_state, such that the lab's inventory plus your two items passes validate_inventory, and the kind, scope and lifetime match the description.

Test data: exercises/ex_state_l01.json.

Deliverable: the three variables above, in the file exercises/test_l01_state.py itself.

Acceptance criteria: python -m pytest exercises/test_l01_state.py passes (3 tests). The tests recompute with ST.survival and ST.locate; TODO 3 compares a hash of (kind, scope, lifetime).

Hints: for each probe, first decide which kind of state the reply depends on, then ask whether that kind is in the context after each event; for other_user, ask: is that value private to this student or visible to everyone? locate also reads the environment (books on loan, the profile), not only what was said in the session. For TODO 3, answer the three questions of §4.2 for each description.

10. Knowledge check

0/10 done · Results are kept in this browser only.

P02 · True or false

An inventory item with scope service (shared across the whole service) and an empty key makes validate_inventory report NO_KEY.

P04 · Select all that apply

Without looking at the table in §8.2, using only the kind of state of each row in part B of the L01 demo: select every row that will be "yes" in the trim column.

P05 · Put in order

Put the steps for drawing up a state inventory for an agent and checking it in order.

  1. Run validate_inventory and fix until no error codes remain
  2. Write the probe recorded for each item and run the control first
  3. For each item, record the kind, scope, key, lifetime, writers and the name of the test you will write
  4. List every place the agent and the service keep data, including caches, summaries and the context
  5. Run the probes after each event and compare the results with the recorded lifetime

P06 · Match

Match each observed behaviour to the kind of state that explains it (the lab's correct service, except for the last line).

P07 · Spot the bug

A tester wrote this function to replace survival and save time. Its results cannot be trusted. Find the bug.

def survival_fast(student, script, probes):
    a, sid = ST.run_script(student, script)
    out = {}
    for fact, p in probes.items():
        out[fact] = p["expect"] in a.send(student, sid, p["ask"])
    return out

P08 · Essay

In the L01 demo table, the class row is trim=no but new_session=yes, even though App.memory has class: K7Q right after turn 3. Write two to four sentences explaining why, and state what a test that only reads the store would miss.

P10 · Recall

Lesson: L3-M04-L05

According to L3-M04-L05, which values can the trajectory evaluator's gate return?

11. Summary

  • Concepts: conversation, task, environment and long-term memory state, plus derived state (context, summary, cache); scope, key, lifetime, writers [R1][R2][R3][R4].
  • Skills: write a state inventory with a test for each item; run survival with a control; use locate to explain a probe.
  • Traps: trusting the store instead of behaviour; probes without a control; leaving out derived state; a display name as the key.
  • Now you can: draw up a state inventory for an agent, say how long each item lives and who sees it, and prove it with probes.

12. References

ID Title Publisher URL Accessed Relevance
R1 Demystifying evals for AI agents Anthropic https://www.anthropic.com/research/demystifying-evals-for-ai-agents 2026-11-04 Conversational agents maintain state, use tools and take actions mid-conversation
R2 Conversation state OpenAI API documentation https://developers.openai.com/api/docs/guides/conversation-state 2026-11-04 Requests are independent and stateless; the Conversations API with a durable identifier
R3 Persistence LangChain (LangGraph documentation) https://docs.langchain.com/oss/python/langgraph/persistence 2026-11-04 Checkpointer (per thread) and store (across threads)
R4 Effective context engineering for AI agents Anthropic https://www.anthropic.com/research/effective-context-engineering-for-ai-agents 2026-11-04 Structured note-taking (agentic memory) outside the context window

Glossary (English ↔ Tiếng Việt)

English Tiếng Việt
State inventory Bản kê trạng thái: danh sách mọi mẩu trạng thái, mỗi mục có phạm vi, khóa, vòng đời, người ghi và test
Conversation / task / environment state Trạng thái hội thoại / tác vụ / môi trường
Long-term memory Bộ nhớ dài hạn: sống qua nhiều phiên
Derived state Trạng thái dẫn xuất: bản sao hay bản rút gọn (context, tóm tắt, cache)
Probe Câu hỏi dò: câu hỏi bình thường gửi tới agent để đọc ra một mẩu trạng thái; khác probe đo thiên lệch (L2-M04-L03)
Control (check) Phép kiểm đối chứng: hỏi khi chưa đổi gì; probe trượt đối chứng là probe hỏng