Repository navigation
feat(core)!: save sessions automatically, fork and truncate them - #115
Merged
Merged
Conversation
gopaljigaur
commented
Oct 15, 2026
gopaljigaur
left a comment
Owner
Author
There was a problem hiding this comment.
Seven findings, inline. Four are bugs in the save path, reproduced on the PR head; the rest are smaller.
FileSessionStore.loadsplits withsplitlines, so a message containing\u2028,\u2029or\x85makes the session unloadable.- 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 withasyncio.shield. - After a failed save, the retry is an
add_messagesfrom 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 fullsave. - An end save error replaces the run's own error, and on a run that succeeded it reports an error after
on_run_endfired. - 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. - Minor: LangGraph takes
durabilityper call, not at compile; the Decisions text should say so. - Minor: document one writer per session for the file store.
Checked and fine:
durabilitynames, semantics and default match LangGraph.add_messages(session, messages)matches LangChain'sBaseChatMessageHistory.add_messagesand the OpenAI Agents SDK'sadd_items;truncate(index)is list slicing, more general thanpop_item.- The
<id>.jsonformat break:FileSessionStoreis not in any release (v0.3.0 has nosession.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\rstill leaves complete JSON. - Saves never overlap, and the last one is awaited at the run end. A dropped
astream_eventsgoes throughhandle.cancel()and thefinally, 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.pyfail withcyclops/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.
gopaljigaur
force-pushed
the
feat/session-autosave
branch
from
October 15, 2026 04:25
2c61e04 to
c02a4ad
Compare
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
force-pushed
the
feat/session-autosave
branch
from
October 15, 2026 04:30
c02a4ad to
21512bc
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What changed
Agent(config, session_store=store, durability="async"): every run with a session saves it to the store.durabilitytakes 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 callssavewith 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.InMemorySessionStoreandFileSessionStorekeep each session as its saved JSON followed by one JSON line per addition;loadreplays them,savestarts over with one line. The file store writes<id>.jsonl, splits lines on\nonly (JSON leaves\u2028,\x85and 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)keepsmessages[:index]and raisesValueErrorwhen the cut would leave an assistant message's tool calls without their results.run.pygets 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 beforeon_run_end, so a failed end save fireson_run_errorinstead._SessionSaver.rewritten()tells the saver that messages it already stored were replaced, so its next save is a fullsave. 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
compile(checkpointer=...)anddurabilityper call (invoke,stream). The names and values here are LangGraph's; keepingdurabilitynext to the store avoids a parameter on every run method.AgentConfiglives intypes.pyand can't importSessionStorewithout an import cycle.invoke, and the OpenAI Agents SDK raises session errors out ofRunner.run. A run that otherwise succeeded ends withstop_reason="error"anderrorset to what the store raised, soarunraises 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 fullsave, since a write that failed partway leaves the store unknown."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.Breaking
SessionStorehas a fourth method,add_messages, andFileSessionStorewrites<id>.jsonlinstead 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-filesanduv run mypy cyclopspass.Closes #65