Skip to content

Conversation

@Ujjwal-Bajpayee
Copy link

@Ujjwal-Bajpayee Ujjwal-Bajpayee commented Feb 7, 2026

Closes #

📝 Description

This PR introduces small but impactful improvements to main.py aimed at improving debugging visibility and ensuring proper asyncio task management for the Discord bot background process.

The changes enhance logging clarity and prevent potential issues related to unmanaged background tasks.

🔧 Changes Made

  • Enhanced logging format

    • Added function name and line number to the log output for better traceability.
    • Updated format:
      • Before: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
      • After: '%(asctime)s - %(name)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s'
  • Fixed Discord bot task management

    • Stored a reference to the Discord bot background task instead of creating it anonymously.
    • Assigned a descriptive task name ("discord_bot") for easier identification.
    • Prevents the task from being garbage collected and avoids silent failures.

📷 Screenshots or Visual Changes (if applicable)

N/A — backend-only changes with no visual UI impact.

🤝 Collaboration

Collaborated with: @username (optional)

✅ Checklist

  • I have read the contributing guidelines.
  • I have added tests or verified behavior to ensure the fix works as intended.
  • I have added necessary documentation (if applicable).
  • Any dependent changes have been merged and published in downstream modules.

Summary by CodeRabbit

Release Notes

  • Improvements
    • Enhanced logging to include function names and line numbers for improved debugging and troubleshooting.
    • Improved Discord bot startup reliability and integration through more robust background task management.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 7, 2026

📝 Walkthrough

Walkthrough

The changes introduce a stored reference to the Discord bot background task by adding a discord_task attribute to the DevRAIApplication class. The startup sequence was refactored to load the Discord cog extension within the async startup flow and assign the bot start as a managed background task instead of fire-and-forget. Log formatting was also enhanced to include function names and line numbers.

Changes

Cohort / File(s) Summary
Discord Task Management
backend/main.py
Added discord_task attribute to store reference to Discord bot background task; modified startup sequence to load cog extension inside async flow and manage bot start as named background task; enhanced logging format to include function name and line number.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 A Discord bot now stands with care,
No longer lost in async air,
With references we hold it tight,
Logs now shine with function light! ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: improved logging format and enhanced Discord bot task management with stored references.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

No actionable comments were generated in the recent review. 🎉

🧹 Recent nitpick comments
backend/main.py (2)

56-60: Add exception handling for the background task and cancel it during shutdown.

The task reference is stored (good), but:

  1. If the Discord bot crashes, the exception goes unobserved until GC or shutdown.
  2. stop_background_tasks() never cancels or awaits self.discord_task.

Consider adding a done callback and cleaning up the task on shutdown:

Proposed fix

Add a callback after task creation (after line 60):

             self.discord_task = asyncio.create_task(
                 self.discord_bot.start(settings.discord_bot_token),
                 name="discord_bot"
             )
+            self.discord_task.add_done_callback(self._on_discord_task_done)

Add the callback method to the class:

def _on_discord_task_done(self, task: asyncio.Task):
    if task.cancelled():
        logger.info("Discord bot task was cancelled.")
    elif exc := task.exception():
        logger.error("Discord bot task failed with exception: %s", exc, exc_info=exc)

And in stop_background_tasks, cancel/await the task:

     async def stop_background_tasks(self):
         """Stops all background tasks and connections gracefully."""
         logger.info("Stopping background tasks and closing connections...")
         try:
             if not self.discord_bot.is_closed():
                 await self.discord_bot.close()
                 logger.info("Discord bot has been closed.")
         except Exception as e:
             logger.error(f"Error closing Discord bot: {e}", exc_info=True)
+        if self.discord_task and not self.discord_task.done():
+            self.discord_task.cancel()
+            try:
+                await self.discord_task
+            except asyncio.CancelledError:
+                logger.info("Discord bot task cancelled.")
         try:
             await self.queue_manager.stop()

51-54: Cog load failure is handled gracefully, but consider whether startup should continue.

If the cog fails to load, the bot starts without its commands — this may be acceptable for resilience, but could silently degrade functionality. The error log is appropriate; just ensure this is the intended behavior.


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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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.

1 participant