Skip to content

Shared LLM/Agent objects across conversations inherit stale per-conversation state #3443

Closed

Description

@csmith49

Summary

When the same LLM or Agent object is reused across multiple LocalConversation instances, per-conversation state mutated onto the LLM leaks between conversations. Two values are affected:

Both use the same pattern: mutate the LLM object, skip if already set. The second conversation sees the first's value and keeps it.

Repro

from openhands.sdk.llm import LLM
from openhands.sdk.agent import Agent
from openhands.sdk.conversation import LocalConversation

llm = LLM(model="openai/gpt-4o-mini", api_key="test")
agent = Agent(llm=llm, tools=[])

conv1 = LocalConversation(agent=agent, workspace="/tmp/ws1")
conv1._ensure_agent_ready()

conv2 = LocalConversation(agent=agent, workspace="/tmp/ws2")
conv2._ensure_agent_ready()

# Both fail — conv2 inherited conv1's values
assert agent.llm._prompt_cache_key == str(conv2.id)                          # still conv1.id
assert agent.llm.extra_headers["x-litellm-session-id"] == str(conv2.id)      # still conv1.id

Examples in this repo that reuse LLM objects across conversations:

  • examples/01_standalone_sdk/24_planning_agent_workflow.py — one llm used for planning + execution conversations
  • examples/01_standalone_sdk/31_iterative_refinement.py — one llm reused across refactoring/critique conversations

Practical impact

Low in production — the Cloud/server path (EventService.start()) always deserializes a fresh agent from JSON, so shared references don't occur. The aliasing only affects standalone SDK usage where callers construct one LLM and pass it to multiple LocalConversation instances.

For _prompt_cache_key: the effect is two conversations sharing an OpenAI prefix-cache shard, which is benign (prefix matching is content-based, not key-based).

For x-litellm-session-id: the effect is two conversations routing to the same LiteLLM deployment, which defeats per-conversation probabilistic distribution. Only matters when the LiteLLM proxy has session_affinity enabled with multiple weighted deployments.

Prior art

fork() already handles this — it deep-copies the agent via JSON round-trip to avoid _prompt_cache_key aliasing (see comment at line ~389).

Possible fixes

  1. Defensive copy in __init__ — same JSON round-trip that fork() uses. Each conversation owns its own agent/LLM objects. Simple (~3 lines), fixes both values at once, but changes the contract (callers can no longer mutate the agent externally after creating the conversation).

  2. Always overwrite, remove guards — _pin_prompt_cache_key drops the is None check, _pin_session_affinity_header drops the not in existing check. Each conversation stamps its own ID. Fixes the aliasing but means the last conversation to init "wins" on the shared object — still a race if conversations are concurrent. Also breaks _prompt_cache_key's intentional sub-agent inheritance (sub-agents inherit the parent's key via model_copy; overwriting would shard them separately).

  3. Private field + call-time injection — store the session ID on a private LLM field (_conversation_session_id), inject into extra_headers at call time in select_chat_options(). Keeps extra_headers clean, private field is always overwritten. More plumbing (~15 lines across 2 files) and doesn't fix _prompt_cache_key.


Surfaced by @enyst's review on #3437.

This issue was created by an AI agent (OpenHands) on behalf of @calvinsmith.

Activity

  1. csmith49 commented on May 29, 2026

    @csmith49
    ContributorAuthor

    I know .fork() resolves these aliasing issues by making a deep copy. I'm not sure that's what we'll want to use always: that same fix in the example given would result in the reference to the agent going stale.

    Honestly not sure that matters though, guess it depends on what we expect folks to be doing with the SDK.

  2. enyst commented on May 30, 2026

    @enyst
    Member

    I wonder if this alternative may be better:

    • use the LLMRegistry to store a mapping between an LLM and each(?) of these values
    • not in the LLM itself (or maybe initialized there from the registry, if that makes sense)
    • (maybe) LLM.create_from(llm: LLM) which does the dirty details
    • so that those details are not necessary all over the code that wants a new LLM from an old LLM
    • I wonder if maybe something design like this can be a more self-contained way to replace model_copy but oops actually

    But I could be wrong?

  3. csmith49 commented on May 30, 2026

    @csmith49
    ContributorAuthor

    My mental model has these values living in the conversation itself, then being injected into the LLM right before completion time. The conversation is the thing that actually cares about the prompt cache keys (and the session ID, if you go to a different deployment there goes your prompt cache), and the SDK might benefit from the flexibility of being able to swap/modify agents and LLMs without having to think about these values.

    But I think I'm implicitly optimizing for "conversation stability", and that may not be right. LLM registry would be a decent solution if these values really should be associated with an LLM instead. Do you think that's the case?

  4. added
    bug
    on Jun 1, 2026
  5. all-hands-bot commented on Jun 1, 2026

    @all-hands-bot
    Collaborator

    [Automatic Post]: This issue has been waiting for triage. @xingyaoww @neubig @enyst, could you
    please take a look and add the appropriate priority label when you have a chance?

    This comment was created by an AI agent (OpenHands) on behalf of the user.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions