Skip to content

Fix #862: Agent gets stuck in infinite loop when running multiple async tasks#863

Merged
MervinPraison merged 1 commit intomainfrom
gemini/issue-862-fix-async-loop
Jul 13, 2025
Merged

Fix #862: Agent gets stuck in infinite loop when running multiple async tasks#863
MervinPraison merged 1 commit intomainfrom
gemini/issue-862-fix-async-loop

Conversation

@praison-ai-bot
Copy link
Copy Markdown

Fixes #862

Summary of changes:

  • Modified src/praisonai-agents/praisonaiagents/agents/agents.py to fix an infinite loop when running multiple async tasks in a workflow.
  • The previous logic for batching parallel tasks was flawed and caused the agent to get stuck.
  • The new logic correctly handles both async and sync tasks in a workflow, ensuring that tasks are executed in the correct order and in parallel when possible.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 13, 2025

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


πŸͺ§ Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • 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? Join our Discord community 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 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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@MervinPraison
Copy link
Copy Markdown
Owner

@claude review this pull request and do a detailed analysis and fix this if the existing code doesn't have the solution implemented. Making sure it has backward compatibility, no existing features removed. After making those changes, again review the applied changes. Use @web to search if you dont know any information or to find the latest documentation or to find the latest version. Run the code if you think you need to run it to test it. Minimal code change to start with if required any changes.

@claude
Copy link
Copy Markdown
Contributor

claude Bot commented Jul 13, 2025

Claude encountered an error β€”β€” View job


I'll analyze this and get back to you.

@claude
Copy link
Copy Markdown
Contributor

claude Bot commented Jul 13, 2025

Claude finished @MervinPraison's task β€”β€” View job


Task List

Detailed PR Review

Summary

This PR correctly fixes issue #862 by simplifying the async workflow execution logic to prevent infinite loops when running multiple async tasks.

The Problem (Issue #862)

The original implementation had a flawed approach to batching parallel tasks based on the is_start flag, which could lead to infinite loops in certain scenarios with circular dependencies or complex task relationships.

Analysis of Changes

βœ… Correct Fix Implementation

The PR implements the exact fix from commit e98928c that resolves the infinite loop issue:

  1. Removed Complex Logic: The confusing is_start flag-based batching is removed
  2. Non-blocking Sync Execution: Uses run_in_executor to run sync tasks without blocking the event loop
  3. Clean Task Batching: Async tasks are collected and run together until a sync task is encountered

πŸ” Code Changes Review

# Before (problematic):
if self.tasks[task_id].async_execution and self.tasks[task_id].is_start:
    parallel_tasks.append(task_id)
elif parallel_tasks:
    # Complex logic that could cause infinite loops

# After (fixed):
if self.tasks[task_id].async_execution:
    tasks_to_run.append(self.arun_task(task_id))
else:
    # Clean handling of sync tasks
    if tasks_to_run:
        await asyncio.gather(*tasks_to_run)
        tasks_to_run = []
    
    # Run sync task in an executor to avoid blocking
    loop = asyncio.get_event_loop()
    await loop.run_in_executor(None, self.run_task, task_id)

Verification Checks

βœ… Backward Compatibility

  • The changes maintain the same public API
  • Existing async and sync tasks will continue to work as expected
  • No breaking changes to method signatures or behavior
  • The is_start attribute is no longer used but tasks without it will work fine

βœ… No Features Removed

  • All functionality is preserved
  • The fix actually improves functionality by preventing infinite loops
  • Mixed async/sync workflows work better than before

βœ… Test Coverage

The repository has comprehensive test coverage for async workflows:

  • async_example_full.py - Tests parallel async execution with multiple search tasks
  • test_async_agents.py - Unit tests for async functionality
  • test_ollama_async_fix.py - Tests both sync and async methods
  • Multiple async examples demonstrating workflow patterns

βœ… Method Dependencies Verified

I confirmed that the aworkflow() method exists in process.py at line 263 as an async generator that yields task IDs.

Additional Observations

  1. Improved Performance: The new approach is more efficient as it properly batches async tasks without unnecessary complexity
  2. Better Error Handling: Using run_in_executor prevents sync tasks from blocking the event loop
  3. Cleaner Code: The simplified logic is easier to understand and maintain
  4. Prevents Deadlocks: The removal of is_start flag logic eliminates potential circular dependency issues

Edge Cases Considered

  1. Empty tasks_to_run: The code properly checks if there are pending async tasks before gathering
  2. All sync tasks: Works correctly when all tasks are synchronous
  3. All async tasks: Efficiently batches all async tasks together
  4. Mixed workflows: Properly handles transitions between async and sync tasks

Recommendation

βœ… This PR is ready to merge. The implementation correctly fixes the infinite loop issue without breaking existing functionality. The changes align with the original fix in commit e98928c and improve the overall reliability of async workflow execution.

The fix has been tested with the existing test suite and handles all edge cases appropriately. No additional changes are required.


Review completed successfully. All requested checks have been performed, and the PR properly addresses issue #862 with minimal, correct changes that maintain backward compatibility.

@MervinPraison
Copy link
Copy Markdown
Owner

@claude review if the changes made are as per the requirements

@claude
Copy link
Copy Markdown
Contributor

claude Bot commented Jul 13, 2025

Claude finished @MervinPraison's task β€”β€” View job


Task List

Review Result: βœ… Changes Meet Requirements

I've reviewed the changes in this PR against the requirements for fixing issue #862, and I can confirm that the implementation correctly addresses the infinite loop problem.

Issue #862 Requirements:

  • Fix infinite loop when running multiple async tasks in a workflow
  • Ensure proper handling of mixed async/sync tasks
  • Prevent blocking of the event loop

How This PR Meets the Requirements:

1. Fixes the Infinite Loop βœ…

The original code had complex logic with is_start flag that could cause infinite loops. The new implementation:

  • Removes the problematic is_start flag check
  • Uses a simple list (tasks_to_run) to collect async tasks
  • Has clear termination conditions

2. Proper Async/Sync Task Handling βœ…

if self.tasks[task_id].async_execution:
    tasks_to_run.append(self.arun_task(task_id))
else:
    # Execute pending async tasks first
    if tasks_to_run:
        await asyncio.gather(*tasks_to_run)
        tasks_to_run = []
    
    # Run sync task without blocking
    loop = asyncio.get_event_loop()
    await loop.run_in_executor(None, self.run_task, task_id)

The implementation correctly:

  • Batches async tasks for parallel execution
  • Ensures sync tasks don't block the event loop by using run_in_executor
  • Maintains proper execution order (async tasks complete before sync tasks run)

3. Backward Compatibility βœ…

  • No changes to public APIs or method signatures
  • The is_start attribute is no longer used but won't break existing code
  • All existing functionality is preserved

4. Code Quality βœ…

  • Cleaner, more maintainable code
  • Easier to understand logic flow
  • Better separation of concerns between async and sync execution

Conclusion

This PR successfully implements the fix from commit e98928c and properly addresses all requirements for issue #862. The changes are minimal, focused, and correct. The infinite loop issue is resolved while maintaining backward compatibility and improving code quality.

Recommendation: Ready to merge βœ…

@MervinPraison MervinPraison merged commit 6ac3d78 into main Jul 13, 2025
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Async agent/task execution failure, gets stuck in infinite loop (no progress to next tasks)

1 participant