Skip to content

fix: reduce checkpointer calls lg events - #2063

Merged
ranst91 merged 5 commits into
mainfrom
fix/reduce-checkpointer-calls-lg-events
Jul 8, 2025
Merged

ranst91 merged 5 commits into
mainfrom
fix/reduce-checkpointer-calls-lg-events

Conversation

@ranst91

@ranst91 ranst91 commented Jun 27, 2025 •

Copy link
Copy Markdown
Contributor

Today, we are querying the checkpointer for the latest state on every event. This is too many calls.
This PR introduces a significant reduction of these calls

Summary by CodeRabbit

  • Refactor
    • Improved internal state handling and caching to optimize performance and synchronization during event streaming.
  • Chores
    • Updated SDK version to 0.1.54-alpha.3.

@vercel

vercel Bot commented Jun 27, 2025 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
copilotkit-feature-viewer ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 8, 2025 11:58am
demo-viewer ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 8, 2025 11:58am
docs ❌ Failed (Inspect) Jul 8, 2025 11:58am
examples-coagents-ai-travel-app ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 8, 2025 11:58am
examples-coagents-research-canvas-ui ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 8, 2025 11:58am
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
examples-coagents-ai-researcher-ui ⬜️ Ignored (Inspect) Visit Preview Jul 8, 2025 11:58am

@coderabbitai

coderabbitai Bot commented Jun 27, 2025 •

Copy link
Copy Markdown
Contributor
## Walkthrough

The `_stream_events` method in `langgraph_agent.py` was modified to maintain a local mutable dictionary, `current_graph_state`, which tracks the agent's state throughout event streaming. This approach reduces redundant asynchronous state fetches by updating the local state with event outputs and using it as the authoritative state during processing. Additionally, thread-specific state caching and method signature updates optimize state handling and synchronization.

## Changes

| File(s)                                 | Change Summary                                                                                     |
|----------------------------------------|--------------------------------------------------------------------------------------------------|
| sdk-python/copilotkit/langgraph_agent.py | Added `thread_state` cache; updated `prepare_stream` to accept explicit `agent_state`; maintained local mutable `current_graph_state` updated during streaming; modified `_stream_events` to use cached and updated state instead of repeated async fetches; changed `prepare_regenerate_stream` and `get_checkpoint_before_message` signatures to use `thread_id` explicitly. |
| sdk-python/pyproject.toml               | Updated `copilotkit` SDK version from `0.1.53` to `0.1.54-alpha.3`.                               |

## Sequence Diagram(s)

```mermaid
sequenceDiagram
    participant Client
    participant LangGraphAgent
    participant EventStream

    Client->>LangGraphAgent: Start _stream_events(initial_state)
    LangGraphAgent->>LangGraphAgent: Initialize current_graph_state from agent_state
    loop For each event in EventStream
        EventStream-->>LangGraphAgent: Send event
        alt event.type == "on_chain_end" and event.output is dict
            LangGraphAgent->>LangGraphAgent: Update current_graph_state with event.output
        end
        alt Intermediate state emitted
            LangGraphAgent->>LangGraphAgent: Use emitted intermediate state as updated_state
        else
            LangGraphAgent->>LangGraphAgent: Use current_graph_state as updated_state
        end
        LangGraphAgent->>Client: Emit event with updated_state
        LangGraphAgent->>LangGraphAgent: Update current_graph_state with updated_state
    end

Suggested reviewers

  • mme
  • suhasdeshpande

<!-- walkthrough_end -->


---

<details>
<summary>📜 Recent review details</summary>

**Configuration used: .coderabbit.yaml**
**Review profile: CHILL**
**Plan: Pro**


<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 5c9846754e56c72bdb636cbe03913a1513ac3917 and 99ff7907b9e6fe3c344f5dca0625c39201b23329.

</details>

<details>
<summary>📒 Files selected for processing (2)</summary>

* `sdk-python/copilotkit/langgraph_agent.py` (11 hunks)
* `sdk-python/pyproject.toml` (1 hunks)

</details>

<details>
<summary>🚧 Files skipped from review as they are similar to previous changes (2)</summary>

* sdk-python/pyproject.toml
* sdk-python/copilotkit/langgraph_agent.py

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (11)</summary>

* GitHub Check: Build Images (coagents-qa-native, ui)
* GitHub Check: Build Images (next-openai, next-openai)
* GitHub Check: Build Images (coagents-research-canvas, agent, python, local-deps)
* GitHub Check: Build Images (coagents-qa-text, agent, python, local-deps)
* GitHub Check: Build Images (coagents-qa-text, ui)
* GitHub Check: Build Images (coagents-routing, ui)
* GitHub Check: Build Images (coagents-qa-native, agent, python, local-deps)
* GitHub Check: Build Images (coagents-research-canvas, ui)
* GitHub Check: Build Images (coagents-routing, agent, python, local-deps)
* GitHub Check: Test (18.x)
* GitHub Check: Test (20.x)

</details>

</details>
<!-- internal state start -->


<!-- DwQgtGAEAqAWCWBnSTIEMB26CuAXA9mAOYCmGJATmriQCaQDG+Ats2bgFyQAOFk+AIwBWJBrngA3EsgEBPRvlqU0AgfFwA6NPEgQAfACgjoCEYDEZyAAUASpETZWaCrKNwSPbABsvkCiQBHbGlcSHFcLzpIACIAM3gADy5/WmwGDwZYUQBrbnx4DBo+BjQfZC8iSBIpQsRoyAB3NGQHAWZ1Gno5MKzIbERKP0xEXABOAEZ0ZG5vX38gkMgMRwFBgCYABgA2AGZ+LFxegGF8bngvfFwAaXU/EjzEdXwXDRhe5m0sJAcPNFpafyIAb0Ao9VC2FDIQ4eEgJdJAyQeZbMVZ8fCxRilLzID5KML4HoZLIMXL5QqDWLPO64CjwaoFSrQyBeaiLEas/ZVKQuLnsV7uRjYCj+QooZjcSJsQrUeD4LALWnSQmMYmkgpFfEE2LzYKFLyyAA0zJIfwZ+JQ5Fi8QYdIwDFk/IQyAh6ooijSSsymFIUNg1Hs8CIGHg1swEXkKQ9yuRqP4GOhA0xZSNp3E7QAXmambx8PDkOjIH6MLQvGbquxEI6PER8KVIeb4OK3VIeJRKRQPnaPN12sGM2bI8Ww/ZcByFXSoQSmZkcnl1ZQq54fHcFiNMVhVncJHSGlFQUpR+d0KEmQBVGwAGS4sFwuG4iA4AHpH0R1LBsAINExmI+TmcLtc6i/qc5yXDcuCPjMPiPpsuwaEY+jGOAUBkPQBZoHghCkOQVCdAorDsFwvD8MIojiFIMjyEwShUKo6haDoiEmFAcCoKgmA4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642gYInYFw1YNIuInYoA8YHYR6HYCYAIj4lI7Iq0AI0YBogQcYrYPGYonYfo2IIA3wtAbYfwhgWkzYcotYeIxw9YjYlI/idQEwsw7cCw2gaJJI+SIAA -->

<!-- internal state end -->
<!-- finishing_touch_checkbox_start -->

<details open="true">
<summary>✨ Finishing Touches</summary>

- [ ] <!-- {"checkboxId": "7962f53c-55bc-4827-bfbf-6a18da830691"} --> 📝 Generate Docstrings

</details>

<!-- finishing_touch_checkbox_end -->
<!-- tips_start -->

---

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.

<details>
<summary>❤️ Share</summary>

- [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai)
- [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai)
- [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai)
- [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)

</details>

<details>
<summary>🪧 Tips</summary>

### Chat

There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=CopilotKit/CopilotKit&utm_content=2063):

> ‼️ **IMPORTANT**
> Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.
- Files and specific lines of code (under the "Files changed" tab): Tag `@coderabbitai` in a new review comment at the desired location with your query. Examples:
  - `@coderabbitai explain this code block.`
  -	`@coderabbitai modularize this function.`
- PR comments: Tag `@coderabbitai` in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
  - `@coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.`
  - `@coderabbitai read src/utils.ts and explain its main purpose.`
  - `@coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.`
  - `@coderabbitai help me debug CodeRabbit configuration file.`

### Support

Need help? Create a ticket on our [support page](https://www.coderabbit.ai/contact-us/support) for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

### CodeRabbit Commands (Invoked using PR comments)

- `@coderabbitai pause` to pause the reviews on a PR.
- `@coderabbitai resume` to resume the paused reviews.
- `@coderabbitai review` to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
- `@coderabbitai full review` to do a full review from scratch and review all the files again.
- `@coderabbitai summary` to regenerate the summary of the PR.
- `@coderabbitai generate docstrings` to [generate docstrings](https://docs.coderabbit.ai/finishing-touches/docstrings) for this PR.
- `@coderabbitai generate sequence diagram` to generate a sequence diagram of the changes in this PR.
- `@coderabbitai resolve` resolve all the CodeRabbit review comments.
- `@coderabbitai configuration` to show the current CodeRabbit configuration for the repository.
- `@coderabbitai help` to get help.

### Other keywords and placeholders

- Add `@coderabbitai ignore` anywhere in the PR description to prevent this PR from being reviewed.
- Add `@coderabbitai summary` to generate the high-level summary at a specific location in the PR description.
- Add `@coderabbitai` anywhere in the PR title to generate the title automatically.

### Documentation and Community

- Visit our [Documentation](https://docs.coderabbit.ai) for detailed information on how to use CodeRabbit.
- Join our [Discord Community](http://discord.gg/coderabbit) to get help, request features, and share feedback.
- Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.

</details>

<!-- tips_end -->

@ranst91
ranst91 force-pushed the fix/reduce-checkpointer-calls-lg-events branch from d8f31d5 to e035299 Compare June 27, 2025 11:08
@ranst91
ranst91 force-pushed the fix/reduce-checkpointer-calls-lg-events branch from e035299 to 69c9eee Compare July 1, 2025 08:37
@ranst91
ranst91 force-pushed the fix/reduce-checkpointer-calls-lg-events branch from 48b8478 to 29dda16 Compare July 1, 2025 11:29

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
sdk-python/copilotkit/langgraph_agent.py (1)

270-272: Consider removing explicit None assignments.

The explicit assignment of None values for "stream", "state", and "config" keys is redundant since the dictionary could simply omit these keys when they're not applicable.

-                "stream": None,
-                "state": None,
-                "config": None,
+                # stream, state, and config are omitted when interrupts are active without resume input
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f8f9592 and 5c98467.

📒 Files selected for processing (2)
  • sdk-python/copilotkit/langgraph_agent.py (11 hunks)
  • sdk-python/pyproject.toml (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • sdk-python/pyproject.toml
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Build Images (coagents-qa-native, ui)
  • GitHub Check: Build Images (next-openai, next-openai)
  • GitHub Check: Build Images (coagents-qa-native, agent, python, local-deps)
  • GitHub Check: Build Images (coagents-qa-text, ui)
  • GitHub Check: Build Images (coagents-routing, agent, python, local-deps)
  • GitHub Check: Build Images (coagents-qa-text, agent, python, local-deps)
  • GitHub Check: Build Images (coagents-routing, ui)
  • GitHub Check: Build Images (coagents-research-canvas, agent, python, local-deps)
  • GitHub Check: Build Images (coagents-research-canvas, ui)
  • GitHub Check: Test (18.x)
  • GitHub Check: Test (20.x)
🔇 Additional comments (15)
sdk-python/copilotkit/langgraph_agent.py (15)

168-168: LGTM: Thread state caching initialization.

The addition of self.thread_state = {} provides the foundation for caching thread-specific states, which directly supports the PR objective of reducing checkpointer calls.


223-224: Effective local state initialization from agent state.

The initialization of current_graph_state from agent_state.values and setting state_input["messages"] provides a solid foundation for local state tracking, eliminating the need for repeated checkpointer calls during event processing.


227-227: Correct parameter usage for merge_state function.

Using state_input instead of the previous state parameter aligns with the new method signature and maintains consistency in state merging logic.


232-232: Proper local state synchronization.

The current_graph_state.update(state) ensures the local state dictionary is kept in sync with the merged state, which is crucial for the optimization strategy.


278-278: Correct return of local state for optimization.

Returning current_graph_state instead of the merged state ensures the caller receives the locally maintained state, supporting the optimization goals.


290-291: Improved parameter extraction and method call.

The explicit extraction of thread_id and passing it directly to get_checkpoint_before_message improves clarity and aligns with the updated method signature.


338-338: Strategic state fetch positioning.

Moving the agent_state fetch before prepare_stream and passing it explicitly eliminates redundant state fetches within the method, directly addressing the PR objective.


340-341: Clean separation of state parameters.

The explicit passing of state_input and agent_state as separate parameters improves method interface clarity and supports the optimization strategy.


369-369: Proper local state assignment.

Assigning current_graph_state from the prepared stream response's "state" establishes the local state tracking mechanism that's central to the optimization.


403-408: Excellent optimization: Local state updates from events.

This is a key optimization that directly addresses the PR objective. By updating current_graph_state with output from "on_chain_end" events, the code avoids expensive checkpointer calls while maintaining state consistency.

The condition checks are appropriate to ensure only valid output dictionaries are used to update the state.


451-451: Core optimization: Use local state instead of checkpointer.

This change represents the heart of the optimization - using current_graph_state instead of fetching state from the checkpointer. The fallback to manually_emitted_state when present is correct logic.


475-475: Maintain local state consistency.

The current_graph_state.update(updated_state) ensures the local state dictionary remains synchronized with state changes, which is essential for the optimization to work correctly throughout the event streaming process.


697-697: Improved method signature with direct thread_id parameter.

The method signature change from accepting a config object to directly accepting thread_id is cleaner and more explicit about the required parameter, improving code clarity.


213-214: prepare_stream Signature Verified Across Codebase

Confirmed via ripgrep that the only definition and invocation of prepare_stream reside in sdk-python/copilotkit/langgraph_agent.py, and both pass the new state_input and agent_state parameters. No other references exist, so this change poses no breaking impact.


616-619: Address potential race in thread state caching

The current implementation in sdk-python/copilotkit/langgraph_agent.py correctly caches per-thread_id state to avoid redundant fetches, but if get_state is invoked concurrently for the same thread_id, both calls may see a missing entry and trigger duplicate await self.graph.aget_state(config) calls. While this won’t corrupt the dict, it does waste resources and could surface unexpected behavior under true multi-threaded or highly concurrent async loads.

To harden this:

  • Introduce an asyncio.Lock (or similar) keyed by thread_id around the “get-or-set” block.
  • Ensure only one fetch populates self.thread_state[thread_id], with other calls awaiting its completion.

Location:
• File: sdk-python/copilotkit/langgraph_agent.py
• Lines: ~616–619

@github-actions

github-actions Bot commented Jul 2, 2025 •

Copy link
Copy Markdown
Contributor

Preview environments destroyed for this pull request.

@github-actions

github-actions Bot commented Jul 2, 2025 •

Copy link
Copy Markdown
Contributor

Test Results

Status: ✅ Passed (View Run)

Commit: e93dc17

Duration: 225.0s

Total Tests: 20

Pass Rate: 100.0%

Failed Tests: 0

🔍 Detailed Results

coagents-research-canvas

CoAgents Research Canvas (UI) - Local Depenencies

Model Browser Status Video
OpenAI chromium ✅ PASSED -
Anthropic chromium ✅ PASSED -
CrewAI chromium ✅ PASSED -

coagents-qa-native

CoAgents QA Native (UI) - Local

Model Browser Status Video
OpenAI chromium ✅ PASSED -
Anthropic chromium ✅ PASSED -

coagents-qa-text

CoAgents QA Text (UI) - Local

Model Browser Status Video
OpenAI chromium ✅ PASSED -
Anthropic chromium ✅ PASSED -
OpenAI (LGC Python) chromium ✅ PASSED -
Anthropic (LGC Python) chromium ✅ PASSED -
OpenAI (LGC JS) chromium ✅ PASSED -
Anthropic (LGC JS) chromium ✅ PASSED -

coagents-routing

CoAgents Routing (UI) - Local

Model Browser Status Video
OpenAI chromium ✅ PASSED -
Anthropic chromium ✅ PASSED -

next-openai

Next OpenAI - Self Hosted

Model Browser Status Video
OpenAI chromium ✅ PASSED -
Anthropic chromium ✅ PASSED -
Google Generative AI chromium ✅ PASSED -
LangChain (OpenAI) chromium ✅ PASSED -
LangChain (Anthropic) chromium ✅ PASSED -
LangChain (Gemini) chromium ✅ PASSED -
Groq chromium ✅ PASSED -

@ranst91
ranst91 force-pushed the fix/reduce-checkpointer-calls-lg-events branch from 5c98467 to 99ff790 Compare July 8, 2025 11:53
@changesets-bot-copilotkit

Copy link
Copy Markdown

⏭️ Changeset Not Required

Latest commit: 99ff790

No changes in this PR affected the @copilitkit/* packages. Merging this PR will not cause a version bump for any packages.

Changeset is not required for this PR.

@ranst91
ranst91 merged commit cf90f85 into main Jul 8, 2025
@ranst91
ranst91 deleted the fix/reduce-checkpointer-calls-lg-events branch July 8, 2025 12:39
bobbyo pushed a commit to bobbyo/CopilotKit that referenced this pull request Oct 10, 2025
…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]>

This branch had an error being deployed

1 failed and 4 active deployments
Preview – demo-viewer — 99ff7907 Deployed Jul 8, 2025 by vercel[bot]
Preview – docs — 99ff7907 Deployed Jul 8, 2025 by vercel[bot]
Preview – copilotkit-feature-viewer — 99ff7907 Deployed Jul 8, 2025 by vercel[bot]
Preview – examples-coagents-research-canvas-ui — 99ff7907 Deployed Jul 8, 2025 by vercel[bot]
Preview – examples-coagents-ai-travel-app — 99ff7907 Deployed Jul 8, 2025 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant