Repository navigation
Simplify and harden session lifecycle with an explicit state machine #1691
Description
Activity
Yea I actually like this, love to hear "state machine". For V2 of the Python SDK something like this could be really cool, but we'll have to pause on what exactly it'll look like until the upcoming transport changes have been a bit more finalised.
Some relevant links for those discussions:
Reacted by Diogo Santos- addedenhancementRequest for a new feature that's not currently supportedRequest for a new feature that's not currently supportedv2Affects the v2 line (2.x on main)Affects the v2 line (2.x on main)
on Dec 3, 2025 - addedP2Moderate issues affecting some users, edge cases, potentially valuable featureModerate issues affecting some users, edge cases, potentially valuable feature
on Dec 9, 2025 - added 5 commits that reference this issue
on Feb 19, 2026 Update: I've opened PR #2099 implementing Phase 1 of this proposal — expanding the
InitializationStateenum withStateless,Closing, andClosedstates, plus a centralized_VALID_TRANSITIONStable and_transition_state()validator.@maxisbey noted that the final shape should wait for the transport spec discussions to settle (linked in the comment above). The PR is designed as a non-breaking incremental step that doesn't lock in any specific transport model — additional states can be added to the transition table later.
The PR applies cleanly to current
mainand includes 20 tests. Happy to iterate based on feedback.- added 4 commits that reference this issue
on Apr 9, 2026
Description
Summary
Server and client sessions use an internal initialization state machine combined with various flags and manual
AsyncExitStackmanagement. Stateless mode complicates this further by setting an "Initialized" state early as a workaround.This makes the lifecycle hard to reason about and contributes to subtle bugs (e.g., past issues like #756 in stateless mode).
Problems
Proposal
Introduce an explicit session state machine
Represent distinct states as separate types, for example:
UninitializedSessionNegotiatingSessionActiveSessionClosedSessionStatelessSession(for per-request / ephemeral cases)Each state exposes only the operations that are valid in that state, and transitions return the next state type.
Model stateless mode explicitly
StatelessSessiontype with a simpler lifecycle.Centralize resource cleanup
AsyncExitStack.Why this matters
Acceptance criteria
References
No response