adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

Session Fork/Clone API for Conversation Branching

Open junseon-yoo opened this issue 11 months ago • 5 comments

Is your feature request related to a problem? Please describe.

When building applications that need to explore multiple conversation paths from a single point, there's no way to create a copy of an existing session without modifying the original.

The current rewind_async() API modifies the original session's state and artifacts, making it impossible to:

  • Preserve the original conversation while exploring alternative paths
  • Create "what-if" branches from a conversation midpoint
  • Allow users to fork a conversation and continue in different directions

Example scenario: A user is at turn 5 of a conversation and wants to try a different approach from turn 3, but also keep the original turn 3→5 history intact. Currently this is not possible.

Describe the solution you'd like

Add a fork_session() or clone_session() API that creates a new independent session by copying events, state, and artifact references up to a specified invocation point.

# Option A: In SessionService
new_session = await session_service.fork_session(
    app_name=app_name,
    user_id=user_id,
    source_session_id=original_session.id,
    fork_before_invocation_id="inv_3",  # Fork point
)

# Option B: In Runner (similar to rewind_async)
new_session = await runner.fork_async(
    user_id=user_id,
    session_id=session_id,
    fork_before_invocation_id="inv_3",
)

The original session remains completely unchanged.

Describe alternatives you've considered

  1. Rewind then copy: Doesn't work because rewind_async() modifies the original session's state and artifacts before any copy could be made.

  2. Manual event copying: Requires manually iterating events, recomputing state deltas, and handling artifact references. Error-prone and not officially supported.

  3. External backup before rewind: Outside ADK's scope, doesn't integrate with artifact versioning, and requires users to implement their own session serialization.

Additional context

  • Related existing feature: rewind_async() in runners.py:509-647 - similar pattern could be followed
  • Use cases: conversation branching UI, A/B testing agent responses, debugging/development snapshots
  • I'm willing to contribute this feature if the design is approved

junseon-yoo avatar Dec 24 '25 07:12 junseon-yoo

This issue has been automatically marked as stale because it has not had recent activity for 7 days after a maintainer requested clarification. It will be closed if no further activity occurs within 7 days.

adk-bot avatar Jan 21 '26 06:01 adk-bot

@junseon-yoo Thank you for bringing this to our attention. The request is under review, and I’ll keep you updated if any additional information is required. We appreciate your patience. thanks.

klateefa avatar Feb 11 '26 07:02 klateefa

@wuliang229 I'd like to contribute this if it's still wanted. Here's a design to check before I build anything.

API (on Runner, next to rewind_async, since copying artifacts needs the artifact service):

new_session = await runner.fork_async(
    user_id="u",
    session_id="s1",
    fork_before_invocation_id="e-3",  # None = clone the whole session
    new_session_id=None,              # None = generated
)

The source session is not modified.

Semantics

  • Events: the source's events before the first event of fork_before_invocation_id (all events if None) are copied in order with new event ids. invocation_id, author, branch, content and actions are kept, so rewinding or forking the new session works with the same invocation ids.
  • State: the new session starts with the source's session-scoped state at the fork point. app: and user: state are shared already, and temp: isn't persisted.
  • Artifacts: for each session-scoped artifact referenced before the fork point, versions 0..N are copied to the new session in order. InMemory, GCS and File all number versions from 0, so the version numbers match and the copied events' artifact_delta stays valid. user: artifacts are shared and not copied.
  • Errors: InvocationNotFoundError for an unknown fork point, as in rewind_async. Artifacts are copied before events. If something fails, the partial new session is deleted (best effort) and the error is raised.
  • Earlier rewinds, compaction and HITL: rewind markers and compaction events are copied with the invocations they refer to, so _apply_rewinds gives the same live history. Fork points are invocation boundaries, so a paused invocation is either fully included or excluded, and a full clone can be resumed like the original.

Implementation: a new sessions/_fork_utils.py (about 100 lines) that shares the state-at-index replay with _rewind_utils, plus a thin Runner.fork_async. No session service backend changes are needed: it only uses get_session, create_session, append_event and delete_session. Tests would cover a mid-session fork, a full clone, the source staying unchanged, artifact versions, user: artifacts and errors, with the core case run on InMemory, Sqlite and Database through the session conformance helpers. A /fork endpoint next to the existing /rewind one in the API server could follow separately.

Questions

  1. Is Runner.fork_async the right home, or would you prefer a BaseSessionService hook so a backend can fork in one transaction?
  2. Should a fork copy events the source had already rewound away (an identical copy), or only the live history?
  3. State passed to create_session that changed after the fork point can't be recovered, because no event records its earlier value. This is the same cause as #4839. Is it OK to document that limitation, or would you rather #4839 land first? A full clone isn't affected.

If this direction works for you, I'll open a PR.

AkshayShah03 avatar Oct 26 '26 00:10 AkshayShah03

Hi @wuliang229, a quick follow-up on the design above. Is session forking still something you'd like from outside contributors, and does Runner.fork_async look like the right direction? If you'd rather handle it internally, or it isn't planned right now, that's completely fine too. I just want to avoid building something that doesn't fit.

AkshayShah03 avatar Nov 02 '26 22:11 AkshayShah03

Adding a use case that the fork_async design above fits well, and two small requests.

Use case: speculative replies in a voice agent. We start generating the agent's reply while the user may still be talking, using the transcript so far as a guess at their turn. The reply runs on a fork of the live session, so the live history only changes if the guess was right. When the turn is final:

  • if the final text matches the guess and the live session hasn't changed since the fork, we append the fork's new events to the live session and delete the fork;
  • otherwise we delete the fork and start again.

We do this by hand today with get, create and one append per copied event (in adk-go, but the shape is the same in Python). A built-in fork would replace most of it.

What this needs from fork_async:

  1. A whole-session clone. fork_before_invocation_id=None already covers it.
  2. Cheap enough to run on every user turn. Copying event by event is fine in memory, but it's one write per event on database-backed services. Could Runner.fork_async call a BaseSessionService method that has a default event-by-event implementation? Then DatabaseSessionService can copy the rows in one statement, and Option A from the original issue comes for free.
  3. A way to tell later whether the source moved on. If the new session records the source session id and the id of the last event it copied (in its state, or in a returned value), a caller can apply the fork's new events back only as a fast-forward. Merging back can stay out of scope for the first PR.

Happy to test or review a PR for this.

lebeg avatar Nov 26 '26 14:11 lebeg