Skip to content

feat(core)!: save sessions automatically, fork and truncate them - #115

Merged
gopaljigaur merged 2 commits into
mainfrom
feat/session-autosave
Oct 15, 2026
Merged

gopaljigaur merged 2 commits into
mainfrom
feat/session-autosave

Conversation

@gopaljigaur

@gopaljigaur gopaljigaur commented Oct 15, 2026 •

Copy link
Copy Markdown
Owner

What changed

  • Agent(config, session_store=store, durability="async"): every run with a session saves it to the store. durability takes LangGraph's names: "async" (default) saves after each step while the next one runs, "sync" saves after each step before the next starts, "exit" saves once when the run ends. Every mode also saves when the run ends, however it ends (failed and cancelled runs included).
  • SessionStore.add_messages(session, messages): adds messages to a stored session and stores its usage. A run's first save calls save with the whole session (it may have been forked, truncated or edited since the store saw it); every later save in that run passes only the new messages. Nothing copies the whole history per step.
  • InMemorySessionStore and FileSessionStore keep each session as its saved JSON followed by one JSON line per addition; load replays them, save starts over with one line. The file store writes <id>.jsonl, splits lines on \n only (JSON leaves \u2028, \x85 and the like unescaped), and ignores a last line without its newline, which is what a crash during an append leaves. Keep one writer per session; the guides say so.
  • Session.fork() returns a deep copy with a new id. Session.truncate(index) keeps messages[:index] and raises ValueError when the cut would leave an assistant message's tool calls without their results.
  • run.py gets one hook after each step that goes on (saver.step()) and one when the run ends (_end_session, which also takes over adding the run's usage to the session). The end save runs before on_run_end, so a failed end save fires on_run_error instead.
  • _SessionSaver.rewritten() tells the saver that messages it already stored were replaced, so its next save is a full save. The naive tool mode fallback calls it now. Compaction (feat: summarize older messages near the model's input limit #118) needs to call it where it replaces messages; whichever of the two PRs merges second adds that call.

Decisions

  • Store and durability on the Agent, not AgentConfig. LangGraph takes the checkpointer at compile(checkpointer=...) and durability per call (invoke, stream). The names and values here are LangGraph's; keeping durability next to the store avoids a parameter on every run method. AgentConfig lives in types.py and can't import SessionStore without an import cycle.
  • A failed save is an error, not an event. LangGraph raises checkpointer errors out of invoke, and the OpenAI Agents SDK raises session errors out of Runner.run. A run that otherwise succeeded ends with stop_reason="error" and error set to what the store raised, so arun raises it. A run that already failed keeps its own error, and a failed end save is logged at ERROR with the session id. With "async", a step's save error surfaces at the next save. A failed write makes the next save a full save, since a write that failed partway leaves the store unknown.
  • Cancellation. A write in progress when the run is cancelled is shielded: it finishes and counts, so the end save doesn't store its messages twice.
  • Non-blocking saves. In "async" mode the save runs as a task while the next completion runs. What to store is snapshotted when the save is scheduled (a slice of new messages, or a shallow copy of the message list for the first save), so later steps don't leak into it. Saves of one run are serialized.
  • truncate raises instead of moving the cut. Silently keeping fewer messages than asked would surprise a caller who picked a message.

Breaking

SessionStore has a fourth method, add_messages, and FileSessionStore writes <id>.jsonl instead of <id>.json.

Tests

Per-step (sync and async) and per-run autosave, a save running while the next step's completion runs, a failing store in every mode, the full save after a failed one, error precedence for failed and successful runs, a write in progress at cancellation stored once, rewritten(), other line breaks in messages, cancelled runs saved, no saves without a session, a full save again after truncation, fork() ids and independence, truncation including the tool-pair rule, and the file store round trip with additions and a crash-cut line. uv run pytest, uv run pre-commit run --all-files and uv run mypy cyclops pass.

Closes #65

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seven findings, inline. Four are bugs in the save path, reproduced on the PR head; the rest are smaller.

  1. FileSessionStore.load splits with splitlines, so a message containing \u2028, \u2029 or \x85 makes the session unloadable.
  2. Cancelling a run while it waits for a file save stores the last step's messages twice (the thread keeps writing, then end() adds them again). Fix with asyncio.shield.
  3. After a failed save, the retry is an add_messages from the old count: a partial line plus the retry corrupts the file, and a store that committed before raising gets duplicates. The next save after a failure should be a full save.
  4. An end save error replaces the run's own error, and on a run that succeeded it reports an error after on_run_end fired.
  5. Overlap with #118: compaction rewrites history mid run, which the count based append path stores wrong without an error. Proposed hook: a rewritten() method that makes the next save full.
  6. Minor: LangGraph takes durability per call, not at compile; the Decisions text should say so.
  7. Minor: document one writer per session for the file store.

Checked and fine:

  • durability names, semantics and default match LangGraph. add_messages(session, messages) matches LangChain's BaseChatMessageHistory.add_messages and the OpenAI Agents SDK's add_items; truncate(index) is list slicing, more general than pop_item.
  • The <id>.json format break: FileSessionStore is not in any release (v0.3.0 has no session.py), so no reader for the old format is needed.
  • Full saves are atomic (temp file and os.replace); a crash cut last line is skipped; Windows text mode translation is symmetric, and a crash after \r still leaves complete JSON.
  • Saves never overlap, and the last one is awaited at the run end. A dropped astream_events goes through handle.cancel() and the finally, so no save task is left behind. A run failed by its store is freed without the cycle collector. Nothing in the library mutates a message dict after appending it.
  • fork() deep copies once per explicit call; truncate's tool pair rule handles parallel calls and negative indexes, and both keep usage as spent.
  • 15 of the 27 tests in tests/test_sessions.py fail with cyclops/ from main. Gaps are listed in the threads.
  • pytest (468 passed), mypy and pre-commit pass on the head; the branch is behind origin/main, merges cleanly, and the merged tree passes (483 passed, mypy and pre-commit clean). CI is green. The confidentiality grep and the dash check over the title, body, commit and added lines find nothing.

Comment thread cyclops/core/session.py Resolved
Comment thread cyclops/core/session.py Resolved
Comment thread cyclops/core/session.py Resolved
Comment thread cyclops/core/run.py Resolved
Comment thread cyclops/core/session.py Resolved
Comment thread cyclops/core/agent.py Resolved
Comment thread docs/guide/sessions.md Resolved
@gopaljigaur
gopaljigaur force-pushed the feat/session-autosave branch from 2c61e04 to c02a4ad Compare October 15, 2026 04:25
Agent(session_store=..., durability=...) saves every run's session to the
store, after each step or once the run ends, with LangGraph's durability
names: "async" (the default) saves while the next step runs, "sync" before
it, "exit" when the run ends. A run's first save stores the whole session;
later saves pass only the new messages to the store's new add_messages. A
failed save fails the run with the store's error.

Session.fork() copies a session under a new id, and Session.truncate()
keeps the messages before an index, refusing to keep tool calls without
their results.

BREAKING CHANGE: SessionStore has a fourth method, add_messages, and
FileSessionStore keeps each session as <id>.jsonl instead of <id>.json.
…d rewrites

A write in progress when a run is cancelled now finishes and counts, so
the end save doesn't add its messages again. A failed write, and messages
the run replaced, make the next save store the whole session. A run that
already failed keeps its own error and logs a failed end save; a run that
succeeded fails with it, before on_run_end. FileSessionStore splits lines
on newlines only, so messages may hold other line breaks.

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No findings.

@gopaljigaur
gopaljigaur merged commit 3bc53f1 into main Oct 15, 2026
10 checks passed
@gopaljigaur
gopaljigaur deleted the feat/session-autosave branch October 15, 2026 04:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Automatic session saving and forking

1 participant