Skip to content

I've made some enhancements to smart_retrieval.py to improve its st…#34

Merged
MasumRab merged 1 commit intomainfrom
feat/smart-retrieval-enhancements
Jun 14, 2025
Merged

I've made some enhancements to smart_retrieval.py to improve its st…#34
MasumRab merged 1 commit intomainfrom
feat/smart-retrieval-enhancements

Conversation

@MasumRab
Copy link
Copy Markdown
Owner

@MasumRab MasumRab commented Jun 14, 2025

…andalone execution and testing capabilities.

Here's a summary of the changes:

  1. Command-Line Interface: I've added a command-line interface with the following commands:

    • list-strategies: This will show you the available retrieval strategies.
    • execute-strategies: This allows you to run specific (or all) strategies with budget controls.
    • get-retrieval-analytics: You can use this to fetch and display retrieval analytics.
      All output from the command-line interface is in JSON format for both successful operations and any errors.
  2. Gmail Authentication: I've integrated OAuth 2.0 authentication, which enables the script to make authenticated calls to the Gmail API. It uses token.json and credentials.json (via the GMAIL_CREDENTIALS_JSON environment variable).

  3. Real Gmail API Calls: I've updated the email fetching logic in _fetch_email_batch to use actual Gmail API calls (messages.list and messages.get) instead of simulated ones. The simulation feature is still available as a fallback if authentication doesn't succeed.

  4. Refinements for Standalone Execution:

    • I've improved and standardized the logging throughout the script, and you can now configure the log levels.
    • I've ensured consistent use of checkpoint_db_path.
    • I've standardized the JSON error responses from the command-line interface, including exiting with a status of 1 when an error occurs.
  5. Unit Tests:

    • I've created tests/test_smart_retrieval.py with a structure for command-line interface and logic tests.
    • I've made significant progress in implementing these tests, including mocking Gmail API interactions and addressing issues related to asynchronous testing and SQLite usage in tests.
    • I've identified the specific next steps needed to fully stabilize the checkpointing and asynchronous command-line interface tests.

These updates make smart_retrieval.py a more functional and robust tool, which can be called by other services like GmailAIService.

Summary by Sourcery

Enable standalone execution of smart_retrieval by adding a command-line interface, integrating Gmail OAuth2 authentication with real API calls (and a simulation fallback), enhancing logging and checkpoint handling, and introducing unit tests for CLI and retrieval logic.

New Features:

  • Add CLI commands (list-strategies, execute-strategies, get-retrieval-analytics) with JSON input/output
  • Integrate OAuth2 authentication and Gmail API calls for live email retrieval with a simulation fallback
  • Implement unit test suite for smart_retrieval CLI and core logic with Gmail API mocking

Enhancements:

  • Standardize logging with configurable log levels and structured JSON error responses
  • Enforce API call and time budgets with detailed execution logging
  • Ensure consistent use of checkpoint database path and improve checkpoint/daily stats persistence logs

Tests:

  • Add tests/test_smart_retrieval.py scaffolding for command-line and async retrieval tests with SQLite support

Summary by CodeRabbit

  • New Features
    • Added support for Gmail API authentication using OAuth2, enabling retrieval of real email data.
    • Introduced a command-line interface (CLI) for listing strategies, executing retrievals, and fetching analytics, with JSON-formatted outputs.
  • Improvements
    • Enhanced logging throughout the retrieval process for better observability and error tracking.
    • Refined strategy optimization and checkpoint management with more informative logs and analytics.
    • Improved error handling and fallback mechanisms during authentication and API interactions.

…andalone execution and testing capabilities.

Here's a summary of the changes:

1.  **Command-Line Interface**: I've added a command-line interface with the following commands:
    *   `list-strategies`: This will show you the available retrieval strategies.
    *   `execute-strategies`: This allows you to run specific (or all) strategies with budget controls.
    *   `get-retrieval-analytics`: You can use this to fetch and display retrieval analytics.
    All output from the command-line interface is in JSON format for both successful operations and any errors.

2.  **Gmail Authentication**: I've integrated OAuth 2.0 authentication, which enables the script to make authenticated calls to the Gmail API. It uses `token.json` and `credentials.json` (via the `GMAIL_CREDENTIALS_JSON` environment variable).

3.  **Real Gmail API Calls**: I've updated the email fetching logic in `_fetch_email_batch` to use actual Gmail API calls (`messages.list` and `messages.get`) instead of simulated ones. The simulation feature is still available as a fallback if authentication doesn't succeed.

4.  **Refinements for Standalone Execution**:
    *   I've improved and standardized the logging throughout the script, and you can now configure the log levels.
    *   I've ensured consistent use of `checkpoint_db_path`.
    *   I've standardized the JSON error responses from the command-line interface, including exiting with a status of 1 when an error occurs.

5.  **Unit Tests**:
    *   I've created `tests/test_smart_retrieval.py` with a structure for command-line interface and logic tests.
    *   I've made significant progress in implementing these tests, including mocking Gmail API interactions and addressing issues related to asynchronous testing and SQLite usage in tests.
    *   I've identified the specific next steps needed to fully stabilize the checkpointing and asynchronous command-line interface tests.

These updates make `smart_retrieval.py` a more functional and robust tool, which can be called by other services like `GmailAIService`.
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai bot commented Jun 14, 2025

Reviewer's Guide

This PR transforms smart_retrieval.py into a standalone, testable CLI tool by integrating an argparse-based JSON CLI, OAuth2 Gmail authentication, real Gmail API calls (with simulation fallback), enhanced logging and error handling, refined retrieval/budget logic, and a new unit test scaffold.

Sequence Diagram: Email Fetching Logic in _fetch_email_batch

sequenceDiagram
    participant SGR as SmartGmailRetriever
    participant GmailSvc as Gmail API Service
    participant Simulator as Simulation Logic

    SGR->>SGR: _fetch_email_batch(query, batch_size, page_token)
    alt self.gmail_service is available
        SGR->>GmailSvc: users().messages().list(q=query, maxResults=batch_size, pageToken=page_token)
        GmailSvc-->>SGR: ListResponse (message_refs, nextPageToken, historyId)
        loop for each message_ref in ListResponse
            SGR->>GmailSvc: users().messages().get(id=message_ref.id, format='metadata')
            GmailSvc-->>SGR: MessageDetail
            SGR->>SGR: Transform MessageDetail
        end
        SGR-->>SGR: Returns {messages, nextPageToken, historyId}
    else self.gmail_service is NOT available
        SGR->>SGR: _simulate_gmail_response(query, batch_size, page_token)
        SGR-->>SGR: Returns simulated {messages, nextPageToken, historyId}
    end
Loading

Sequence Diagram: CLI execute-strategies Command Flow

sequenceDiagram
    actor User
    participant CLI as main_cli
    participant SGR as SmartGmailRetriever

    User->>CLI: python smart_retrieval.py execute-strategies ...
    CLI->>CLI: Parse arguments
    CLI->>SGR: __init__(checkpoint_db_path)
    alt SGR.gmail_service is None
        CLI-->>User: JSON error (Gmail auth failed)
    else SGR.gmail_service is available
        CLI->>SGR: execute_smart_retrieval(strategies, max_api_calls, time_budget)
        loop For each strategy (respecting budget)
            SGR->>SGR: _load_checkpoint(strategy.name)
            SGR->>SGR: get_incremental_query(strategy, checkpoint)
            SGR->>SGR: _execute_strategy_retrieval(strategy, query, checkpoint, remaining_calls)
            SGR->>SGR: _save_checkpoint(new_checkpoint)
        end
        SGR->>SGR: _store_daily_stats(results)
        SGR-->>CLI: Returns execution results
        CLI-->>User: JSON output (results)
    end
Loading

Class Diagram: Changes to SmartGmailRetriever and Related Types

classDiagram
    class SmartGmailRetriever {
        +checkpoint_db_path: str
        +logger: logging.Logger
        +gmail_service: Optional~Resource~
        +api_limits: Dict
        +sync_stats: Dict
        +error_stats: Dict
        +__init__(checkpoint_db_path: str)
        #_init_checkpoint_db()
        #_load_credentials() : Optional~Credentials~
        #_store_credentials(creds: Credentials)
        #_authenticate() : Optional~Credentials~
        +get_optimized_retrieval_strategies() : List~RetrievalStrategy~
        +get_incremental_query(strategy: RetrievalStrategy, checkpoint: Optional~SyncCheckpoint~) : str
        +execute_smart_retrieval(strategies: Optional~List~, max_api_calls: int, time_budget_minutes: int) : Dict
        #_execute_strategy_retrieval(strategy: RetrievalStrategy, query: str, checkpoint: Optional~SyncCheckpoint~, remaining_api_calls: int) : Dict
        #_fetch_email_batch(query: str, batch_size: int, page_token: Optional~str~) : Dict
        #_simulate_gmail_response(query: str, batch_size: int, page_token: Optional~str~) : Dict
        #_load_checkpoint(strategy_name: str) : Optional~SyncCheckpoint~
        #_save_checkpoint(checkpoint: SyncCheckpoint)
        #_store_daily_stats(results: Dict)
        +get_retrieval_analytics(days: int) : Dict
        +optimize_strategies_based_on_performance() : List~RetrievalStrategy~
    }
    class Credentials {
        <<google.oauth2.credentials>>
        +valid: bool
        +expired: bool
        +refresh_token: str
        +refresh(request: Request)
        +to_json() : str
        +from_authorized_user_file(filename: str, scopes: List[str]) : Credentials
    }
    class RetrievalStrategy {
        <<Dataclass>>
        +name: str
        +query_filter: str
        +priority: int
        +frequency: str
        +max_emails_per_run: int
        +batch_size: int
        +include_folders: List[str]
        +exclude_folders: List[str]
    }
    class SyncCheckpoint {
        <<Dataclass>>
        +strategy_name: str
        +last_sync_date: datetime
        +last_history_id: str
        +processed_count: int
        +next_page_token: Optional[str]
        +errors_count: int
    }
    SmartGmailRetriever --> Credentials : uses
    SmartGmailRetriever --> RetrievalStrategy : uses
    SmartGmailRetriever --> SyncCheckpoint : uses
Loading

File-Level Changes

Change Details Files
Command-line interface support
  • Added main_cli() with argparse subcommands: list-strategies, execute-strategies, get-retrieval-analytics
  • Outputs all results and errors in JSON and exits with status 1 on failures
  • Introduced --checkpoint-db-path and other CLI flags for custom configurations
server/python_nlp/smart_retrieval.py
OAuth2 Gmail authentication integration
  • Loaded credentials from token.json or GMAIL_CREDENTIALS_JSON, refreshed or re-authenticated via InstalledAppFlow
  • Stored credentials back to token.json after refresh or new auth
  • Initialized gmail_service or logged failure for fallback
server/python_nlp/smart_retrieval.py
Production Gmail API calls & simulation fallback
  • Replaced simulated fetch logic in _fetch_email_batch with actual users().messages().list/get calls
  • Transformed and aggregated message metadata, tracked historyId
  • Retained _simulate_gmail_response() for use when gmail_service is unavailable
server/python_nlp/smart_retrieval.py
Improved logging & error standardization
  • Configured logging levels via LOG_LEVEL env var; reduced Google client verbosity by default
  • Added structured info/debug logs across methods (queries, checkpoints, batches, budgets)
  • Standardized JSON error responses in CLI and consistent use of checkpoint_db_path
server/python_nlp/smart_retrieval.py
Enhanced retrieval execution & budgeting
  • Inserted detailed time and API call budget checks with warnings on limits reached
  • Logged per-strategy execution steps, batch fetch details, and performance metrics
  • Introduced placeholders and TODOs for more accurate API call accounting
server/python_nlp/smart_retrieval.py
Unit test suite scaffolding
  • Created tests/test_smart_retrieval.py for CLI and logic tests
  • Mocked Gmail API interactions and set up SQLite in-memory tests
  • Documented next steps to stabilize checkpointing and async CLI tests
server/python_nlp/tests/test_smart_retrieval.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

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Jun 14, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The changes introduce OAuth2-based Gmail API authentication and real email data fetching in the SmartGmailRetriever class. Logging is extensively added throughout retrieval, checkpoint, and analytics processes. A new command-line interface (CLI) is implemented for strategy management, retrieval execution, and analytics, with improved error handling and logging configuration.

Changes

File(s) Change Summary
server/python_nlp/smart_retrieval.py Integrated Gmail OAuth2 authentication, real API data fetching, extensive logging, new CLI, improved checkpoint and analytics handling, and strategy optimization logic. Added and modified several methods and entry points for these purposes.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant SmartGmailRetriever
    participant GmailAPI

    User->>CLI: Run command (e.g., execute retrieval)
    CLI->>SmartGmailRetriever: Initialize and authenticate
    SmartGmailRetriever->>GmailAPI: Authenticate via OAuth2
    GmailAPI-->>SmartGmailRetriever: Return credentials/service
    SmartGmailRetriever->>GmailAPI: Fetch email batch (with query)
    GmailAPI-->>SmartGmailRetriever: Return email data
    SmartGmailRetriever->>CLI: Return results/logs
    CLI->>User: Display output (JSON, logs, errors)
Loading

Poem

In the warren of code, new tunnels appear,
Gmail’s secrets unlocked, OAuth draws near.
With logging that sparkles and CLI bright,
Strategies hop forward, checkpoints in sight.
Now emails retrieved with a bunny’s delight—
Hopping through inboxes, day and night!
🐇📧✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0e2832d and aed3bf0.

📒 Files selected for processing (1)
  • server/python_nlp/smart_retrieval.py (17 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.

@MasumRab MasumRab merged commit c9ff057 into main Jun 14, 2025
2 of 3 checks passed
@MasumRab MasumRab deleted the feat/smart-retrieval-enhancements branch June 14, 2025 13:21
Copy link
Copy Markdown
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 @MasumRab - 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> `server/python_nlp/smart_retrieval.py:26` </location>
<code_context>
+from googleapiclient.discovery import build
+from googleapiclient.errors import HttpError
+
+load_dotenv()
+
+# Define constants for authentication
</code_context>

<issue_to_address>
Avoid loading .env at import time

Move load_dotenv() to the CLI entrypoint or main function to prevent side effects and improve testability.

Suggested implementation:

```python
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# Define constants for authentication

```

You must move the `load_dotenv()` call to the CLI entrypoint or the main function of your application (e.g., under `if __name__ == "__main__":` or in your main CLI handler). This will ensure environment variables are loaded only when the script is run directly, not on import.
</issue_to_address>

### Comment 2
<location> `server/python_nlp/smart_retrieval.py:421` </location>
<code_context>
             exclude_filters = " AND ".join([f"-in:{folder.lower()}" for folder in strategy.exclude_folders])
             base_query = f"{base_query} {exclude_filters}"

+        self.logger.info(f"Generated incremental query for strategy '{strategy.name}': {base_query}")
         return base_query

</code_context>

<issue_to_address>
Use DEBUG level for verbose query logs

Consider changing this log statement to DEBUG to prevent cluttering INFO logs and reduce the risk of exposing sensitive information.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
        self.logger.info(f"Generated incremental query for strategy '{strategy.name}': {base_query}")
=======
        self.logger.debug(f"Generated incremental query for strategy '{strategy.name}': {base_query}")
>>>>>>> REPLACE

</suggested_fix>

### Comment 3
<location> `server/python_nlp/smart_retrieval.py:701` </location>
<code_context>
+        sys.exit(1)
+
 if __name__ == "__main__":
-    asyncio.run(main())
\ No newline at end of file
+    # Configure logging. Default to INFO, but allow override via environment variable for debugging.
</code_context>

<issue_to_address>
Add CLI invocation in __main__

Please add a call to execute the CLI, such as `asyncio.run(main_cli())`, so the script performs the intended retrieval logic when run.
</issue_to_address>

### Comment 4
<location> `server/python_nlp/smart_retrieval.py:595` </location>
<code_context>
+                # For now, assume 1 "conceptual" API call per _fetch_email_batch call for loop control.
+                # The actual API calls will be summed up later.
+                # This means api_calls_for_strategy here is more like "batches_processed_for_strategy".
+                # TODO: Refine API call counting here based on _fetch_email_batch's true cost.
+                # For now, let's count it as 1 + number of messages fetched (1 for list, 1 for each get).
+                # This is a placeholder, actual counting is complex and depends on _fetch_email_batch internals.
</code_context>

<issue_to_address>
Implement accurate API call counting

Use the actual number of list and get calls from `_fetch_email_batch` to ensure accurate API quota tracking.

Suggested implementation:

```python
                # _fetch_email_batch makes 1 call for list, and N calls for get.
                # We now use the actual number of API calls made in the batch, as reported by _fetch_email_batch.
                # _fetch_email_batch must return an 'api_calls_in_batch' field: 1 (list) + N (get) calls.
                api_calls_for_strategy += batch_result.get('api_calls_in_batch', 1)  # Default to 1 if not present

                if batch_result.get('error'):

```

You must ensure that `_fetch_email_batch` returns an `api_calls_in_batch` field in its result dictionary, accurately reflecting the number of API calls made (1 for list + N for get). If it does not, update `_fetch_email_batch` accordingly.
</issue_to_address>

### Comment 5
<location> `server/python_nlp/smart_retrieval.py:942` </location>
<code_context>
+                    strategy.batch_size = max(10, strategy.batch_size // 2)
+                    self.logger.info(f"Strategy '{strategy.name}': High error rate ({error_rate:.2f}%). Reducing batch size from {original_batch_size} to {strategy.batch_size}.")
+                elif error_rate < 2 and perf.get('sync_count', 0) > 5 : # Low error rate and sufficient data
+                    strategy.batch_size = min(self.api_limits.get('batch_size_limit', 100), int(strategy.batch_size * 1.2)) # Ensure not over API limit
+                    if strategy.batch_size != original_batch_size:
+                        self.logger.info(f"Strategy '{strategy.name}': Low error rate ({error_rate:.2f}%). Increasing batch size from {original_batch_size} to {strategy.batch_size}.")
</code_context>

<issue_to_address>
Define `batch_size_limit` in `api_limits`

`api_limits` should explicitly define `batch_size_limit` or derive it from the Gmail API to avoid relying on a hardcoded default value.

Suggested implementation:

```python
                elif error_rate < 2 and perf.get('sync_count', 0) > 5 : # Low error rate and sufficient data
                    strategy.batch_size = min(self.api_limits['batch_size_limit'], int(strategy.batch_size * 1.2)) # Ensure not over API limit
                    if strategy.batch_size != original_batch_size:
                        self.logger.info(f"Strategy '{strategy.name}': Low error rate ({error_rate:.2f}%). Increasing batch size from {original_batch_size} to {strategy.batch_size}.")

```

You must ensure that `self.api_limits['batch_size_limit']` is always set before this code runs. 
- If `self.api_limits` is set in the class `__init__` or a setup method, add something like:
    ```python
    self.api_limits['batch_size_limit'] = <value_from_gmail_api_or_config>
    ```
- If you can derive it from the Gmail API, do so and assign it to `self.api_limits['batch_size_limit']` during initialization.
- Remove any fallback to a hardcoded default in the `.get()` call as shown above.
</issue_to_address>

### Comment 6
<location> `server/python_nlp/smart_retrieval.py:158` </location>
<code_context>
+    def _store_credentials(self, creds: Credentials):
+        """Stores credentials to TOKEN_JSON_PATH."""
+        try:
+            with open(TOKEN_JSON_PATH, 'w') as token_file:
+                token_file.write(creds.to_json())
+            self.logger.info(f"Stored credentials to {TOKEN_JSON_PATH}")
</code_context>

<issue_to_address>
Restrict credentials file permissions

Set file permissions to 0o600 after writing the token file to prevent unauthorized access.
</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.

from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

load_dotenv()
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

suggestion: Avoid loading .env at import time

Move load_dotenv() to the CLI entrypoint or main function to prevent side effects and improve testability.

Suggested implementation:

from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# Define constants for authentication

You must move the load_dotenv() call to the CLI entrypoint or the main function of your application (e.g., under if __name__ == "__main__": or in your main CLI handler). This will ensure environment variables are loaded only when the script is run directly, not on import.

exclude_filters = " AND ".join([f"-in:{folder.lower()}" for folder in strategy.exclude_folders])
base_query = f"{base_query} {exclude_filters}"

self.logger.info(f"Generated incremental query for strategy '{strategy.name}': {base_query}")
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

suggestion: Use DEBUG level for verbose query logs

Consider changing this log statement to DEBUG to prevent cluttering INFO logs and reduce the risk of exposing sensitive information.

Suggested change
self.logger.info(f"Generated incremental query for strategy '{strategy.name}': {base_query}")
self.logger.debug(f"Generated incremental query for strategy '{strategy.name}': {base_query}")

sys.exit(1)

if __name__ == "__main__":
asyncio.run(main()) No newline at end of file
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

suggestion (bug_risk): Add CLI invocation in main

Please add a call to execute the CLI, such as asyncio.run(main_cli()), so the script performs the intended retrieval logic when run.

# For now, assume 1 "conceptual" API call per _fetch_email_batch call for loop control.
# The actual API calls will be summed up later.
# This means api_calls_for_strategy here is more like "batches_processed_for_strategy".
# TODO: Refine API call counting here based on _fetch_email_batch's true cost.
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

suggestion: Implement accurate API call counting

Use the actual number of list and get calls from _fetch_email_batch to ensure accurate API quota tracking.

Suggested implementation:

                # _fetch_email_batch makes 1 call for list, and N calls for get.
                # We now use the actual number of API calls made in the batch, as reported by _fetch_email_batch.
                # _fetch_email_batch must return an 'api_calls_in_batch' field: 1 (list) + N (get) calls.
                api_calls_for_strategy += batch_result.get('api_calls_in_batch', 1)  # Default to 1 if not present

                if batch_result.get('error'):

You must ensure that _fetch_email_batch returns an api_calls_in_batch field in its result dictionary, accurately reflecting the number of API calls made (1 for list + N for get). If it does not, update _fetch_email_batch accordingly.

strategy.batch_size = max(10, strategy.batch_size // 2)
self.logger.info(f"Strategy '{strategy.name}': High error rate ({error_rate:.2f}%). Reducing batch size from {original_batch_size} to {strategy.batch_size}.")
elif error_rate < 2 and perf.get('sync_count', 0) > 5 : # Low error rate and sufficient data
strategy.batch_size = min(self.api_limits.get('batch_size_limit', 100), int(strategy.batch_size * 1.2)) # Ensure not over API limit
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

suggestion: Define batch_size_limit in api_limits

api_limits should explicitly define batch_size_limit or derive it from the Gmail API to avoid relying on a hardcoded default value.

Suggested implementation:

                elif error_rate < 2 and perf.get('sync_count', 0) > 5 : # Low error rate and sufficient data
                    strategy.batch_size = min(self.api_limits['batch_size_limit'], int(strategy.batch_size * 1.2)) # Ensure not over API limit
                    if strategy.batch_size != original_batch_size:
                        self.logger.info(f"Strategy '{strategy.name}': Low error rate ({error_rate:.2f}%). Increasing batch size from {original_batch_size} to {strategy.batch_size}.")

You must ensure that self.api_limits['batch_size_limit'] is always set before this code runs.

  • If self.api_limits is set in the class __init__ or a setup method, add something like:
    self.api_limits['batch_size_limit'] = <value_from_gmail_api_or_config>
  • If you can derive it from the Gmail API, do so and assign it to self.api_limits['batch_size_limit'] during initialization.
  • Remove any fallback to a hardcoded default in the .get() call as shown above.

def _store_credentials(self, creds: Credentials):
"""Stores credentials to TOKEN_JSON_PATH."""
try:
with open(TOKEN_JSON_PATH, 'w') as token_file:
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🚨 suggestion (security): Restrict credentials file permissions

Set file permissions to 0o600 after writing the token file to prevent unauthorized access.

self.logger.info(f"Generated incremental query for strategy '{strategy.name}': {base_query}")
return base_query

async def execute_smart_retrieval(
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

issue (code-quality): Low code quality found in SmartGmailRetriever.execute_smart_retrieval - 20% (low-code-quality)


ExplanationThe quality score for this function is below the quality threshold of 25%.
This score is a combination of the method length, cognitive complexity and working memory.

How can you solve this?

It might be worth refactoring this function to make it shorter and more readable.

  • Reduce the function length by extracting pieces of functionality out into
    their own functions. This is the most important thing you can do - ideally a
    function should be less than 10 lines.
  • Reduce nesting, perhaps by introducing guard clauses to return early.
  • Ensure that variables are tightly scoped, so that code using related concepts
    sits together within the function rather than being scattered.

@@ -581,6 +852,7 @@ def _store_daily_stats(self, results: Dict[str, Any]):

def get_retrieval_analytics(self, days: int = 30) -> Dict[str, Any]:
"""Get retrieval analytics for the past N days"""
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

issue (code-quality): Convert for loop into list comprehension [×2] (list-comprehension)

@@ -643,37 +915,49 @@ def get_retrieval_analytics(self, days: int = 30) -> Dict[str, Any]:

def optimize_strategies_based_on_performance(self) -> List[RetrievalStrategy]:
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

issue (code-quality): We've found these issues:

  • Use named expression to simplify assignment and conditional (use-named-expression)
  • Low code quality found in SmartGmailRetriever.optimize_strategies_based_on_performance - 21% (low-code-quality)


Explanation
The quality score for this function is below the quality threshold of 25%.
This score is a combination of the method length, cognitive complexity and working memory.

How can you solve this?

It might be worth refactoring this function to make it shorter and more readable.

  • Reduce the function length by extracting pieces of functionality out into
    their own functions. This is the most important thing you can do - ideally a
    function should be less than 10 lines.
  • Reduce nesting, perhaps by introducing guard clauses to return early.
  • Ensure that variables are tightly scoped, so that code using related concepts
    sits together within the function rather than being scattered.

This was referenced Oct 14, 2025
MasumRab added a commit that referenced this pull request Oct 29, 2025
I've made some enhancements to `smart_retrieval.py` to improve its st…
MasumRab added a commit that referenced this pull request Nov 6, 2025
I've made some enhancements to `smart_retrieval.py` to improve its st…
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