Skip to content
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

Adapt CaseSearchProfiler for more general use #35743

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from

Conversation

Charl1996
Copy link
Contributor

This PR is laying the groundwork for profiling the Case List Explorer.

Technical Summary

Ticket
Tech spec

This PR pulls out some functionality from the existing CaseSearchProfiler such that it can be used more generally where ES queries are executed with classes inheriting from HQESQuery.

A new mixin, ESQueryProfilerMixin, now makes use of this new profiler class. Any class making use of this mixin have access to a profiler which can be used to profile various class methods arbitrarily deep.

How to use mixin

Using the mixin and profiler is really easy. Say I have the following class definition:

class MyClass:
    search_class = ... # any ES class inheriting from HQESQuery 
    def some_complex_method(self):
        # some complex logic
        ...

If I now want to see how long some_complex_method takes to execute I can simply add the mixin, which gives me access to the profiler which I can use

class MyClass(ESQueryProfilerMixin):
    search_class = ... # any ES class inheriting from HQESQuery 
    def some_complex_method(self):
        # some complex logic
        with self.profiler.timing_context('Tracking some complex method'):
            ...

Note that some_complex_method does not have to necessarily execute an ES query; you can use the profiler to profile basically any method duration with the timing_context attribute.

How do I access the results?

The results can be accessed via the profiler.timing_context attribute. See the tech spec for more information.

Safety Assurance

Tested locally - more tests needed before opening for review.

Safety story

Automated test coverage

Tests to be added.

QA Plan

No QA planned for this PR - QA will be done as part of

Rollback instructions

  • This PR can be reverted after deploy with no further considerations

Labels & Review

  • Risk label is set correctly
  • The set of people pinged as reviewers is appropriate for the level of risk of the change

@Charl1996 Charl1996 requested a review from Jtang-1 February 6, 2025 15:28
Copy link

sentry-io bot commented Feb 6, 2025

🔍 Existing Issues For Review

Your pull request is modifying functions with the following pre-existing issues:

📄 File: corehq/apps/case_search/utils.py

Function Unhandled Issue
run ESError: ConnectionTimeout caused by - ReadTimeoutError(HTTPConnectionPool(host='10.202.40.159', port=9200... ...
Event Count: 3
run ESError: ConnectionTimeout caused by - ReadTimeoutError(HTTPConnectionPool(host='10.202.40.159', port=9200... ...
Event Count: 2

Did you find this useful? React with a 👍 or 👎

@Charl1996
Copy link
Contributor Author

@CodeRabbit Please review

Copy link

coderabbitai bot commented Feb 6, 2025

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Get the PR diff
gh pr diff 35743

# Search for relevant files
echo "=== Files containing CaseSearchProfiler ==="
rg -l "CaseSearchProfiler"

echo "=== Files containing ESQueryProfilerMixin ==="
rg -l "ESQueryProfilerMixin"

# Search for test files related to case search
echo "=== Test files related to case search ==="
fd "test.*case.*search.*\.py$"

Length of output: 5977


@Charl1996 Thank you for the PR! I've reviewed the changes and here's my feedback:

👍 Positives:

  • Great job on extracting the profiling functionality into a reusable base class
  • Clean implementation of the ESQueryProfilerMixin
  • Good use of dataclasses and inheritance

🤔 Suggestions:

  1. Consider adding docstrings to the ESQueryProfiler class explaining its purpose and usage
  2. The _get_search_class method could benefit from a more descriptive error message:
def _get_search_class(self):
    if not self.search_class:
        raise NotImplementedError(
            "You must define a search_class attribute that inherits from HQESQuery"
        )
    return self.search_class
  1. Consider adding type hints to improve code maintainability:
from typing import Type, Optional
# ...
def get_search_class(self, slug: Optional[str] = None) -> Type[HQESQuery]:

Required Changes:

  1. Tests are needed to cover:
    • Basic functionality of ESQueryProfiler
    • Integration with ESQueryProfilerMixin
    • Edge cases (e.g., when profiler is disabled)
    • Timing context accuracy

Let me know if you'd like me to elaborate on any of these points!


✏️ Learnings added
Learnt from: Charl1996
URL: https://github.com/dimagi/commcare-hq/pull/35743

Timestamp: 2025-02-06T15:30:23.908Z
Learning: The ESQueryProfilerMixin is used to profile Elasticsearch queries in CommCare HQ. It requires a search_class attribute to be defined and can be enabled/disabled via the profiler_enabled flag.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

coderabbitai bot commented Feb 6, 2025

Walkthrough

The changes refactor the search profiling mechanism used across case search and report generation. The original profiler class has been renamed from CaseSearchProfiler to ESQueryProfiler and modified to initialize a timing context and generate a dynamic inner search class via a new method get_search_class. A new subclass, also named CaseSearchProfiler, now inherits from ESQueryProfiler and introduces additional fields for counting primary and related queries. Updates in helper classes now refer to the new get_search_class method. Additionally, a new mixin class, ESQueryProfilerMixin, is added to the reports module to facilitate Elasticsearch query profiling. Its initializer and properties set up and maintain the profiler when enabled. Finally, the CaseListMixin class now includes the mixin, integrating profiling capabilities into the reporting workflow without altering the existing logic of query construction or result handling.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as QueryHelper/RegistryQueryHelper
    participant ESProfiler as ESQueryProfiler
    participant Dynamic as ProfiledSearchClass

    Caller->>ESProfiler: get_search_class(slug)
    ESProfiler->>ESProfiler: __post_init__ (initialize TimingContext)
    ESProfiler->>Dynamic: Define dynamic inner class based on search_class
    ESProfiler-->>Caller: Return ProfiledSearchClass
Loading
sequenceDiagram
    participant Report as CaseListReport/CaseListMixin
    participant Mixin as ESQueryProfilerMixin
    participant ESProfiler as ESQueryProfiler

    Report->>Mixin: Initialize report instance
    Mixin->>ESProfiler: Setup profiler (if enabled)
    ESProfiler-->>Mixin: Return profiler instance with search_class
    Mixin-->>Report: Integrate profiler context for report generation
Loading

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 docstrings to generate docstrings for this PR. (Beta)
  • @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.

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.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
corehq/apps/reports/standard/__init__.py (2)

311-328: Improve attribute assignment and initialization.

The mixin is well-designed but has a minor issue with the use of setattr.

Replace setattr with direct assignment for better readability:

-            setattr(self, 'search_class', self.profiler.get_search_class(slug=self.__class__.__name__))
+            self.search_class = self.profiler.get_search_class(slug=self.__class__.__name__)
🧰 Tools
🪛 Ruff (0.8.2)

327-327: Do not call setattr with a constant attribute value. It is not any safer than normal property access.

Replace setattr with assignment

(B010)


333-336: Enhance error message for missing search_class.

The error message could be more descriptive to help developers understand how to fix the issue.

-            raise NotImplementedError("You must define a search_class attribute.")
+            raise NotImplementedError(
+                "You must define a search_class attribute in your class. "
+                "This should be a subclass of HQESQuery that defines the search functionality."
+            )
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9fe973a and a52fa68.

📒 Files selected for processing (3)
  • corehq/apps/case_search/utils.py (4 hunks)
  • corehq/apps/reports/standard/__init__.py (2 hunks)
  • corehq/apps/reports/standard/cases/basic.py (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.py`: - Review the code following best practises and st...

**/*.py: - Review the code following best practises and standards

  • corehq/apps/reports/standard/__init__.py
  • corehq/apps/reports/standard/cases/basic.py
  • corehq/apps/case_search/utils.py
📓 Learnings (3)
📓 Common learnings
Learnt from: Charl1996
PR: dimagi/commcare-hq#0
File: :0-0
Timestamp: 2025-02-06T15:30:24.017Z
Learning: The ESQueryProfilerMixin is used to profile Elasticsearch queries in CommCare HQ. It requires a search_class attribute to be defined and can be enabled/disabled via the profiler_enabled flag.
corehq/apps/reports/standard/__init__.py (1)
Learnt from: Charl1996
PR: dimagi/commcare-hq#0
File: :0-0
Timestamp: 2025-02-06T15:30:24.017Z
Learning: The ESQueryProfilerMixin is used to profile Elasticsearch queries in CommCare HQ. It requires a search_class attribute to be defined and can be enabled/disabled via the profiler_enabled flag.
corehq/apps/case_search/utils.py (1)
Learnt from: Charl1996
PR: dimagi/commcare-hq#0
File: :0-0
Timestamp: 2025-02-06T15:30:24.017Z
Learning: The ESQueryProfilerMixin is used to profile Elasticsearch queries in CommCare HQ. It requires a search_class attribute to be defined and can be enabled/disabled via the profiler_enabled flag.
🪛 Ruff (0.8.2)
corehq/apps/reports/standard/__init__.py

327-327: Do not call setattr with a constant attribute value. It is not any safer than normal property access.

Replace setattr with assignment

(B010)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: tests (python-sharded-and-javascript)
🔇 Additional comments (4)
corehq/apps/case_search/utils.py (3)

57-67: LGTM! Well-structured base profiler class.

The refactoring of CaseSearchProfiler to ESQueryProfiler is clean and follows Python best practices:

  • Good use of @dataclass to reduce boilerplate
  • Proper initialization of timing_context in __post_init__
  • Sensible defaults for fields

68-92: LGTM! Well-designed profiling mechanism.

The get_search_class method effectively wraps the search class with profiling capabilities:

  • Proper timing context management
  • Debug mode support with query profiling
  • Clean implementation of the inner ProfiledSearchClass

95-100: LGTM! Well-designed specialized profiler.

The new CaseSearchProfiler class:

  • Properly inherits from ESQueryProfiler
  • Correctly specializes for case search with CaseSearchES
  • Adds relevant counters for case search profiling
corehq/apps/reports/standard/cases/basic.py (1)

32-44: LGTM! Clean integration of profiling capabilities.

The addition of ESQueryProfilerMixin is well-integrated:

  • Proper order in inheritance chain
  • Required search_class attribute is already defined
  • Maintains existing functionality

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