Memory, context and state are different
Context is the information available to the model for a particular call, including instructions, messages, tool results and retrieved documents. Memory preserves and recalls information from earlier interactions. Execution state records the current process stage and actual effects. A string saying “refund completed” is not proof of payment. [1][2][3]
Application memory does not change model weights. RAG supplies knowledge sources, while memory personalizes behavior or preserves experience; both may share retrieval infrastructure. Read authoritative business state such as balances from the responsible service, not an agent recollection.
Memory types and scopes
| Layer | Content | Example store |
|---|---|---|
| Working context | Instructions and evidence | Current call data |
| Short-term | Messages | Session database |
| Semantic | Facts and preferences | Database and optional index |
| Episodic | Task outcomes | Event log |
| Procedural | Approved rules | Versioned repository |
| Execution state | Stage and operations | Transactional database |
Short-term memory normally belongs to a thread or session. Long-term memory may store facts and preferences (semantic), previous task outcomes (episodic) and approved procedures (procedural). This is a useful taxonomy, not a mandatory database design. Procedural memory must not let a model rewrite security policy. [1]
Every record needs a scope: task, session, user, tenant or approved shared knowledge. Do not automatically copy information between scopes. User memory may retain a preferred language but cannot grant administrative privileges or replace current consent.
Read and write architecture
- Establish identity and scope
- Retrieve current authorized records
- Build context and call model
- Validate proposed write
- Persist only approved data
Store an identifier, scope, type, content or source reference, provenance, creation and verification timestamps, version, status and expiry. An optional confidence score can prioritize verification but is not evidence of truth. Define who may write, approve, update and delete records.
Separate session, knowledge and execution repositories logically even when they share one database. Establish identity and access scope before retrieval, collect candidates, check freshness, deduplicate and fit them to the task. Tool results or models may propose a memory write; the controlled application layer decides whether to persist it. [2][3][4]
Distinguish a user statement, a fact verified by the system and a model inference. If a user changes their preferred language from Polish to English, replace the active preference within the same scope instead of adding a second equally authoritative record. Mark inferences as unverified and do not let them overwrite confirmed facts. For changing information, retain the validity period and source version; resolve conflicts rather than selecting only the most similar record.
Storage and concurrency
A relational database suits versioned records, permissions and transactions. Object storage can retain large artifacts; state can hold a reference and checksum. A vector index supports similarity retrieval but is not an authoritative store. A TTL cache works for reconstructable data, not as the only durable record.
Concurrent workers must not overwrite each other's decisions. Use transactions, locks or optimistic concurrency with version numbers. On conflict, reread the current record and reassess the update; do not blindly repeat external operations. Bind derived indexes to record versions and enforce revocation even during delayed index updates. [5][6]
Concurrency example: two workers read record version 7. The first writes version 8; the second may write only if the current version is still 7. If that condition fails, reread the record and reassess the update. Reject stale events when updating the vector index. Derive tenant and user identities on the server; a thread identifier or namespace alone is not authorization.
Context budget and cost
| Purpose | Tokens |
|---|---|
| Instructions and tools | 3 000 |
| History and query | 5 000 |
| Evidence | 18 000 |
| Generation | 4 000 |
| Headroom | 2 000 |
| Total | 32 000 |
Use recent messages, summaries of earlier steps and selective evidence retrieval. Preserve source identifiers, constraints and open questions. Do not irreversibly summarize the only copy of audit-critical facts. Lost in the Middle demonstrates that evidence position may affect performance; this does not imply identical behavior across all models. [3][7][8]
For an illustrative 32,000-token window, allocate 3,000 to instructions and tools, 5,000 to history and query, 18,000 to evidence, 4,000 to generation and 2,000 to headroom. Actual limits depend on the API. Across 100,000 calls per month, reducing input from 12,000 to 4,000 tokens saves 800 million tokens, or USD 800 at an assumed USD 1 per million. Subtract retrieval, summarization and storage costs before estimating net savings.
When the context limit is approached, remove duplicates and irrelevant tool results first, then compact history while retaining source identifiers and unresolved requirements. Preserve applicable constraints and keep tool calls paired with results as required by the API. If retrieval, summarization and memory maintenance add USD 250 per month, the previous example yields USD 550 in net savings, assuming other costs and quality are unchanged. Account for cached-token pricing and changes in retries as well.
Durable state, checkpoints and safe resumption
- Load checkpoint
- Check permissions, approval and version
- Determine external operation outcome
Next steps depending on the outcome:
- Confirmed success: continue without repetition
- Unknown outcome: reconcile or escalate to a person
- Confirmed failure: assess retry conditions
A checkpoint is persisted state at a process boundary. Store task ID, stage, schema and policy versions, artifact references, approval status, cost budget and operation IDs. On resume, recheck current permissions, approval validity and version compatibility. A checkpoint is not authorization. [2][9]
Consider a refund: the agent prepares it, an authorized user approves it, and the process loses the response after submission. Record an unknown outcome. Query the payment system using the operation identifier; reuse the same idempotency key if the provider guarantees it. Without a confirmed outcome or adequate contract, do not automatically repeat the refund. A local transaction does not guarantee exactly-once execution across independent systems.
Before sending a request, durably record the intended operation, its business identifier and idempotency key, bound to approved parameters. An operation ledger or transactional outbox can link the local commit to later dispatch but cannot guarantee a single external side effect. After restart, read the ledger and reconcile with the target system. In LangGraph, replaying an earlier checkpoint can rerun subsequent nodes; protect side effects independently. [13]
Multi-agent memory and security
Separate private memory from shared spaces. Delegate only information needed for a specific task, with scope and provenance. Delegation must not elevate privileges. Shared storage does not mean every agent has access to every record.
OWASP ASI06 addresses memory and context poisoning. Malicious document content can be persisted as an apparently trustworthy rule and affect future sessions. Validate write type and scope, confirm consequential facts and separately approve procedure changes. Keep access tokens out of model memory. Encrypt data, limit retention, audit changes, revoke access and delete records and derived copies. Do not log full conversations by default. [6]
Deletion must cover the lifecycle of the source record, summaries, embeddings, indexes, caches, checkpoints and exports. Block further use of deleted data immediately; physical deletion and backup expiry may follow a defined policy. When restoring a backup, apply the current deletion and revocation ledger before making the system available, in accordance with retention policy. Prevent stale events or background tasks from recreating deleted records. [6]
Implementation in agent frameworks
LangGraph separates thread checkpoints from cross-thread stores. OpenAI Agents SDK provides Sessions for history and RunState for resuming interrupted execution. Google ADK distinguishes Session, State and Memory and supports different storage service implementations. Feature availability depends on SDK version and language. [2][4][9][10][11]
A library memory abstraction is not durable without a suitable backend. Process-local memory is useful for prototypes but cannot restore a lost process. Before deployment, test schema migration, concurrent writes, access controls and restoration after restart. Keep policy and domain state independent of the model provider.
In OpenAI Agents SDK, keep serialized RunState in trusted server-side storage. Deserialization authenticates neither the snapshot nor the approver. The client should submit only a pending decision identifier and its outcome; the server verifies ownership and current permissions and atomically marks the decision as consumed. When an operation has an unknown outcome, absence from a potentially stale lookup does not prove that retrying is safe. [9]
Quality evaluation and acceptance tests
Build a test set with facts the agent must use, conflicting records and information that must be forgotten. Compare no memory, history and selective retrieval with the same model. Measure task correctness, retrieval relevance, stale-fact rate, cost and latency. For Recall@5, if four records are expected and three appear among five results, recall is 75%; this does not establish answer quality.
Test interruptions before and after writes, concurrent updates, revocation, deletion and attempts to persist unrelated instructions. Require no unauthorized reads or effects within the test suite. Report trial counts and configuration versions; absence of detected violations does not prove complete safety.
Separate retrieval relevance from the quality of memory use. For the same example, Recall@5 is 3/4 = 75% and Precision@5 is 3/5 = 60% if the other two results are irrelevant. Test generation with manually selected correct records as well. Include changed preferences, stale indexes, backup restoration after deletion and lost responses after external writes. Verify database state and actual side effects, not merely the model’s claim.
A practical rollout plan
Begin with durable state and bounded history. Add selective semantic memory only when cross-session recall has measurable value. Define write and deletion policies before enabling automatic retention. Add episodic memory for recurring tasks and version procedures like code.
Before release, test resumption, tenant isolation, deletion and model changes. Memory is useful only when it improves task performance without crossing trust boundaries or imposing disproportionate costs.
See Harness Engineering for execution environments and operation controls. [12]
For context selection and token budgets, see Prompt Engineering vs Context Engineering. [14]
