Skip to content

refactor(treewide): reorder statements to improve speed #953

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

amadaluzia
Copy link
Contributor

@amadaluzia amadaluzia commented Jul 16, 2025

Description

This refactors the tree to optimise the cog loader, the avatar command and the xkcd command with reordered if statements, and storing variables to remove unnecessary function calls. I think this is clean enough at the moment for me to write this as a PR. There will of course still be some unoptimal things I have missed but I cannot seem to find any that wouldn't conflict with #853.

Guidelines

  • My code follows the style guidelines of this project (formatted with Ruff)

  • I have performed a self-review of my own code

  • I have commented my code, particularly in hard-to-understand areas

  • I have made corresponding changes to the documentation if needed

  • My changes generate no new warnings

  • I have tested this change

  • Any dependent changes have been merged and published in downstream modules

  • I have added all appropriate labels to this PR

  • I have followed all of these guidelines.

How Has This Been Tested? (if applicable)

I started Tux and ran a few commands.

Screenshots (if applicable)

{DA6308F5-4136-4C22-A265-C737785F4DC8}

Additional Information

Please add any other information that is important to this PR.

Summary by Sourcery

Refactor sentry span tagging and command handlers to reduce redundant calls and simplify control flows

Enhancements:

  • Cache sentry initialization status in a module-level variable to eliminate repeated is_initialized calls in cog_loader
  • Reorder and combine SENTRY_INITIALIZED checks around span tagging to streamline cog loading observability
  • Simplify avatar command logic by consolidating interaction response paths and removing duplicate branches
  • Refactor xkcd command to use an early return for missing comic_id and reorder specific comic handling

Copy link
Contributor

sourcery-ai bot commented Jul 16, 2025

Reviewer's Guide

This PR optimizes the cog loader and command handlers by caching Sentry initialization to eliminate redundant calls, and by streamlining conditional logic in the avatar and xkcd commands to simplify control flow and improve performance.

Sequence diagram for optimized Sentry initialization in cog loader

sequenceDiagram
    participant CogLoader
    participant SENTRY_INITIALIZED
    participant sentry_sdk
    participant current_span
    CogLoader->>SENTRY_INITIALIZED: Check if Sentry is initialized (cached)
    alt SENTRY_INITIALIZED is True
        CogLoader->>sentry_sdk: get_current_span()
        alt current_span exists
            CogLoader->>current_span: set_tag/set_data
        end
    end
Loading

Sequence diagram for refactored avatar command handler

sequenceDiagram
    participant User as actor
    participant AvatarCommandHandler
    participant discord.Interaction
    User->>AvatarCommandHandler: send_avatar(source, member)
    alt source is discord.Interaction and member exists
        AvatarCommandHandler->>discord.Interaction: response.send_message(files=files)
    else member has no avatar
        AvatarCommandHandler->>discord.Interaction: response.send_message(content=message, ephemeral=True, delete_after=30)
    else source is commands.Context
        AvatarCommandHandler->>AvatarCommandHandler: member = MemberConverter().convert(source, author.id)
    end
Loading

Sequence diagram for refactored xkcd command handler

sequenceDiagram
    participant User as actor
    participant XKCDCommandHandler
    participant commands.Context
    User->>XKCDCommandHandler: xkcd(ctx, comic_id)
    alt comic_id is not provided
        XKCDCommandHandler->>commands.Context: send_help("xkcd")
        XKCDCommandHandler-->>User: return
    else comic_id is provided
        XKCDCommandHandler->>XKCDCommandHandler: specific(ctx, comic_id)
    end
Loading

Class diagram for Sentry initialization optimization in cog loader

classDiagram
    class CogLoader {
        +load_times: dict
        +async _load_single_cog(path: Path)
        +async _load_cog_group(cogs: Sequence[Path])
        +async _process_single_file(path: Path)
        +async _process_directory(path: Path)
        +async load_cogs(path: Path)
        +async load_cogs_from_folder(folder_name: str)
        +static async setup(bot: commands.Bot)
    }
    class sentry_sdk {
        +is_initialized()
        +get_current_span()
    }
    CogLoader ..> sentry_sdk : uses
    class SENTRY_INITIALIZED {
        +bool
    }
    CogLoader ..> SENTRY_INITIALIZED : uses
Loading

Class diagram for refactored avatar command handler

classDiagram
    class AvatarCommandHandler {
        +async send_avatar(source, member)
        +async create_avatar_file(avatar)
    }
    class discord.Interaction {
        +response.send_message()
    }
    class commands.Context {
        +author
        +reply()
    }
    AvatarCommandHandler ..> discord.Interaction : interacts
    AvatarCommandHandler ..> commands.Context : interacts
Loading

Class diagram for refactored xkcd command handler

classDiagram
    class XKCDCommandHandler {
        +async xkcd(ctx, comic_id)
        +async specific(ctx, comic_id)
    }
    class commands.Context {
        +send_help()
    }
    XKCDCommandHandler ..> commands.Context : interacts
Loading

File-Level Changes

Change Details Files
Cache Sentry initialization state and replace repeated checks
  • Introduce module-level SENTRY_INITIALIZED constant
  • Swap all sentry_sdk.is_initialized() calls to use SENTRY_INITIALIZED
  • Move bot.id span tagging under the new constant guard
tux/cog_loader.py
Simplify avatar command control flow
  • Reorder check to handle Interaction sources first
  • Unify message sending to always use source.response.send_message
  • Remove redundant branches for reply vs. response
tux/cogs/info/avatar.py
Refactor xkcd command for early return and clearer branching
  • Invert comic_id guard to return early when missing
  • Shift specific comic call below the guard
  • Eliminate the nested else block for clarity
tux/cogs/fun/xkcd.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @amadaluzia - I've reviewed your changes - here's some feedback:

  • Caching sentry_sdk.is_initialized() in IS_INITIALIZED at import time assumes Sentry is initialized before this module loads—consider a lazy check or helper function to avoid stale values if initialization happens later.
  • There’s a lot of repeated if IS_INITIALIZED and (current_span := get_current_span()) boilerplate—extracting that into a small helper would reduce repetition and make future span calls easier to maintain.
  • The avatar refactor removes the fallback that converted the context author into a Member when no member was passed; double-check that you’re not losing intended behavior for context commands without explicit members.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Caching sentry_sdk.is_initialized() in IS_INITIALIZED at import time assumes Sentry is initialized before this module loads—consider a lazy check or helper function to avoid stale values if initialization happens later.
- There’s a lot of repeated `if IS_INITIALIZED and (current_span := get_current_span())` boilerplate—extracting that into a small helper would reduce repetition and make future span calls easier to maintain.
- The avatar refactor removes the fallback that converted the context author into a Member when no member was passed; double-check that you’re not losing intended behavior for context commands without explicit members.

## Individual Comments

### Comment 1
<location> `tux/cogs/fun/xkcd.py:38` </location>
<code_context>
             The ID of the xkcd comic to search for.
         """

-        if comic_id:
-            await self.specific(ctx, comic_id)
-        else:
+        if not comic_id:
             await ctx.send_help("xkcd")
+            return
</code_context>

<issue_to_address>
The logic for handling comic_id=0 may have changed unintentionally.

The updated condition causes comic_id=0 to trigger the help message instead of fetching comic 0. If 0 is valid, use 'if comic_id is not None' to avoid this regression.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@amadaluzia
Copy link
Contributor Author

@sourcery-ai review

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @amadaluzia - I've reviewed your changes - here's some feedback:

  • You have a lot of repeated if IS_INITIALIZED and get_current_span() checks—consider extracting that pattern into a helper or decorator to reduce duplication and improve readability.
  • Caching sentry_sdk.is_initialized() at import time can become stale if Sentry is initialized later—confirm that initialization always happens before this module loads or revert to a dynamic check.
  • The avatar command now only uses source.response for sending, so verify that non-Interaction (Context) invocations still behave as expected or explicitly handle both cases.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- You have a lot of repeated `if IS_INITIALIZED and get_current_span()` checks—consider extracting that pattern into a helper or decorator to reduce duplication and improve readability.
- Caching `sentry_sdk.is_initialized()` at import time can become stale if Sentry is initialized later—confirm that initialization always happens before this module loads or revert to a dynamic check.
- The `avatar` command now only uses `source.response` for sending, so verify that non-Interaction (Context) invocations still behave as expected or explicitly handle both cases.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link

codecov bot commented Jul 17, 2025

Codecov Report

❌ Patch coverage is 3.57143% with 27 lines in your changes missing coverage. Please review.
✅ Project coverage is 9.75%. Comparing base (8cd2837) to head (39ac2e4).
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
tux/cog_loader.py 4.54% 21 Missing ⚠️
tux/cogs/fun/xkcd.py 0.00% 3 Missing ⚠️
tux/cogs/info/avatar.py 0.00% 3 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##            main    #953      +/-   ##
========================================
+ Coverage   9.63%   9.75%   +0.12%     
========================================
  Files        123     123              
  Lines      10414   10412       -2     
  Branches    1279    1277       -2     
========================================
+ Hits        1003    1016      +13     
+ Misses      9307    9280      -27     
- Partials     104     116      +12     
Flag Coverage Δ *Carryforward flag
database 0.31% <ø> (+<0.01%) ⬆️ Carriedforward from 8cd2837
integration 5.86% <3.57%> (+0.01%) ⬆️
unit 6.31% <3.57%> (+0.01%) ⬆️

*This pull request uses carry forward flags. Click here to find out more.

Components Coverage Δ
Core Bot Infrastructure 16.52% <4.54%> (+0.08%) ⬆️
Database Layer 0.00% <ø> (ø)
Bot Commands & Features 0.00% <0.00%> (ø)
Event & Error Handling ∅ <ø> (∅)
Utilities & Helpers ∅ <ø> (∅)
User Interface Components 0.00% <ø> (ø)
CLI Interface ∅ <ø> (∅)
External Service Wrappers ∅ <ø> (∅)

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Collaborator

@anemoijereja-eden anemoijereja-eden left a comment

Choose a reason for hiding this comment

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

changes look good, please resolve the ambiguous naming of the IS_INITIALIZED variable

@electron271 electron271 marked this pull request as draft July 26, 2025 23:12
@electron271 electron271 marked this pull request as ready for review July 26, 2025 23:17
Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @amadaluzia - I've reviewed your changes - here's some feedback:

  • Using a module-level IS_INITIALIZED constant can be problematic if sentry_sdk is initialized later at runtime; consider a lazy check or ensuring sentry is always set up before import.
  • send_avatar refactor only handles Interaction sources in the primary branch and falls through for Context sources, which could break direct avatar commands in ctx—please verify Context handling remains correct.
  • A lot of boilerplate around checking IS_INITIALIZED and fetching current_span could be DRYed up with a helper or context manager to further clean this code.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Using a module-level IS_INITIALIZED constant can be problematic if sentry_sdk is initialized later at runtime; consider a lazy check or ensuring sentry is always set up before import.
- send_avatar refactor only handles Interaction sources in the primary branch and falls through for Context sources, which could break direct avatar commands in ctx—please verify Context handling remains correct.
- A lot of boilerplate around checking IS_INITIALIZED and fetching current_span could be DRYed up with a helper or context manager to further clean this code.

## Individual Comments

### Comment 1
<location> `tux/cogs/fun/xkcd.py:38` </location>
<code_context>
             The ID of the xkcd comic to search for.
         """

-        if comic_id:
-            await self.specific(ctx, comic_id)
-        else:
+        if not comic_id:
             await ctx.send_help("xkcd")
+            return
</code_context>

<issue_to_address>
The logic for handling comic_id has been inverted, which may affect behavior for comic_id=0.

The updated logic prevents access to comic 0 if it's valid. Explicitly check for None to allow comic_id=0.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@@ -35,10 +35,11 @@
The ID of the xkcd comic to search for.
"""

if comic_id:
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (bug_risk): The logic for handling comic_id has been inverted, which may affect behavior for comic_id=0.

The updated logic prevents access to comic 0 if it's valid. Explicitly check for None to allow comic_id=0.

@amadaluzia
Copy link
Contributor Author

@sourcery-ai review

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @amadaluzia - I've reviewed your changes - here's some feedback:

  • Using a module-level SENTRY_INITIALIZED flag means that if sentry_sdk.is_initialized() returns false at import time the flag will never update; consider lazily calling sentry_sdk.is_initialized() or refreshing the flag at runtime.
  • In the xkcd command, use an explicit 'if comic_id is None' check instead of falsy 'if not comic_id' to avoid treating a comic_id of 0 as missing.
  • The refactored avatar handler no longer sends replies for Context sources after converting the member—reintroduce or unify Context support so non-Interaction invocations still produce a response.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Using a module-level SENTRY_INITIALIZED flag means that if sentry_sdk.is_initialized() returns false at import time the flag will never update; consider lazily calling sentry_sdk.is_initialized() or refreshing the flag at runtime.
- In the xkcd command, use an explicit 'if comic_id is None' check instead of falsy 'if not comic_id' to avoid treating a comic_id of 0 as missing.
- The refactored avatar handler no longer sends replies for Context sources after converting the member—reintroduce or unify Context support so non-Interaction invocations still produce a response.

## Individual Comments

### Comment 1
<location> `tux/cogs/info/avatar.py:78` </location>
<code_context>
         member : discord.Member
             The member to get the avatar of.
         """
-        if member is not None:
+        if isinstance(source, discord.Interaction) and member is not None:
             guild_avatar = member.guild_avatar.url if member.guild_avatar else None
             global_avatar = member.avatar.url if member.avatar else None
</code_context>

<issue_to_address>
The function now only handles discord.Interaction sources for members, potentially breaking support for other source types.

If this change is intentional, please document or enforce the restriction. Otherwise, it may break support for non-Interaction sources.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@@ -75,22 +75,16 @@
member : discord.Member
The member to get the avatar of.
"""
if member is not None:
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (bug_risk): The function now only handles discord.Interaction sources for members, potentially breaking support for other source types.

If this change is intentional, please document or enforce the restriction. Otherwise, it may break support for non-Interaction sources.

@amadaluzia
Copy link
Contributor Author

@sourcery-ai review

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @amadaluzia - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `tux/cog_loader.py:17` </location>
<code_context>
 from tux.utils.config import CONFIG
 from tux.utils.sentry import safe_set_name, span, start_span, transaction

+SENTRY_INITIALIZED: bool = sentry_sdk.is_initialized()
+

</code_context>

<issue_to_address>
SENTRY_INITIALIZED is set at import time, which may not reflect runtime state.

If sentry_sdk may be initialized after import, caching its state could cause incorrect behavior. Consider calling sentry_sdk.is_initialized() directly unless initialization is guaranteed to be static.
</issue_to_address>

### Comment 2
<location> `tux/cogs/info/avatar.py:85` </location>
<code_context>

             if files:
-                if isinstance(source, discord.Interaction):
-                    await source.response.send_message(files=files)
-                else:
-                    await source.reply(files=files)
</code_context>

<issue_to_address>
No fallback for non-Interaction sources when sending avatar files.

If source can be something other than discord.Interaction, add a fallback or raise a clear error to avoid AttributeError.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@@ -14,6 +14,8 @@
from tux.utils.config import CONFIG
from tux.utils.sentry import safe_set_name, span, start_span, transaction

SENTRY_INITIALIZED: bool = sentry_sdk.is_initialized()
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (bug_risk): SENTRY_INITIALIZED is set at import time, which may not reflect runtime state.

If sentry_sdk may be initialized after import, caching its state could cause incorrect behavior. Consider calling sentry_sdk.is_initialized() directly unless initialization is guaranteed to be static.

await source.response.send_message(files=files)
else:
await source.reply(files=files)
await source.response.send_message(files=files)
else:
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (bug_risk): No fallback for non-Interaction sources when sending avatar files.

If source can be something other than discord.Interaction, add a fallback or raise a clear error to avoid AttributeError.

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.

2 participants