Runs & Durability

The Run row and its step trail, the LangGraph checkpoints beside it, and why the trail's writes commit on a session of their own.


A graph turn creates one runs row and appends one step to it per node. That row is the audit trail the UI renders and the join a reloaded conversation follows. LangGraph keeps its own record of the same turn, a checkpoint after every node, keyed by the run id.

class Run(Base):
    id: str                   # also the LangGraph thread_id
    conversation_id: str      # FK → conversations, CASCADE
    client_id: str            # denormalised, so lookups scope without a join
    status: str               # running | completed | failed
    current_stage: str | None
    steps: list               # JSON, one entry per node
    state: dict               # unused since D10; kept so pipeline-era rows still load

Three records of one turn

runs.stepsLangGraph checkpointstraces
GranularityOne entry per nodeThe full graph state after each nodeOne row per model or tool call
Answers”Why did this turn escalate?""Where does this turn continue from?""What did this call cost?”
Written byRunRecorder, on checkpoint_session()The checkpointer, on its own psycopg connectionThe request session
Survives a crashYesYesNo
Read byThe UI and conversation reloadconfirm_ticket()Cost roll-ups
Tablesrunscheckpoints, checkpoint_blobs, checkpoint_writestraces

The trail is for people and the checkpoints are for the graph. Keeping them apart means the UI never parses LangGraph’s serialized state, and a framework upgrade that changes the checkpoint format cannot break a conversation reload.

  • One connection for all checkpoints. AsyncPostgresSaver.from_conn_string() opens it in the app lifespan and serialises access with a lock. A pool is a known gap for when concurrent turns contend on it.
  • setup() runs on every start. It creates or migrates the checkpoint tables, so they need no Alembic migration.
  • Checkpoints are never pruned. A paused ticket offer has to outlive its request, so the rows cannot be deleted at turn end.

Why the trail’s writes need their own session

The request-scoped session from get_db commits once at the end of a turn and rolls back on any failure. A step written through it would be erased by exactly the crash it exists to survive.

So the trail goes through checkpoint_session() instead:

@asynccontextmanager
async def checkpoint_session() -> AsyncIterator[AsyncSession]:
    async with AsyncSessionLocal() as session:
        try:
            yield session
            await session.commit()
        except Exception:
            await session.rollback()
            raise

Each call opens its own connection, commits immediately, and closes. That costs one connection per node, which is cheaper than losing the audit trail.

The foreign-key trap. Run.conversation_id references conversations. An independent session cannot see a row the request session has only flushed, so the conversation is committed before the graph starts. Otherwise the first Run insert fails on a parent that isn’t visible yet.


A step entry

A node calls _step(), which calls RunRecorder.step(). That builds the entry, persists the whole list, and returns the same dict, which _step() writes to the stream. One shape, one write, so the stream and the record cannot disagree.

{
  "seq": 2,
  "stage": "grade",
  "status": "ok",
  "level": 1,
  "reasoning": "The passages cover Cloud Run deployment, runtime errors, CPU/memory limits, autoscaling…",
  "confidence": 0.05,
  "kind": "question",
  "latency_ms": 4110,
  "ts": "2026-09-11T05:42:32.418Z",
  "tokens_in": 1850,
  "tokens_out": 96,
  "cost_usd": 0.0024
}

Token counts in that sample are illustrative. Every entry carries level, and a node that called a model adds tokens_in, tokens_out and cost_usd. The rest depends on the node:

  • retrieve: n_hits, top_similarity, sources
  • grade, regrade: confidence, kind
  • rewrite: queries, keywords
  • hybrid_retrieve: n_hits, sources
  • answer: n_citations
  • escalate: category, product_area, priority
  • ticket: ticket_id, url, queue, eta_hours

A repeated node replaces its entry

RunRecorder.next_seq(stage) returns the last entry’s seq when the same node runs again straight after itself. Today that only happens when a ticket is retried after a failed filing. Replacing the entry keeps the trail to one ticket step and keeps the idempotency key {run_id}:{stage_seq} stable across the retry.

A run gains a step after it finishes. The turn ends with the graph paused in ticket, and the run is marked completed. If the user confirms, confirm_ticket() rebuilds a RunRecorder from the row, resumes the graph, and the ticket node appends its step. A completed run with a pending offer is a normal resting state, not an interrupted one.


Reloading a conversation

The assistant Message row carries a run_id. Steps live in runs, not on the message, so replaying a conversation joins back through that column to show the trail again. That join is why the trail survives a page reload rather than existing only for the life of one SSE stream.


What crashing proves today

CRASH_AFTER=<stage> raises GraphCrash right after the named node’s step is streamed:

async for event, data in graph.astream(initial, thread, context=deps,
                                       stream_mode="custom", durability="sync"):
    yield event, data
    if event == "step":
        _maybe_crash(data["stage"])
  • The stream consumer raises it, never a node. Nodes run as asyncio tasks, and a SystemExit raised inside a task is fatal to the event loop rather than to the run.
  • A named injection point, not kill -9. The turn still dies with uncommitted work and an open SSE connection. Only the timing is chosen, which makes it assertable in a test.
  • CRASH_AFTER=grade leaves retrieve and grade on the trail, with the reasoning and confidence intact, and the run at status running.
  • The checkpoint holds retrieve, not grade. The step is streamed from inside the grade node, before it returns, so that node’s output was never checkpointed.

Resume isn’t built. The pieces exist: graph.astream(None, thread) continues from the last checkpoint and re-runs the node that was cut off, and next_seq() would keep its step from duplicating. What’s missing is the endpoint that checks the run and calls it, and a Resume control in the UI. It is a known gap in D10, cut from the first draft.