Agent Build智能体搭建 Tutor教程
Map地图 / Module模块 4 / labs/m04_*

State and storage状态与存储

Where facts live between calls, who may write them, and how concurrent writers stay safe.两次调用之间数据存在哪里、谁可以写,以及多个写入方如何互不破坏。

What it is and why it exists它是什么,为什么需要它

What是什么

State is everything that outlives one model call: the run state inside a request, the conversation across requests, durable knowledge and memory, and the cursors that mark how far a background job has read.状态是比一次模型调用活得更久的一切:单次请求内的运行状态、跨请求的对话、持久化的知识与记忆,以及标记后台任务读到哪里的游标。

Why为什么

A model call has no memory. Each kind of state has a different lifetime and owner, and mixing them causes the worst bugs. The reference build's single-writer stores failed when two scheduled jobs wrote at once, and one file was corrupted.模型调用本身没有记忆。每种状态的生命周期和所有者都不同,混在一起会导致最严重的问题。参考系统早期使用单写入方的存储,两个定时任务同时写入时出了故障,其中一个文件被损坏。

How it works工作原理

Where it sits in the build order它在搭建顺序中的位置

Needs first前置模块

Nothing. You can start here.没有。可以从这里开始。

Unlocks解锁

  • RAG and knowledge graphRAG 与知识图谱Chunks, vectors, and edges need tables that survive a nightly writer and concurrent readers.文本块、向量和边需要存在表里,并且要经得住夜间写入和并发读取。
  • Harness engineeringHarness 工程Concurrent tool results have to merge into one conversation without overwriting each other. The merge rules exist before the loop that relies on them.并发的工具结果必须合并进同一个对话而不互相覆盖。合并规则要先于依赖它的循环而存在。
  • Memory记忆Memory is durable state with concurrent writers: live chats and background jobs. It needs the tables and the connection settings from the state module.记忆是有并发写入方的持久状态:实时对话和后台任务都会写。它需要状态模块里的表和连接设置。

In the reference build在参考系统中

Path路径Role作用
apps/agent-server/graph.pymerge_state: the rules for run state.merge_state:运行状态的合并规则。
apps/agent-server/pgstore.pyConnection handling and schema setup for Postgres.Postgres 的连接管理和建表。
apps/agent-server/pgschema.sqlSchemas by owner: learned knowledge, file ledger, chunk indexes.按归属划分的 schema:学到的知识、文件台账、文本块索引。
apps/agent-server/conversation_store.pyThreads and messages across requests.跨请求的会话和消息。

Process map流程图

Three lifetimes, three places三种生命周期,三个存放位置

  1. 1
    Run state运行状态Lives for one request. A dict. Dies when the answer is returned.只存在于一次请求内。是一个字典。回答返回后即消失。
  2. 2
    Conversation对话Lives for a thread. Rows with user, thread, role, content.存在于一个会话期间。数据行包含用户、会话、角色、内容。
  3. 3
    Ingested knowledge入库的知识kb tables. Written by the indexer. Rebuildable from the bank.kb 表。由索引程序写入。可以从知识库重建。
  4. 4
    Learned knowledge学到的知识brain tables. Written by the nightly loop. Can be dropped without touching kb.brain 表。由夜间任务写入。删除它不影响 kb。
  5. 5
    User memory用户记忆mem tables. Every row carries a partition.mem 表。每一行都带有分区标识。
  6. 6
    Cursors游标One number per job: how far into a log it has read.每个任务一个数字:它读到日志的哪个位置。

Build steps搭建步骤

Follow them in order the first time. Each step names what it uses from earlier steps and what it leaves for later ones. Code is read from the lab files, and output is what the lab printed when it was run.第一次请按顺序做。每一步都写明它用到前面步骤的什么成果,又为后面的步骤留下什么。代码直接读取自 lab 文件,输出是 lab 实际运行时打印的内容。

  1. 1Name each kind of state and its owner给每种状态命名,并确定归属
  2. 2Open the database so concurrent access works以支持并发访问的方式打开数据库
  3. 3Create the schema, grouped by owner按归属分组建表
  4. 4Define merge rules for run state定义运行状态的合并规则
  5. 5Test concurrent writers before you depend on them在依赖并发写入之前先测试
  6. 6Give every background job a cursor给每个后台任务一个游标
  7. 7Check that learned state can be dropped alone确认学到的状态可以单独清除
  8. 8Move to Postgres when the workload asks for it当负载需要时迁移到 Postgres
01Name each kind of state and its owner给每种状态命名,并确定归属
Why this step is here为什么这一步排在这里Decide ownership before creating a single table. A table with two owners is where concurrent-write bugs and privacy leaks start.在建任何一张表之前先确定归属。一张表有两个所有者,正是并发写入问题和隐私泄露的起点。
Uses用到Nothing from earlier steps.不依赖之前的任何步骤。

Do this操作

  1. List what must outlive a request. For each item write: lifetime, the one job that writes it, who reads it.列出哪些数据必须活过一次请求。对每一项写下:生命周期、唯一负责写入的任务、谁来读。
  2. Group them under prefixes: kb, brain, mem, conv, job.按前缀分组:kb、brain、mem、conv、job。
You are done when完成标志Every table in your plan has exactly one writer.规划中的每张表都只有一个写入方。
Produces产出An ownership table: prefix, writer, readers, lifetime.一张归属表:前缀、写入方、读取方、生命周期。
02Open the database so concurrent access works以支持并发访问的方式打开数据库
Why this step is here为什么这一步排在这里Connection settings come before schema because they decide whether a second writer waits or fails. Fixing this after jobs exist means finding it as a corrupted file.连接设置排在建表之前,因为它决定第二个写入方是等待还是失败。等任务都跑起来再改,往往是通过文件损坏才发现问题。
Uses用到

Do this操作

  1. Enable write-ahead logging so readers proceed while a writer writes.开启预写日志(WAL),这样写入时读取不受阻塞。
  2. Set a busy timeout so a second writer waits its turn.设置 busy timeout,让第二个写入方排队等待。
  3. Use one `connect()` function everywhere.全系统只用一个 `connect()` 函数。
labs/m04_state/store.py · connect
def connect(path: Path) -> sqlite3.Connection:
    """WAL lets readers proceed while one writer writes. busy_timeout makes a second
    writer wait its turn instead of failing with 'database is locked'."""
    db = sqlite3.connect(str(path), timeout=30, check_same_thread=False)
    db.execute("PRAGMA journal_mode=WAL")
    db.execute("PRAGMA busy_timeout=30000")
    db.execute("PRAGMA foreign_keys=ON")
    return db
You are done when完成标志`PRAGMA journal_mode` returns wal.`PRAGMA journal_mode` 返回 wal。
Produces产出`connect()`: the only way the stack opens its database.`connect()`:全系统打开数据库的唯一方式。
03Create the schema, grouped by owner按归属分组建表
Why this step is here为什么这一步排在这里Schema follows ownership. Every later module writes into one of these tables, so they are created once here and never altered ad hoc.表结构由归属决定。后面每个模块都会往其中某张表里写数据,所以在这里一次建好,之后不做临时修改。

Do this操作

  1. Read the schema below. Find the prefix of each table.阅读下面的表结构,找出每张表的前缀。
  2. Note `chunk_id` is `<source>::<n>`. Retrieval and evals rely on that format.注意 `chunk_id` 的格式是 `<source>::<n>`。检索和评估都依赖这个格式。
  3. Make schema creation idempotent and call it on every start.让建表操作幂等,并在每次启动时调用。
labs/m04_state/store.py · schema
SCHEMA = """
CREATE TABLE IF NOT EXISTS kb_chunks (
  chunk_id TEXT PRIMARY KEY,            -- "<source>::<n>"
  collection TEXT NOT NULL, source TEXT NOT NULL, chunk_index INTEGER NOT NULL,
  text TEXT NOT NULL, context TEXT, embedding TEXT,   -- JSON list of floats
  tier INTEGER NOT NULL DEFAULT 3, retired INTEGER NOT NULL DEFAULT 0, heldout INTEGER NOT NULL DEFAULT 0);
CREATE VIRTUAL TABLE IF NOT EXISTS kb_fts USING fts5(chunk_id UNINDEXED, collection UNINDEXED, body);
CREATE TABLE IF NOT EXISTS kb_edges (
  from_key TEXT NOT NULL, to_chunk TEXT NOT NULL, relation TEXT NOT NULL,   -- 'defines' | 'cites'
  PRIMARY KEY (from_key, to_chunk, relation));

CREATE TABLE IF NOT EXISTS brain_claims (
  claim_id INTEGER PRIMARY KEY, kind TEXT NOT NULL, text TEXT NOT NULL, source_ref TEXT NOT NULL,
  status TEXT NOT NULL DEFAULT 'candidate',   -- candidate | trusted | unsupported | retired
  formed_at TEXT NOT NULL, UNIQUE (kind, text));
CREATE TABLE IF NOT EXISTS brain_evidence (
  claim_id INTEGER NOT NULL REFERENCES brain_claims(claim_id), origin TEXT NOT NULL, day TEXT NOT NULL,
  PRIMARY KEY (claim_id, origin, day));

CREATE TABLE IF NOT EXISTS mem_facts (
  partition TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, updated_at REAL NOT NULL,
  PRIMARY KEY (partition, key));
CREATE TABLE IF NOT EXISTS conv_turns (
  turn_id INTEGER PRIMARY KEY, partition TEXT NOT NULL, thread TEXT NOT NULL,
  role TEXT NOT NULL, content TEXT NOT NULL, ts REAL NOT NULL);

CREATE TABLE IF NOT EXISTS job_cursors (job TEXT PRIMARY KEY, position INTEGER NOT NULL);
"""


def ensure_schema(db: sqlite3.Connection) -> None:
    db.executescript(SCHEMA)      # idempotent: safe to run on every start
    db.commit()
run
python3 -m labs.m04_state.demo
Recorded output / 记录的输出 · m04.demo
1 schema, applied twice : brain_claims, brain_evidence, conv_turns, job_cursors, kb_chunks, kb_edges, kb_fts, mem_facts
You are done when完成标志Running `ensure_schema` twice raises no error and changes nothing.运行两次 `ensure_schema` 不报错,也不改变任何东西。
Produces产出Tables for chunks, edges, claims, memory, turns, and cursors.文本块、边、论断、记忆、对话轮次和游标的表。
04Define merge rules for run state定义运行状态的合并规则
Why this step is here为什么这一步排在这里This must exist before any code runs two nodes at once. Without it, the second tool result silently replaces the first.在任何代码同时运行两个节点之前,这套规则就必须存在。否则第二个工具的结果会悄悄覆盖第一个。
Uses用到Nothing from earlier steps.不依赖之前的任何步骤。

Do this操作

  1. Keys ending in `_append` extend a list.以 `_append` 结尾的键向列表追加。
  2. Counter keys add.计数类的键做加法。
  3. Every other key overwrites. That is a decision: last writer wins.其余的键直接覆盖。这是有意的决定:后写的生效。
labs/m04_state/store.py · merge
EXTEND_KEYS = {"messages_append", "tools_used_append", "findings_append"}          # concurrent nodes each add items
SUM_KEYS = {"prompt_tokens", "completion_tokens", "model_calls"}   # concurrent nodes each add a number


def merge_state(state: dict, update: dict) -> None:
    """Apply one node's update to shared run state without losing a sibling's update."""
    for key, value in update.items():
        if key in EXTEND_KEYS:
            state.setdefault(key[: -len("_append")], []).extend(value)
        elif key in SUM_KEYS:
            state[key] = state.get(key, 0) + value
        else:
            state[key] = value                               # last writer wins, on purpose
Recorded output / 记录的输出 · m04.demo
2 two nodes merged      : ['q', 'A', 'B'] model_calls = 2 last_node = tool:b
You are done when完成标志Two updates that each append a message leave both messages in the list.两个各自追加一条消息的更新,合并后列表里两条都在。
Produces产出`merge_state()`: used by the wave executor in the harness.`merge_state()`:Harness 里的波次执行器会用到它。
05Test concurrent writers before you depend on them在依赖并发写入之前先测试
Why this step is here为什么这一步排在这里It needs the connection and the schema. It is here, and not in operations, because a failure changes the storage choice.它需要连接和表结构都就绪。放在这里而不是运维模块,是因为一旦失败就要改变存储方案。

Do this操作

  1. Start three threads, each with its own connection, each inserting 200 rows.启动三个线程,各用自己的连接,各插入 200 行。
  2. Count the rows.统计行数。
Recorded output / 记录的输出 · m04.demo
3 three writers at once : 600 rows, none lost
You are done when完成标志600 rows, no `database is locked` error.共 600 行,没有出现 `database is locked` 错误。
Produces产出Proof that a chat, a nightly job, and an eval can write at the same time.证明聊天、夜间任务和评估可以同时写入。
Feeds供给
06Give every background job a cursor给每个后台任务一个游标
Why this step is here为什么这一步排在这里Jobs that read logs come later, in evaluation and self-evolution. The cursor is built now because it is storage, and those jobs assume it.读取日志的任务在后面的评估和自进化模块才出现。游标现在就建好,因为它属于存储层,而那些任务默认它已存在。

Do this操作

  1. Store one byte offset per job name.为每个任务名保存一个字节偏移量。
  2. Read from the offset to the last complete line. Advance the offset in the same call.从偏移量读到最后一个完整的行,并在同一次调用中推进偏移量。
  3. If the file is now smaller than the stored offset, it was rotated: start again from 0. Without this check the job skips every line written after rotation. Lab 15 shows it.如果文件现在比保存的偏移量还小,说明它被轮转过:从 0 重新开始。没有这项检查,任务会跳过轮转之后写入的每一行。lab 15 演示了这一点。
  4. Write logs as JSON lines, one record per line.日志使用 JSON Lines 格式,每行一条记录。
labs/m04_state/store.py · cursor
def read_new_lines(db: sqlite3.Connection, job: str, log_path: Path) -> list:
    """Return log lines this job has not seen, then advance its cursor. A job that
    crashes and restarts resumes where it stopped and never handles a line twice."""
    row = db.execute("SELECT position FROM job_cursors WHERE job=?", (job,)).fetchone()
    pos = row[0] if row else 0
    if not log_path.exists():
        return []
    if log_path.stat().st_size < pos:     # the file was rotated (copied, then truncated): start over
        pos = 0
    with log_path.open("rb") as f:
        f.seek(pos)
        data = f.read()
        end = pos + data.rfind(b"\n") + 1 if b"\n" in data else pos     # only whole lines
    lines = [json.loads(x) for x in data[: end - pos].decode().splitlines() if x.strip()]
    db.execute("INSERT INTO job_cursors VALUES (?,?) ON CONFLICT(job) DO UPDATE SET position=excluded.position",
               (job, end))
    db.commit()
    return lines
Recorded output / 记录的输出 · m04.demo
4 cursor                : 3 lines, then 1 new, then 0
You are done when完成标志Three lines are read once, one new line is read next, and a third call returns nothing.先读到三行,接着读到一行新的,第三次调用返回空。
Produces产出`read_new_lines()` and `append_log()`.`read_new_lines()` 和 `append_log()`。
07Check that learned state can be dropped alone确认学到的状态可以单独清除
Why this step is here为什么这一步排在这里Do this before any learning job exists. It is the test of the ownership boundary, and it is your recovery plan when a learner writes something wrong.要在任何学习任务出现之前做这件事。它检验归属边界是否成立,也是学习任务写错内容时的恢复方案。
Uses用到

Do this操作

  1. Drop every table with the brain prefix.删除所有以 brain 为前缀的表。
  2. Confirm the kb tables are untouched.确认 kb 表没有受影响。
Recorded output / 记录的输出 · m04.demo
5 dropped brain_* tables: 3 of 3 kb_* tables still there
You are done when完成标志The kb tables are all still present.kb 表全部还在。
Produces产出A tested answer to: how do I delete everything the agent taught itself?一个经过验证的答案:如何删除智能体自己学到的一切?
08Move to Postgres when the workload asks for it当负载需要时迁移到 Postgres
Why this step is here为什么这一步排在这里It is last because the lab database is enough to learn every later module. Move when you have several writers under load, need a vector index over many rows, or need point-in-time recovery.它排在最后,因为 lab 用的数据库足够学完后面所有模块。当你有多个高负载写入方、需要对大量数据建向量索引,或需要按时间点恢复时,再迁移。
Uses用到

Do this操作

  1. Start Postgres with the pgvector extension. On your machine use the container command below. The lab starts a private throwaway cluster instead.启动带 pgvector 扩展的 Postgres。在你自己的机器上用下面的容器命令。lab 则会启动一个用完即删的私有集群。
  2. Map each table prefix to a Postgres schema of the same name: kb, brain, mem.把每个表前缀映射为同名的 Postgres schema:kb、brain、mem。
  3. Keep the same column names so calling code keeps its SQL.保持列名不变,这样调用代码的 SQL 不用改。
  4. Run the concurrent-writer test against Postgres. Each writer uses its own connection.在 Postgres 上运行并发写入测试。每个写入方使用自己的连接。
labs/m05_rag/pg.py · writers
def concurrent_writers(dsn: str, writers=("chat", "nightly-job", "eval-job"), rows: int = 200) -> int:
    """The state-module writer test, against Postgres. Each writer has its own connection."""
    errors = []

    def write(name):
        try:
            with psycopg.connect(dsn) as c:
                for i in range(rows):
                    c.execute("INSERT INTO mem.turns (partition, thread, role, content) VALUES (%s,'t1','user',%s)",
                              (name, f"{name}-{i}"))
                    c.commit()
        except Exception as e:                       # a lock error would land here
            errors.append(f"{name}: {e}")

    ts = [threading.Thread(target=write, args=(n,)) for n in writers]
    [t.start() for t in ts]
    [t.join() for t in ts]
    if errors:
        raise RuntimeError("; ".join(errors))
    with psycopg.connect(dsn) as c:
        return c.execute("SELECT count(*) FROM mem.turns").fetchone()[0]
on your machine
docker run -d --name agentdb -e POSTGRES_PASSWORD=change-me -p 127.0.0.1:5432:5432 pgvector/pgvector:pg17
psql -h 127.0.0.1 -U postgres -c "CREATE EXTENSION IF NOT EXISTS vector;"
psql -h 127.0.0.1 -U postgres -c "CREATE SCHEMA kb; CREATE SCHEMA brain; CREATE SCHEMA mem;"
# "delete everything the agent taught itself" becomes:  DROP SCHEMA brain CASCADE;

The container command was not run by the labs. The lab ran the same schema and writer test on a local Postgres 16 server.lab 没有运行这条容器命令。lab 在本地的 Postgres 16 上运行了同样的 schema 和写入测试。

run
PG_RUN_AS=<ordinary user, only when running as root> python3 -m labs.m05_rag.pg
Recorded output / 记录的输出 · m05.pg
1 cluster up, pgvector 0.6.0 | schemas, applied twice: brain, kb, mem
2 three writers at once : 600 rows, no lock errors
You are done when完成标志The schema applies twice without error, and three writers insert 600 rows with no lock errors.schema 连续应用两次不报错,三个写入方写入 600 行且没有锁错误。
Produces产出A production store with the same layout.一个结构相同的生产级存储。
Feeds供给

How it works with the other parts它如何与其他部分协作

What went wrong in the real build真实搭建中踩过的坑

2026-08

Two jobs wrote one single-writer file两个任务同时写一个单写入方文件

What happened发生了什么
The daily cycle and the learner collided at the same minute two nights running. One night the database was corrupted.日常任务和学习任务连续两晚在同一分钟撞在一起。其中一晚数据库被损坏。
Fix修复
A store with real concurrency control, and an explicit lock for jobs that must not overlap.换用真正支持并发控制的存储,并对不能重叠的任务显式加锁。
Lesson教训
Find out how your store handles a second writer before you have one.在出现第二个写入方之前,先弄清你的存储会如何处理它。
2026-09

A findings file that was 97 percent duplicates一个 97% 都是重复内容的发现记录文件

What happened发生了什么
A job re-recorded the same 26 findings about 11,000 times, once every hour.一个任务每小时把同样的 26 条发现重新记录一遍,累计约 11,000 次。
Fix修复
A cursor per job, and a uniqueness rule on what is recorded.每个任务一个游标,并对记录内容加唯一性约束。
Lesson教训
A job without a cursor counts its own repetition as evidence.没有游标的任务,会把自己的重复劳动当成证据。

The same idea on other platforms同样的思路在其他平台上

Platform平台How this module maps本模块如何对应
DatabricksDelta tables for durable state. Lakebase for Postgres-style transactional state such as threads and checkpoints. Run state lives in your agent code.持久状态用 Delta 表。会话和检查点这类事务型状态用 Lakebase(Postgres 风格)。运行状态在你的智能体代码里。
IBM watsonxOrchestrate manages thread state for its agents. Durable domain state goes in watsonx.data or a database you connect.Orchestrate 为其智能体管理会话状态。持久的业务状态放在 watsonx.data 或你接入的数据库里。
CodexSession history is managed by the tool and can be resumed. Durable project state is files in the repo.会话历史由工具管理,可以恢复。持久的项目状态是仓库里的文件。
CursorChat history is managed by the editor. Durable state is files, plus whatever your MCP servers store.聊天历史由编辑器管理。持久状态是文件,以及你的 MCP 服务自己存的数据。
Claude Code / Agent SDKSessions can be resumed and the SDK exposes session ids. Durable state is files and your own stores.会话可以恢复,SDK 提供会话 ID。持久状态是文件和你自己的存储。
Another machineSQLite with WAL is enough for one machine. Postgres in a container gives the same layout with stronger guarantees.单机用开启 WAL 的 SQLite 就够了。容器里的 Postgres 结构相同,保障更强。

Step-by-step guides per platform各平台的分步指南

Explain it back讲给自己听

Answer aloud first. Then open the answer and compare.先自己说一遍答案,再展开对照。

Name three kinds of state and their lifetimes.说出三种状态及其生命周期。
A strong answer参考答案Run state lasts one request. Conversation state lasts a thread. Knowledge and memory last until retired. Mixing them leads to leaks across users or loss across requests.运行状态持续一次请求。对话状态持续一个会话。知识和记忆持续到被退役。混用会导致用户间的数据泄露,或请求间的数据丢失。
Why are merge rules part of storage and not part of the harness?为什么合并规则属于存储,而不属于 Harness?
A strong answer参考答案They define what happens when two writers update the same state. That is a storage question. The harness only decides when nodes run.它定义的是两个写入方更新同一状态时会发生什么,这是存储层面的问题。Harness 只决定节点何时运行。
Why build the cursor now when no job reads logs yet?现在还没有任务读日志,为什么要先做游标?
A strong answer参考答案Every later background job assumes it. Building it once here means no job invents its own, and none re-reads a log from the start.后面每个后台任务都默认它已经存在。在这里统一做好,就不会有任务各自发明一套,也不会有任务从头重读日志。
How do you delete everything the agent taught itself, and nothing else?如何只删除智能体自己学到的内容,而不影响其他?
A strong answer参考答案Drop the brain tables. Ingested documents are in kb and user memory is in mem, so neither is touched. This works only because ownership was decided before the tables were created.删除 brain 表。入库文档在 kb,用户记忆在 mem,两者都不受影响。这之所以可行,是因为建表之前就确定了归属。

Terms术语

WALWAL(预写日志)Write-ahead logging. Changes go to a log first, so readers are not blocked by a writer.修改先写入日志,因此读取不会被写入阻塞。
Cursor游标A saved position in a log, one per job.日志中保存下来的位置,每个任务一个。
Partition分区The value, usually a user id, that scopes every memory read and write.限定每次记忆读写范围的值,通常是用户 ID。

From the live build来自实时构建

Recent changes and files the sync job filed under this module. These lines are in English as written in the build.同步任务归到本模块下的近期变更和文件。这些内容保留了构建系统中的英文原文。

Ask the tutor about this module就本模块向导师提问