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 performance-critical code by caching the sentry initialization state and reorganizing conditional statements in cog loading and command handlers to reduce redundant checks and simplify logic.

Enhancements:

  • Cache sentry initialization in an IS_INITIALIZED constant and replace repeated sentry_sdk.is_initialized() calls throughout CogLoader
  • Reorder and simplify span tagging and timing logic in cog_loader.setup for cleaner and more efficient execution
  • Streamline the avatar command by unifying response handling under Interaction and reducing nested type branches
  • Simplify xkcd command flow by inverting the initial condition to early return when no comic_id and flatten the logic

Copy link
Contributor

sourcery-ai bot commented Jul 16, 2025

Reviewer's Guide

This PR optimizes the cog loader, avatar command, and xkcd command by caching sentry initialization checks, reordering conditionals, and flattening nested logic for improved performance and readability.

Class diagram for CogLoader sentry optimization

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
    }
    class sentry_sdk {
        +is_initialized()
        +get_current_span()
    }
    CogLoader --|> sentry_sdk : uses
    note for CogLoader "Now uses IS_INITIALIZED instead of repeated sentry_sdk.is_initialized() calls"
Loading

File-Level Changes

Change Details Files
Cache sentry initialization state and replace repeated checks
  • Introduce a global IS_INITIALIZED flag set once at import time
  • Replace all sentry_sdk.is_initialized() calls with the IS_INITIALIZED constant
  • Remove redundant sentry initialization evaluations before setting span tags and data
tux/cog_loader.py
Simplify avatar command by unifying response handling and reordering conditions
  • Combine interaction type and member presence check into a single if condition
  • Use a single source.response.send_message path for both file and text responses
  • Eliminate separate Context reply branches in the interaction handling
tux/cogs/info/avatar.py
Flatten xkcd command logic with an early return to reduce nesting
  • Invert the comic_id check to return early when it’s missing
  • Move the specific comic handler call after the early return
  • Remove the else branch to simplify the command flow
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.

@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.

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