[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M792BXPN33DF8V1JZA5ED407":3,"skill-same:01M792BXPN33DF8V1JZA5ED407":61},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":38,"commitSha":39,"skillDirectory":40,"forksCount":41,"repositoryHtmlUrl":42,"repositoryHomepageUrl":6,"ownerHtmlUrl":43,"ownerBlogUrl":44,"ownerDescription":45,"updatedAt":46,"install":47,"resources":60},"01M792BXPN33DF8V1JZA5ED407","langchain-langgraph-checkpointing",null,"Persist LangGraph agent state correctly with MemorySaver and PostgresSaver —\nthread_id discipline, JSON-serializable state rules, time-travel, schema\nmigration. Use when adding chat memory, migrating from ConversationBufferMemory,\nor time-traveling an agent state to debug an incident.\nTrigger with \"langgraph checkpointer\", \"MemorySaver\", \"PostgresSaver\",\n\"thread_id\", \"langgraph time travel\", \"langgraph state persistence\".","jukeyman\u002Fjukeyman-skills","jukeyman","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F142960420?v=4","01M78FR4Y3DHMMCBCC0GXXNB3F","RICK JEFFERSON","01M78FR4Z8RVQRAD31Y5J7V6EB",1,"MIT","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--langchain-py-pack--langchain-langgraph-checkpointing\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: langchain-langgraph-checkpointing\ndescription: |\n  Persist LangGraph agent state correctly with MemorySaver and PostgresSaver —\n  thread_id discipline, JSON-serializable state rules, time-travel, schema\n  migration. Use when adding chat memory, migrating from ConversationBufferMemory,\n  or time-traveling an agent state to debug an incident.\n  Trigger with \"langgraph checkpointer\", \"MemorySaver\", \"PostgresSaver\",\n  \"thread_id\", \"langgraph time travel\", \"langgraph state persistence\".\nallowed-tools: Read, Write, Edit, Bash(python:*), Bash(psql:*)\nversion: 2.0.0\nlicense: MIT\nauthor: Jeremy Longshore \u003Cjeremy@intentsolutions.io>\ntags: [saas, langchain, langgraph, python, langchain-1.0, checkpointing, persistence, memory]\ncompatible-with: claude-code, codex\n---\n\n# LangGraph Checkpointing (Python)\n\n## Overview\n\nA chat agent that \"keeps introducing itself\" is almost always P16. The caller\ninvokes `graph.invoke(state)` without passing `config={\"configurable\":\n{\"thread_id\": ...}}` — LangGraph's checkpointer silently spawns a fresh state per\ncall. No error, no warning, no log line. The user sees it; the code does not.\n\nThat is one of five separate checkpointing pitfalls this skill covers:\n\n- **P16** — missing `thread_id` silently resets memory\n- **P17** — `interrupt_before` raises `TypeError` when state holds non-JSON values\n  (`datetime`, `Decimal`, custom classes) — and it raises *at the interrupt\n  boundary*, not when the bad value was first assigned, so the traceback points\n  at the wrong line\n- **P20** — `PostgresSaver` does not auto-migrate checkpoint schema; upgrading\n  `langgraph` silently reads old checkpoints as empty state\n- **P40** — `ConversationBufferMemory` and the rest of legacy chat memory were\n  removed in LangChain 1.0; checkpointers are the replacement\n- **P51** — Deep Agent virtual-FS state in `state[\"files\"]` grows unboundedly\n  and eventually makes checkpoint writes a latency hotspot\n\nThis skill walks through picking a checkpointer by environment, enforcing\n`thread_id` at the application boundary, constraining state to JSON-safe\nprimitives, Postgres setup + migration, and time-travel for incident debugging.\nPinned to `langgraph >= 1.0, \u003C 2.0`, `langgraph-checkpoint-postgres >= 1.0, \u003C\n2.0`. Pain-catalog anchors: P16, P17, P18, P20, P22, P40, P51.\n\n## Prerequisites\n\n- Python 3.10+\n- `pip install langgraph langchain-core` (both `>= 1.0, \u003C 2.0`)\n- For Postgres: `pip install langgraph-checkpoint-postgres` and a Postgres 13+\n  instance\n- For async Postgres: the same package plus `asyncpg`\n- A `thread_id` strategy — typically a UUID4 string per conversation; see\n  [thread-id-discipline.md](references\u002Fthread-id-discipline.md)\n\n## Instructions\n\n### Step 1 — Pick a checkpointer by environment\n\n| Env | Checkpointer | Import |\n|---|---|---|\n| Dev, tests, notebooks | `MemorySaver` | `langgraph.checkpoint.memory` |\n| Single-host CLI \u002F desktop | `SqliteSaver` | `langgraph.checkpoint.sqlite` |\n| Staging, prod (sync) | `PostgresSaver` | `langgraph.checkpoint.postgres` |\n| Staging, prod (async \u002F FastAPI) | `AsyncPostgresSaver` | `langgraph.checkpoint.postgres.aio` |\n\n`MemorySaver` is in-process only. State vanishes on restart. Every worker has\nits own (P22 analog for LangGraph). Use it anywhere state loss is acceptable;\nnever in a multi-worker web backend.\n\n`PostgresSaver` and its async sibling require `setup()` on every startup *and\nafter every `langgraph` upgrade* (see Step 5). Checkpoint storage overhead is\ntypically **1-10 KB per step** of serialized state; plan your DB size\naccordingly — a 2,000-turn conversation with 3 KB average state fits in\n~6 MB per thread.\n\nSee [checkpointer-comparison.md](references\u002Fcheckpointer-comparison.md) for the\nfull matrix including latency, concurrency, and the FastAPI lifespan pattern.\n\n### Step 2 — Require `thread_id` at every invocation\n\nThis is the fail-loud middleware that prevents P16:\n\n```python\nfrom typing import Any\n\ndef require_thread_id(config: dict[str, Any]) -> dict[str, Any]:\n    \"\"\"Raise if thread_id is missing. Fails loud so P16 surfaces in tests,\n    not in user-visible conversation logs.\"\"\"\n    configurable = (config or {}).get(\"configurable\", {})\n    thread_id = configurable.get(\"thread_id\")\n    if not thread_id:\n        raise ValueError(\n            \"thread_id missing from config['configurable']. \"\n            \"Every graph invocation must carry a thread_id.\"\n        )\n    if not isinstance(thread_id, str):\n        raise TypeError(\n            f\"thread_id must be str (UUID), got {type(thread_id).__name__}\"\n        )\n    return config\n```\n\nCall it at every application boundary:\n\n```python\nimport uuid\n\nconfig = {\"configurable\": {\"thread_id\": str(uuid.uuid4())}}\nrequire_thread_id(config)\nresult = graph.invoke(initial_state, config=config)\n```\n\nFor web endpoints, extract to a FastAPI dependency (`Header(...)` with no\ndefault — forces `422` on missing). For multi-tenant apps, scope the thread id by composing tenant + user +\nconversation ids into a single colon-delimited string (example:\n`\"acme:alice:conv-1\"`). See\n[thread-id-discipline.md](references\u002Fthread-id-discipline.md) for UUID\ngeneration, rotation, and the integration test that proves tenants do not share\nstate.\n\n### Step 3 — Keep state JSON-serializable (TypedDict, primitives only)\n\n```python\nfrom typing import Annotated, TypedDict\nfrom langgraph.graph.message import add_messages\nfrom langchain_core.messages import AnyMessage\n\n\nclass AgentState(TypedDict):\n    # Messages are safe — LangGraph registers a custom serializer.\n    messages: Annotated[list[AnyMessage], add_messages]\n\n    # Primitives only below. NO datetime, NO Decimal, NO custom classes.\n    user_id: str\n    turn_count: int\n    last_action_at: str           # ISO string, not datetime.datetime\n    pending_approval: bool\n    metadata: dict[str, str]      # dict keys must be str\n    plan: list[dict[str, str]]    # list of primitive dicts\n```\n\nThe rule: **state fields must be JSON-safe primitives or recursive structures\nof them** (`str`, `int`, `float`, `bool`, `None`, `list`, `dict[str, ...]`).\n`json.dumps(state)` must succeed. If it raises, the checkpointer raises —\noften at a HITL interrupt many steps later (P17), which is why the traceback\nnever points at the line that introduced the bad value.\n\nFor non-primitive inputs, coerce at node output boundaries with a helper:\n\n```python\nfrom datetime import datetime\nfrom decimal import Decimal\n\ndef record_purchase(state: AgentState) -> dict:\n    now = datetime.utcnow()\n    price = Decimal(\"19.99\")\n    return {\n        \"last_action_at\": now.isoformat(),\n        \"metadata\": {**state[\"metadata\"], \"price\": str(price)},\n    }\n```\n\nForbidden-types reference and the full `to_state` \u002F `from_state` helper pair\nare in [json-serializability-rules.md](references\u002Fjson-serializability-rules.md).\n\n### Step 4 — Compile the graph with a checkpointer (Postgres, sync)\n\n```python\nfrom langgraph.checkpoint.postgres import PostgresSaver\nfrom langgraph.graph import StateGraph\nimport os\n\nDB_URI = os.environ[\"DATABASE_URL\"]\n\ndef build_graph() -> StateGraph:\n    builder = StateGraph(AgentState)\n    builder.add_node(\"agent\", agent_node)\n    builder.add_node(\"human_approval\", human_approval_node)\n    builder.set_entry_point(\"agent\")\n    builder.add_edge(\"agent\", \"human_approval\")\n    builder.set_finish_point(\"human_approval\")\n    return builder\n\nwith PostgresSaver.from_conn_string(DB_URI) as checkpointer:\n    checkpointer.setup()     # Idempotent. Creates checkpoint tables if missing.\n    graph = build_graph().compile(\n        checkpointer=checkpointer,\n        interrupt_before=[\"human_approval\"],\n    )\n\n    config = {\"configurable\": {\"thread_id\": \"user-123\"}}\n    require_thread_id(config)\n    result = graph.invoke({\"messages\": [HumanMessage(\"hi\")]}, config=config)\n```\n\nFor async, mirror the pattern with `AsyncPostgresSaver.from_conn_string(...)`\ninside a FastAPI `@asynccontextmanager` lifespan; every call site uses\n`await graph.ainvoke(...)`.\n\n### Step 5 — Run `setup()` on startup AND after every `langgraph` upgrade\n\nP20 is the quiet one: you `pip install --upgrade langgraph`, tests pass, CI\ngoes green, you deploy. Existing threads come back empty. No DB error.\n\n```python\n# Put this in your deploy script \u002F migration runbook:\nwith PostgresSaver.from_conn_string(DB_URI) as checkpointer:\n    checkpointer.setup()\n    # Sanity check: read one known thread and assert it's not empty.\n    snap = checkpointer.get({\"configurable\": {\"thread_id\": \"canary-thread\"}})\n    assert snap is not None, \"Canary thread lost after schema migration\"\n```\n\nRun this in **staging** first, with a canary thread whose state you pre-populated\nfrom an older `langgraph` version. If the assertion holds, promote. If not,\nthe migration path is: dump checkpoints, upgrade, restore via a migration\nscript. Do **not** promote to production on a version bump without this check.\n\n### Step 6 — Time-travel for incident debugging\n\nEvery checkpoint is keyed by `(thread_id, checkpoint_id)` and reachable via\n`graph.get_state_history(config)`:\n\n```python\nconfig = {\"configurable\": {\"thread_id\": bad_thread_id}}\nhistory = list(graph.get_state_history(config))\n\nfor i, snap in enumerate(history):\n    print(i, snap.metadata.get(\"step\"), snap.next, list(snap.values.keys()))\n\n# Resume from a specific prior checkpoint — None as input = \"use this state\":\npast = history[3]                                    # history is newest-first\nresult = graph.invoke(None, config=past.config)       # past.config pins checkpoint_id\n```\n\nTo fix state and replay:\n\n```python\ngraph.update_state(\n    past.config,\n    {\"retry_count\": 0, \"error_reason\": None},\n    as_node=\"validator\",\n)\ngraph.invoke(None, config=past.config)\n```\n\nThe original branch is preserved — `update_state` creates a new checkpoint\nalongside the old one. Useful for forensics and for A\u002FB comparing an old vs\nnew model on the exact same state.\n\nSee [time-travel-and-replay.md](references\u002Ftime-travel-and-replay.md) for the\nfull incident playbook, branching for A\u002FB eval, and checkpoint pruning SQL.\n\n## Output\n\n- A checkpointer selected by environment, not copy-pasted from a tutorial\n- A `require_thread_id` middleware that fails loud on missing `thread_id`, and\n  at least one integration test that asserts two tenants do not share state\n- An `AgentState` TypedDict constrained to JSON-safe primitives, plus a\n  `to_state` helper at node output boundaries for `datetime` \u002F `Decimal` \u002F\n  Pydantic \u002F enums\n- `PostgresSaver.setup()` wired into startup **and** every deploy that bumps\n  `langgraph`\n- An incident runbook that uses `get_state_history` + `update_state` to\n  time-travel an agent state, with prior branches preserved\n\n## Error Handling\n\n| Error | Cause | Fix |\n|-------|-------|-----|\n| Agent forgets every turn, no error logged | Missing `thread_id` (P16) | Add `require_thread_id` middleware at app boundary; FastAPI `Header(...)` with no default |\n| `TypeError: Object of type datetime is not JSON serializable` at a HITL pause | Non-JSON value in state (P17) | Coerce at node output: `dt.isoformat()`, `str(decimal)`, `model.model_dump(mode=\"json\")` |\n| Upgrading `langgraph` returns empty state for existing threads | Checkpoint schema drift (P20) | `PostgresSaver.setup()` after every upgrade; canary-thread assertion in staging before prod |\n| `ImportError: cannot import name 'ConversationBufferMemory'` | Legacy memory removed in 1.0 (P40) | Migrate to `MemorySaver`\u002F`PostgresSaver` + `thread_id` per conversation |\n| Checkpoint writes take 500+ ms on Deep Agent runs | Unbounded `state[\"files\"]` growth (P51) | Add cleanup node that prunes `state[\"files\"]` older than N steps |\n| `Command(update={\"messages\": [x]})` erases prior messages | Missing reducer (P18) | `messages: Annotated[list[AnyMessage], add_messages]` |\n| Mixed `graph.invoke` with `AsyncPostgresSaver` | Sync call on async saver | Use `await graph.ainvoke(...)` everywhere, or switch to sync `PostgresSaver` |\n\n## Examples\n\n### Minimal chat agent with `MemorySaver`\n\nDev-mode multi-turn chat that survives within a single process. Good for local\niteration and pytest fixtures; state vanishes on restart.\n\n```python\nfrom langgraph.checkpoint.memory import MemorySaver\nfrom langgraph.prebuilt import create_react_agent\nfrom langchain_anthropic import ChatAnthropic\n\ncheckpointer = MemorySaver()\nagent = create_react_agent(\n    model=ChatAnthropic(model=\"claude-sonnet-4-6\"),\n    tools=[...],\n    checkpointer=checkpointer,\n)\nconfig = {\"configurable\": {\"thread_id\": \"dev-session-1\"}}\nagent.invoke({\"messages\": [HumanMessage(\"hi\")]}, config=config)\nagent.invoke({\"messages\": [HumanMessage(\"remember my name is alice\")]}, config=config)\nagent.invoke({\"messages\": [HumanMessage(\"what's my name?\")]}, config=config)  # alice\n```\n\n### Multi-tenant Postgres + FastAPI lifespan\n\nAsync production shape. One `AsyncPostgresSaver` pool, thread-id extracted from\na required header, tenants isolated by a composite key.\n\nSee [checkpointer-comparison.md](references\u002Fcheckpointer-comparison.md) for the\ncomplete FastAPI lifespan pattern and pool sizing advice (`max_size` needs to\nexceed concurrent graph count, and the LangGraph pool should be separate from\nthe application's primary DB pool).\n\n### Migrating from `ConversationBufferMemory` (P40)\n\nLegacy 0.x pattern replaced end-to-end:\n\n```python\n# OLD — raises ImportError on 1.0:\n# from langchain.memory import ConversationBufferMemory\n# memory = ConversationBufferMemory()\n# chain = LLMChain(llm=llm, memory=memory)\n\n# NEW:\nfrom langgraph.prebuilt import create_react_agent\nfrom langgraph.checkpoint.postgres import PostgresSaver\n\nwith PostgresSaver.from_conn_string(DB_URI) as cp:\n    cp.setup()\n    agent = create_react_agent(model=llm, tools=tools, checkpointer=cp)\n    config = {\"configurable\": {\"thread_id\": user_session_id}}\n    agent.invoke({\"messages\": [HumanMessage(user_input)]}, config=config)\n```\n\nThe `thread_id` is now the \"session key\" that `ConversationBufferMemory` used\nto carry implicitly.\n\n### Incident time-travel\n\nProduction returned a wrong answer for `thread_id=bad-thread` at 14:03.\nWalk history newest-first, inspect the prior state, patch and replay:\n\n```python\nconfig = {\"configurable\": {\"thread_id\": \"bad-thread\"}}\nhistory = list(graph.get_state_history(config))\nfor i, snap in enumerate(history):\n    print(i, snap.metadata.get(\"step\"), snap.next)\n# Assume step 7 wrote the bad output; step 6 is the input.\nprior = history[-7]  # or index by metadata[\"step\"]\nprint(\"input to bad node:\", prior.values)\ngraph.update_state(prior.config, {\"retry_count\": 0}, as_node=\"validator\")\ngraph.invoke(None, config=prior.config)  # new branch with correct result\n```\n\nFull playbook (finding `thread_id` in logs, inspecting `writes` metadata,\npruning history) in\n[time-travel-and-replay.md](references\u002Ftime-travel-and-replay.md).\n\n## Resources\n\n- [LangGraph persistence concepts](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Fconcepts\u002Fpersistence\u002F)\n- [Checkpointer API reference](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Freference\u002Fcheckpoints\u002F)\n- [LangGraph HITL concepts](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Fconcepts\u002Fhuman_in_the_loop\u002F)\n- [LangGraph 1.0 release notes](https:\u002F\u002Fblog.langchain.com\u002Flangchain-langgraph-1dot0\u002F)\n- Pack pain catalog: `docs\u002Fpain-catalog.md` (entries P16, P17, P18, P20, P22, P40, P51)\n- Related skills in this pack: `langchain-langgraph-basics`, `langchain-langgraph-agents`, `langchain-upgrade-migration`, `langchain-common-errors`\n","# LangGraph Checkpointing (Python)\n\n## Overview\n\nA chat agent that \"keeps introducing itself\" is almost always P16. The caller\ninvokes `graph.invoke(state)` without passing `config={\"configurable\":\n{\"thread_id\": ...}}` — LangGraph's checkpointer silently spawns a fresh state per\ncall. No error, no warning, no log line. The user sees it; the code does not.\n\nThat is one of five separate checkpointing pitfalls this skill covers:\n\n- **P16** — missing `thread_id` silently resets memory\n- **P17** — `interrupt_before` raises `TypeError` when state holds non-JSON values\n  (`datetime`, `Decimal`, custom classes) — and it raises *at the interrupt\n  boundary*, not when the bad value was first assigned, so the traceback points\n  at the wrong line\n- **P20** — `PostgresSaver` does not auto-migrate checkpoint schema; upgrading\n  `langgraph` silently reads old checkpoints as empty state\n- **P40** — `ConversationBufferMemory` and the rest of legacy chat memory were\n  removed in LangChain 1.0; checkpointers are the replacement\n- **P51** — Deep Agent virtual-FS state in `state[\"files\"]` grows unboundedly\n  and eventually makes checkpoint writes a latency hotspot\n\nThis skill walks through picking a checkpointer by environment, enforcing\n`thread_id` at the application boundary, constraining state to JSON-safe\nprimitives, Postgres setup + migration, and time-travel for incident debugging.\nPinned to `langgraph >= 1.0, \u003C 2.0`, `langgraph-checkpoint-postgres >= 1.0, \u003C\n2.0`. Pain-catalog anchors: P16, P17, P18, P20, P22, P40, P51.\n\n## Prerequisites\n\n- Python 3.10+\n- `pip install langgraph langchain-core` (both `>= 1.0, \u003C 2.0`)\n- For Postgres: `pip install langgraph-checkpoint-postgres` and a Postgres 13+\n  instance\n- For async Postgres: the same package plus `asyncpg`\n- A `thread_id` strategy — typically a UUID4 string per conversation; see\n  [thread-id-discipline.md](references\u002Fthread-id-discipline.md)\n\n## Instructions\n\n### Step 1 — Pick a checkpointer by environment\n\n| Env | Checkpointer | Import |\n|---|---|---|\n| Dev, tests, notebooks | `MemorySaver` | `langgraph.checkpoint.memory` |\n| Single-host CLI \u002F desktop | `SqliteSaver` | `langgraph.checkpoint.sqlite` |\n| Staging, prod (sync) | `PostgresSaver` | `langgraph.checkpoint.postgres` |\n| Staging, prod (async \u002F FastAPI) | `AsyncPostgresSaver` | `langgraph.checkpoint.postgres.aio` |\n\n`MemorySaver` is in-process only. State vanishes on restart. Every worker has\nits own (P22 analog for LangGraph). Use it anywhere state loss is acceptable;\nnever in a multi-worker web backend.\n\n`PostgresSaver` and its async sibling require `setup()` on every startup *and\nafter every `langgraph` upgrade* (see Step 5). Checkpoint storage overhead is\ntypically **1-10 KB per step** of serialized state; plan your DB size\naccordingly — a 2,000-turn conversation with 3 KB average state fits in\n~6 MB per thread.\n\nSee [checkpointer-comparison.md](references\u002Fcheckpointer-comparison.md) for the\nfull matrix including latency, concurrency, and the FastAPI lifespan pattern.\n\n### Step 2 — Require `thread_id` at every invocation\n\nThis is the fail-loud middleware that prevents P16:\n\n```python\nfrom typing import Any\n\ndef require_thread_id(config: dict[str, Any]) -> dict[str, Any]:\n    \"\"\"Raise if thread_id is missing. Fails loud so P16 surfaces in tests,\n    not in user-visible conversation logs.\"\"\"\n    configurable = (config or {}).get(\"configurable\", {})\n    thread_id = configurable.get(\"thread_id\")\n    if not thread_id:\n        raise ValueError(\n            \"thread_id missing from config['configurable']. \"\n            \"Every graph invocation must carry a thread_id.\"\n        )\n    if not isinstance(thread_id, str):\n        raise TypeError(\n            f\"thread_id must be str (UUID), got {type(thread_id).__name__}\"\n        )\n    return config\n```\n\nCall it at every application boundary:\n\n```python\nimport uuid\n\nconfig = {\"configurable\": {\"thread_id\": str(uuid.uuid4())}}\nrequire_thread_id(config)\nresult = graph.invoke(initial_state, config=config)\n```\n\nFor web endpoints, extract to a FastAPI dependency (`Header(...)` with no\ndefault — forces `422` on missing). For multi-tenant apps, scope the thread id by composing tenant + user +\nconversation ids into a single colon-delimited string (example:\n`\"acme:alice:conv-1\"`). See\n[thread-id-discipline.md](references\u002Fthread-id-discipline.md) for UUID\ngeneration, rotation, and the integration test that proves tenants do not share\nstate.\n\n### Step 3 — Keep state JSON-serializable (TypedDict, primitives only)\n\n```python\nfrom typing import Annotated, TypedDict\nfrom langgraph.graph.message import add_messages\nfrom langchain_core.messages import AnyMessage\n\n\nclass AgentState(TypedDict):\n    # Messages are safe — LangGraph registers a custom serializer.\n    messages: Annotated[list[AnyMessage], add_messages]\n\n    # Primitives only below. NO datetime, NO Decimal, NO custom classes.\n    user_id: str\n    turn_count: int\n    last_action_at: str           # ISO string, not datetime.datetime\n    pending_approval: bool\n    metadata: dict[str, str]      # dict keys must be str\n    plan: list[dict[str, str]]    # list of primitive dicts\n```\n\nThe rule: **state fields must be JSON-safe primitives or recursive structures\nof them** (`str`, `int`, `float`, `bool`, `None`, `list`, `dict[str, ...]`).\n`json.dumps(state)` must succeed. If it raises, the checkpointer raises —\noften at a HITL interrupt many steps later (P17), which is why the traceback\nnever points at the line that introduced the bad value.\n\nFor non-primitive inputs, coerce at node output boundaries with a helper:\n\n```python\nfrom datetime import datetime\nfrom decimal import Decimal\n\ndef record_purchase(state: AgentState) -> dict:\n    now = datetime.utcnow()\n    price = Decimal(\"19.99\")\n    return {\n        \"last_action_at\": now.isoformat(),\n        \"metadata\": {**state[\"metadata\"], \"price\": str(price)},\n    }\n```\n\nForbidden-types reference and the full `to_state` \u002F `from_state` helper pair\nare in [json-serializability-rules.md](references\u002Fjson-serializability-rules.md).\n\n### Step 4 — Compile the graph with a checkpointer (Postgres, sync)\n\n```python\nfrom langgraph.checkpoint.postgres import PostgresSaver\nfrom langgraph.graph import StateGraph\nimport os\n\nDB_URI = os.environ[\"DATABASE_URL\"]\n\ndef build_graph() -> StateGraph:\n    builder = StateGraph(AgentState)\n    builder.add_node(\"agent\", agent_node)\n    builder.add_node(\"human_approval\", human_approval_node)\n    builder.set_entry_point(\"agent\")\n    builder.add_edge(\"agent\", \"human_approval\")\n    builder.set_finish_point(\"human_approval\")\n    return builder\n\nwith PostgresSaver.from_conn_string(DB_URI) as checkpointer:\n    checkpointer.setup()     # Idempotent. Creates checkpoint tables if missing.\n    graph = build_graph().compile(\n        checkpointer=checkpointer,\n        interrupt_before=[\"human_approval\"],\n    )\n\n    config = {\"configurable\": {\"thread_id\": \"user-123\"}}\n    require_thread_id(config)\n    result = graph.invoke({\"messages\": [HumanMessage(\"hi\")]}, config=config)\n```\n\nFor async, mirror the pattern with `AsyncPostgresSaver.from_conn_string(...)`\ninside a FastAPI `@asynccontextmanager` lifespan; every call site uses\n`await graph.ainvoke(...)`.\n\n### Step 5 — Run `setup()` on startup AND after every `langgraph` upgrade\n\nP20 is the quiet one: you `pip install --upgrade langgraph`, tests pass, CI\ngoes green, you deploy. Existing threads come back empty. No DB error.\n\n```python\n# Put this in your deploy script \u002F migration runbook:\nwith PostgresSaver.from_conn_string(DB_URI) as checkpointer:\n    checkpointer.setup()\n    # Sanity check: read one known thread and assert it's not empty.\n    snap = checkpointer.get({\"configurable\": {\"thread_id\": \"canary-thread\"}})\n    assert snap is not None, \"Canary thread lost after schema migration\"\n```\n\nRun this in **staging** first, with a canary thread whose state you pre-populated\nfrom an older `langgraph` version. If the assertion holds, promote. If not,\nthe migration path is: dump checkpoints, upgrade, restore via a migration\nscript. Do **not** promote to production on a version bump without this check.\n\n### Step 6 — Time-travel for incident debugging\n\nEvery checkpoint is keyed by `(thread_id, checkpoint_id)` and reachable via\n`graph.get_state_history(config)`:\n\n```python\nconfig = {\"configurable\": {\"thread_id\": bad_thread_id}}\nhistory = list(graph.get_state_history(config))\n\nfor i, snap in enumerate(history):\n    print(i, snap.metadata.get(\"step\"), snap.next, list(snap.values.keys()))\n\n# Resume from a specific prior checkpoint — None as input = \"use this state\":\npast = history[3]                                    # history is newest-first\nresult = graph.invoke(None, config=past.config)       # past.config pins checkpoint_id\n```\n\nTo fix state and replay:\n\n```python\ngraph.update_state(\n    past.config,\n    {\"retry_count\": 0, \"error_reason\": None},\n    as_node=\"validator\",\n)\ngraph.invoke(None, config=past.config)\n```\n\nThe original branch is preserved — `update_state` creates a new checkpoint\nalongside the old one. Useful for forensics and for A\u002FB comparing an old vs\nnew model on the exact same state.\n\nSee [time-travel-and-replay.md](references\u002Ftime-travel-and-replay.md) for the\nfull incident playbook, branching for A\u002FB eval, and checkpoint pruning SQL.\n\n## Output\n\n- A checkpointer selected by environment, not copy-pasted from a tutorial\n- A `require_thread_id` middleware that fails loud on missing `thread_id`, and\n  at least one integration test that asserts two tenants do not share state\n- An `AgentState` TypedDict constrained to JSON-safe primitives, plus a\n  `to_state` helper at node output boundaries for `datetime` \u002F `Decimal` \u002F\n  Pydantic \u002F enums\n- `PostgresSaver.setup()` wired into startup **and** every deploy that bumps\n  `langgraph`\n- An incident runbook that uses `get_state_history` + `update_state` to\n  time-travel an agent state, with prior branches preserved\n\n## Error Handling\n\n| Error | Cause | Fix |\n|-------|-------|-----|\n| Agent forgets every turn, no error logged | Missing `thread_id` (P16) | Add `require_thread_id` middleware at app boundary; FastAPI `Header(...)` with no default |\n| `TypeError: Object of type datetime is not JSON serializable` at a HITL pause | Non-JSON value in state (P17) | Coerce at node output: `dt.isoformat()`, `str(decimal)`, `model.model_dump(mode=\"json\")` |\n| Upgrading `langgraph` returns empty state for existing threads | Checkpoint schema drift (P20) | `PostgresSaver.setup()` after every upgrade; canary-thread assertion in staging before prod |\n| `ImportError: cannot import name 'ConversationBufferMemory'` | Legacy memory removed in 1.0 (P40) | Migrate to `MemorySaver`\u002F`PostgresSaver` + `thread_id` per conversation |\n| Checkpoint writes take 500+ ms on Deep Agent runs | Unbounded `state[\"files\"]` growth (P51) | Add cleanup node that prunes `state[\"files\"]` older than N steps |\n| `Command(update={\"messages\": [x]})` erases prior messages | Missing reducer (P18) | `messages: Annotated[list[AnyMessage], add_messages]` |\n| Mixed `graph.invoke` with `AsyncPostgresSaver` | Sync call on async saver | Use `await graph.ainvoke(...)` everywhere, or switch to sync `PostgresSaver` |\n\n## Examples\n\n### Minimal chat agent with `MemorySaver`\n\nDev-mode multi-turn chat that survives within a single process. Good for local\niteration and pytest fixtures; state vanishes on restart.\n\n```python\nfrom langgraph.checkpoint.memory import MemorySaver\nfrom langgraph.prebuilt import create_react_agent\nfrom langchain_anthropic import ChatAnthropic\n\ncheckpointer = MemorySaver()\nagent = create_react_agent(\n    model=ChatAnthropic(model=\"claude-sonnet-4-6\"),\n    tools=[...],\n    checkpointer=checkpointer,\n)\nconfig = {\"configurable\": {\"thread_id\": \"dev-session-1\"}}\nagent.invoke({\"messages\": [HumanMessage(\"hi\")]}, config=config)\nagent.invoke({\"messages\": [HumanMessage(\"remember my name is alice\")]}, config=config)\nagent.invoke({\"messages\": [HumanMessage(\"what's my name?\")]}, config=config)  # alice\n```\n\n### Multi-tenant Postgres + FastAPI lifespan\n\nAsync production shape. One `AsyncPostgresSaver` pool, thread-id extracted from\na required header, tenants isolated by a composite key.\n\nSee [checkpointer-comparison.md](references\u002Fcheckpointer-comparison.md) for the\ncomplete FastAPI lifespan pattern and pool sizing advice (`max_size` needs to\nexceed concurrent graph count, and the LangGraph pool should be separate from\nthe application's primary DB pool).\n\n### Migrating from `ConversationBufferMemory` (P40)\n\nLegacy 0.x pattern replaced end-to-end:\n\n```python\n# OLD — raises ImportError on 1.0:\n# from langchain.memory import ConversationBufferMemory\n# memory = ConversationBufferMemory()\n# chain = LLMChain(llm=llm, memory=memory)\n\n# NEW:\nfrom langgraph.prebuilt import create_react_agent\nfrom langgraph.checkpoint.postgres import PostgresSaver\n\nwith PostgresSaver.from_conn_string(DB_URI) as cp:\n    cp.setup()\n    agent = create_react_agent(model=llm, tools=tools, checkpointer=cp)\n    config = {\"configurable\": {\"thread_id\": user_session_id}}\n    agent.invoke({\"messages\": [HumanMessage(user_input)]}, config=config)\n```\n\nThe `thread_id` is now the \"session key\" that `ConversationBufferMemory` used\nto carry implicitly.\n\n### Incident time-travel\n\nProduction returned a wrong answer for `thread_id=bad-thread` at 14:03.\nWalk history newest-first, inspect the prior state, patch and replay:\n\n```python\nconfig = {\"configurable\": {\"thread_id\": \"bad-thread\"}}\nhistory = list(graph.get_state_history(config))\nfor i, snap in enumerate(history):\n    print(i, snap.metadata.get(\"step\"), snap.next)\n# Assume step 7 wrote the bad output; step 6 is the input.\nprior = history[-7]  # or index by metadata[\"step\"]\nprint(\"input to bad node:\", prior.values)\ngraph.update_state(prior.config, {\"retry_count\": 0}, as_node=\"validator\")\ngraph.invoke(None, config=prior.config)  # new branch with correct result\n```\n\nFull playbook (finding `thread_id` in logs, inspecting `writes` metadata,\npruning history) in\n[time-travel-and-replay.md](references\u002Ftime-travel-and-replay.md).\n\n## Resources\n\n- [LangGraph persistence concepts](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Fconcepts\u002Fpersistence\u002F)\n- [Checkpointer API reference](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Freference\u002Fcheckpoints\u002F)\n- [LangGraph HITL concepts](https:\u002F\u002Flangchain-ai.github.io\u002Flanggraph\u002Fconcepts\u002Fhuman_in_the_loop\u002F)\n- [LangGraph 1.0 release notes](https:\u002F\u002Fblog.langchain.com\u002Flangchain-langgraph-1dot0\u002F)\n- Pack pain catalog: `docs\u002Fpain-catalog.md` (entries P16, P17, P18, P20, P22, P40, P51)\n- Related skills in this pack: `langchain-langgraph-basics`, `langchain-langgraph-agents`, `langchain-upgrade-migration`, `langchain-common-errors`\n",{"name":5,"tags":24,"author":33,"license":15,"version":34,"description":35,"allowed-tools":36,"compatible-with":37},[25,26,27,28,29,30,31,32],"saas","langchain","langgraph","python","langchain-1.0","checkpointing","persistence","memory","Jeremy Longshore \u003Cjeremy@intentsolutions.io>","2.0.0","Persist LangGraph agent state correctly with MemorySaver and PostgresSaver —\nthread_id discipline, JSON-serializable state rules, time-travel, schema\nmigration. Use when adding chat memory, migrating from ConversationBufferMemory,\nor time-traveling an agent state to debug an incident.\nTrigger with \"langgraph checkpointer\", \"MemorySaver\", \"PostgresSaver\",\n\"thread_id\", \"langgraph time travel\", \"langgraph state persistence\".\n","Read, Write, Edit, Bash(python:*), Bash(psql:*)","claude-code, codex","main","99825ad3f3bcc6597ddcc7294a14e6e922f2b67b","skills\u002Fsaas-packs--langchain-py-pack--langchain-langgraph-checkpointing",0,"https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills","https:\u002F\u002Fgithub.com\u002Fjukeyman","https:\u002F\u002FRJBUSINESSSOLUTIONS.ORG","Credit and Finance Expert | Developer\r\n\r\nI'm Rick Jefferson, a seasoned credit and finance expert with over a decade of experience in financial literacy,","2026-07-13 07:03:29",{"source":8,"skillName":5,"commands":48,"prompt":58,"zipAvailable":59},[49,52,55],{"tool":50,"command":51},"npx","npx skills add jukeyman\u002Fjukeyman-skills --skill langchain-langgraph-checkpointing",{"tool":53,"command":54},"bunx","bunx skills add jukeyman\u002Fjukeyman-skills --skill langchain-langgraph-checkpointing",{"tool":56,"command":57},"pnpm","pnpm dlx skills add jukeyman\u002Fjukeyman-skills --skill langchain-langgraph-checkpointing","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fsaas-packs--langchain-py-pack--langchain-langgraph-checkpointing\u002FSKILL.md",true,[],[62,69,76,83,90,98],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M79ANS2SM329NEP5ZCX106RR","zustand-store-creator","Create zustand store creator operations. Auto-activating skill for Frontend Development.\nTriggers on: zustand store creator, zustand store creator\nPart of the Frontend Development skill category. Use when working with zustand store creator functionality. Trigger with phrases like \"zustand store creator\", \"zustand creator\", \"zustand\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzustand-store-creator\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M79AMZKP4YDEZ7EHG1Y7PP74","zero-trust-config-helper","Configure with zero trust config helper operations. Auto-activating skill for Security Advanced.\nTriggers on: zero trust config helper, zero trust config helper\nPart of the Security Advanced skill category. Use when configuring systems or services. Trigger with phrases like \"zero trust config helper\", \"zero helper\", \"zero\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzero-trust-config-helper\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M79AMJSBCEJQNBTYNAHYN5HM","zapier-integration-helper","Assist with zapier integration helper operations. Auto-activating skill for Business Automation.\nTriggers on: zapier integration helper, zapier integration helper\nPart of the Business Automation skill category. Use when working with APIs or building integrations. Trigger with phrases like \"zapier integration helper\", \"zapier helper\", \"zapier\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzapier-integration-helper\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M79AHJZGVMARS13VFQYRR1MP","yaml-config-validator","Validate yaml config validator operations. Auto-activating skill for DevOps Basics.\nTriggers on: yaml config validator, yaml config validator\nPart of the DevOps Basics skill category. Use when configuring systems or services. Trigger with phrases like \"yaml config validator\", \"yaml validator\", \"yaml\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fyaml-config-validator\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":94,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":19},"01M79AHGDZRN0020RDQSQDPAM8","xvary-stock-research","Thesis-driven equity analysis from public SEC EDGAR and market data; \u002Fanalyze, \u002Fscore, \u002Fcompare workflows with bundled Python tools (Claude Code, Cursor, Codex).","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxvary-stock-research\u002FSKILL.md",[],[],{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":19},"01M79AHCYJ9FV9RMHQ24HDRN33","xss-vulnerability-scanner","Scan xss vulnerability scanner operations. Auto-activating skill for Security Fundamentals.\nTriggers on: xss vulnerability scanner, xss vulnerability scanner\nPart of the Security Fundamentals skill category. Use when working with xss vulnerability scanner functionality. Trigger with phrases like \"xss vulnerability scanner\", \"xss scanner\", \"xss\".","https:\u002F\u002Fgithub.com\u002Fjukeyman\u002Fjukeyman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fxss-vulnerability-scanner\u002FSKILL.md",[],[]]