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 various commands and the cog loader to improve performance and readability by caching sentry initialization checks, reordering conditionals, and flattening nested branches

Enhancements:

  • Cache sentry_sdk.is_initialized() in cog_loader and replace repeated calls with a constant flag
  • Simplify avatar command by reordering type checks and unifying message sending via the interaction response API
  • Flatten xkcd command logic with an early return when no comic_id is provided to reduce nesting

Copy link
Contributor

sourcery-ai bot commented Jul 16, 2025

Reviewer's Guide

Implemented performance optimizations by caching repeated sentry initialization checks, flattening command logic for early returns, and reordering conditional flows to reduce redundant calls.

Sequence diagram for optimized avatar command flow

sequenceDiagram
    participant User as actor User
    participant Bot
    participant AvatarCog
    participant Discord as discord.Interaction
    User->>Bot: Triggers avatar command
    Bot->>AvatarCog: send_avatar(source, member)
    AvatarCog->>Discord: response.send_message(files=files) (if member has avatar)
    AvatarCog->>Discord: response.send_message(content=message, ephemeral, delete_after=30) (if no avatar)
Loading

Sequence diagram for optimized xkcd command flow

sequenceDiagram
    participant User as actor User
    participant Bot
    participant XKCDCog
    User->>Bot: Triggers xkcd command
    Bot->>XKCDCog: xkcd(ctx, comic_id)
    alt comic_id is not provided
        XKCDCog->>Bot: ctx.send_help("xkcd")
    else comic_id is provided
        XKCDCog->>XKCDCog: specific(ctx, comic_id)
    end
Loading

Class diagram for CogLoader sentry optimization changes

classDiagram
    class CogLoader {
        +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)
        -IS_INITIALIZED: bool
    }
    CogLoader --|> Exception : CogLoadError
    class sentry_sdk {
        +is_initialized()
        +get_current_span()
    }
    CogLoader ..> sentry_sdk : uses
    CogLoader ..> safe_set_name
    CogLoader ..> span
    CogLoader ..> start_span
    CogLoader ..> transaction
Loading

Class diagram for avatar command logic refactor

classDiagram
    class AvatarCog {
        +async send_avatar(source, member: discord.Member)
        +async create_avatar_file(avatar)
    }
    AvatarCog ..> discord.Interaction
    AvatarCog ..> commands.Context
    AvatarCog ..> discord.Member
    AvatarCog ..> commands.MemberConverter
Loading

Class diagram for xkcd command logic refactor

classDiagram
    class XKCDCog {
        +async xkcd(ctx: commands.Context[Tux], comic_id: int | None = None)
        +async specific(ctx, comic_id)
    }
    XKCDCog ..> commands.Context
Loading

File-Level Changes

Change Details Files
Cache sentry initialization status and reduce redundant function calls
  • Introduced IS_INITIALIZED constant at module level
  • Replaced sentry_sdk.is_initialized() calls with IS_INITIALIZED in all span conditionals
  • Consolidated span tagging logic to use the cached flag
tux/cog_loader.py
Simplify avatar command logic and unify response handling
  • Reordered source-type check to prioritize Interaction path
  • Cached guild/global avatar URLs and built file list once
  • Unified all send_message calls and removed duplicate branching
tux/cogs/info/avatar.py
Refactor xkcd command for early return on missing ID
  • Inverted comic_id conditional to send help and return immediately if absent
  • Moved the specific(ctx, comic_id) invocation after validation
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

Attention: Patch coverage is 3.57143% with 27 lines in your changes missing coverage. Please review.

Project coverage is 9.39%. Comparing base (3e4f69e) to head (a50dbb3).

✅ 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.26%   9.39%   +0.12%     
========================================
  Files        123     123              
  Lines      10390   10388       -2     
  Branches    1276    1274       -2     
========================================
+ Hits         963     976      +13     
+ Misses      9325    9298      -27     
- Partials     102     114      +12     
Flag Coverage Δ *Carryforward flag
database 0.31% <ø> (+<0.01%) ⬆️ Carriedforward from 3e4f69e
integration 5.87% <3.57%> (+0.01%) ⬆️
unit 6.32% <3.57%> (+0.01%) ⬆️

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

Components Coverage Δ
Core Bot Infrastructure 16.53% <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

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

IS_INITIALIZED: bool = sentry_sdk.is_initialized()
Copy link
Collaborator

Choose a reason for hiding this comment

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

it's not immediately clear what IS_INITIALIZED is referring to exactly. consider naming the variable something like SENTRY_INITIALIZED instead for clarity.

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