Skip to content

⚡ Bolt: Optimize get_system_stats query#502

Open
RohanExploit wants to merge 1 commit intomainfrom
bolt-optimize-admin-stats-1994715676450805088
Open

⚡ Bolt: Optimize get_system_stats query#502
RohanExploit wants to merge 1 commit intomainfrom
bolt-optimize-admin-stats-1994715676450805088

Conversation

@RohanExploit
Copy link
Owner

@RohanExploit RohanExploit commented Mar 4, 2026

💡 What: Refactored the /admin/stats endpoint to use a single SQL query with aggregates instead of three separate count() queries.
🎯 Why: Performing three separate queries (total_users, admin_users, active_users) caused redundant database scans and network round-trips. Consolidating into a single query improves performance by reducing database overhead.
📊 Impact: Reduces database queries from 3 to 1 per request. In local benchmarks with 1300 users, execution time for 100 iterations dropped from ~0.1788s to ~0.1055s, roughly a 40% performance improvement.
🔬 Measurement: Verify by executing the /admin/stats endpoint and comparing latency, or using pytest backend/tests/.


PR created automatically by Jules for task 1994715676450805088 started by @RohanExploit


Summary by cubic

Optimized the /admin/stats endpoint to use one aggregated SQL query instead of multiple count calls, reducing database work and speeding up responses.

  • Performance

    • Consolidated total, admin, and active user counts into a single query.
    • Reduced queries from 3 to 1 per request.
    • Local benchmark (1300 users, 100 runs): ~0.1788s → ~0.1055s (~40% faster).
  • Refactors

    • Implemented SQLAlchemy func/count with sum(case) for aggregates.
    • Return safe zeros when aggregates are null.
    • Added pytest.ini to auto-configure asyncio for tests.

Written for commit 198edaf. Summary will update on new commits.

Summary by CodeRabbit

  • Refactor

    • Optimized admin system statistics retrieval to use a single, efficient database query instead of multiple separate queries.
  • Tests

    • Added pytest configuration to enable asyncio integration for asynchronous test execution.

Copilot AI review requested due to automatic review settings March 4, 2026 14:25
@google-labs-jules
Copy link
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@netlify
Copy link

netlify bot commented Mar 4, 2026

Deploy Preview for fixmybharat canceled.

Name Link
🔨 Latest commit 198edaf
🔍 Latest deploy log https://app.netlify.com/projects/fixmybharat/deploys/69a840f3e32b940008d8485e

@github-actions
Copy link

github-actions bot commented Mar 4, 2026

🙏 Thank you for your contribution, @RohanExploit!

PR Details:

Quality Checklist:
Please ensure your PR meets the following criteria:

  • Code follows the project's style guidelines
  • Self-review of code completed
  • Code is commented where necessary
  • Documentation updated (if applicable)
  • No new warnings generated
  • Tests added/updated (if applicable)
  • All tests passing locally
  • No breaking changes to existing functionality

Review Process:

  1. Automated checks will run on your code
  2. A maintainer will review your changes
  3. Address any requested changes promptly
  4. Once approved, your PR will be merged! 🎉

Note: The maintainers will monitor code quality and ensure the overall project flow isn't broken.

@coderabbitai
Copy link

coderabbitai bot commented Mar 4, 2026

📝 Walkthrough

Walkthrough

The changes optimize database queries in the admin statistics endpoint by consolidating three separate count queries into a single aggregated query using SQLAlchemy, and add pytest configuration for async test handling.

Changes

Cohort / File(s) Summary
Database Query Optimization
backend/routers/admin.py
Replaced three separate database queries with a single aggregated query using func.count and func.sum(case(...)) to compute total_users, admin_count, and active_users metrics in one database hit. Added descriptive docstring and updated return payload to use aggregated result values with safe defaults.
Test Configuration
pytest.ini
Added new pytest configuration file with asyncio integration settings: asyncio_mode = auto and asyncio_default_fixture_loop_scope = function.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested labels

size/m

Poem

🐰 A query optimized with purpose and grace,
Three into one, in database space,
With pytest configured for async delight,
The tests shall hop through the night,
Efficiency wins, and the code shines bright! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The PR description provides clear context (what, why, impact, measurement) but does not follow the repository's required template structure with sections like 'Type of Change', 'Related Issue', 'Testing Done', and 'Checklist'. Fill in the required template sections including Type of Change (select ⚡ Performance improvement), Related Issue, Testing Done (confirm tests pass), and complete the Checklist to ensure all requirements are met.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: optimizing the get_system_stats query, which aligns with the primary objective of reducing database queries from 3 to 1.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch bolt-optimize-admin-stats-1994715676450805088

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@cubic-dev-ai cubic-dev-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.

No issues found across 2 files

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: 1

🧹 Nitpick comments (1)
backend/routers/admin.py (1)

28-32: Good optimization; consider fixing boolean comparison style.

The aggregated query is well-structured and achieves the 3→1 query optimization. However, the static analyzer flags User.is_active == True (E712). In SQLAlchemy, you can use the column directly in case() for boolean checks, or use .is_(True) for explicit comparison.

♻️ Suggested fix
     stats = db.query(
         func.count(User.id).label('total_users'),
         func.sum(case((User.role == UserRole.ADMIN, 1), else_=0)).label('admin_count'),
-        func.sum(case((User.is_active == True, 1), else_=0)).label('active_users')
+        func.sum(case((User.is_active, 1), else_=0)).label('active_users')
     ).first()

Or, if you prefer explicit boolean comparison:

-        func.sum(case((User.is_active == True, 1), else_=0)).label('active_users')
+        func.sum(case((User.is_active.is_(True), 1), else_=0)).label('active_users')
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/routers/admin.py` around lines 28 - 32, The case expression comparing
booleans uses a Python equality check (User.is_active == True) which triggers
E712; update the aggregation in the stats query to use the boolean column
directly or an SQLAlchemy is_ comparison (e.g., replace the predicate in
func.sum(case(...)) for User.is_active with User.is_active or
User.is_active.is_(True)) so the call to db.query / func.sum / case referencing
User.is_active is corrected without using == True.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@pytest.ini`:
- Around line 1-3: The project uses pytest-asyncio options (asyncio_mode and
asyncio_default_fixture_loop_scope) in pytest.ini but the dependency is missing;
add pytest-asyncio>=0.23.0 to backend/requirements.txt (and
backend/requirements-render.txt if async tests run there) so pytest-asyncio is
installed and the pytest.ini keys are supported; ensure the version constraint
is >=0.23.0 to guarantee support for asyncio_default_fixture_loop_scope.

---

Nitpick comments:
In `@backend/routers/admin.py`:
- Around line 28-32: The case expression comparing booleans uses a Python
equality check (User.is_active == True) which triggers E712; update the
aggregation in the stats query to use the boolean column directly or an
SQLAlchemy is_ comparison (e.g., replace the predicate in func.sum(case(...))
for User.is_active with User.is_active or User.is_active.is_(True)) so the call
to db.query / func.sum / case referencing User.is_active is corrected without
using == True.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 083cc43e-d96d-41f0-a2ae-b8a4c8315e5d

📥 Commits

Reviewing files that changed from the base of the PR and between 62aa431 and 198edaf.

📒 Files selected for processing (2)
  • backend/routers/admin.py
  • pytest.ini

Comment on lines +1 to +3
[pytest]
asyncio_mode = auto
asyncio_default_fixture_loop_scope = function
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# Search for pytest-asyncio version requirements in the repository
find . -type f \( -name "*.txt" -o -name "*.toml" -o -name "*.cfg" -o -name "*.py" -o -name "*.lock" -o -name "*.yaml" -o -name "*.yml" \) | head -20

Repository: RohanExploit/VishwaGuru

Length of output: 917


🏁 Script executed:

# Look for dependency files
git ls-files | grep -E "(requirements|setup|pyproject|poetry|pipfile)" | head -20

Repository: RohanExploit/VishwaGuru

Length of output: 177


🏁 Script executed:

# Check for pytest-asyncio in common dependency files
for file in requirements.txt requirements-dev.txt setup.py setup.cfg pyproject.toml poetry.lock Pipfile Pipfile.lock .python-version; do
  if [ -f "$file" ]; then
    echo "=== $file ==="
    cat "$file" | head -50
  fi
done

Repository: RohanExploit/VishwaGuru

Length of output: 49


🏁 Script executed:

echo "=== backend/requirements.txt ===" && cat backend/requirements.txt
echo ""
echo "=== backend/requirements-render.txt ===" && cat backend/requirements-render.txt

Repository: RohanExploit/VishwaGuru

Length of output: 984


🏁 Script executed:

# Search for pytest-asyncio anywhere in the repository
rg "pytest-asyncio" -i

Repository: RohanExploit/VishwaGuru

Length of output: 49


🏁 Script executed:

# Also check functions/requirements.txt and any other requirements files
find . -name "*requirements*.txt" -o -name "Pipfile*" -o -name "pyproject.toml" | grep -v node_modules

Repository: RohanExploit/VishwaGuru

Length of output: 156


🏁 Script executed:

cat functions/requirements.txt

Repository: RohanExploit/VishwaGuru

Length of output: 298


Add pytest-asyncio to project dependencies.

The pytest.ini file uses pytest-asyncio specific configuration options (asyncio_mode and asyncio_default_fixture_loop_scope), but pytest-asyncio is not listed as a dependency in any requirements file. Add it to backend/requirements.txt (and backend/requirements-render.txt if async tests run there) to enable these configuration options. Recommend a version constraint of pytest-asyncio>=0.23.0 to support asyncio_default_fixture_loop_scope.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pytest.ini` around lines 1 - 3, The project uses pytest-asyncio options
(asyncio_mode and asyncio_default_fixture_loop_scope) in pytest.ini but the
dependency is missing; add pytest-asyncio>=0.23.0 to backend/requirements.txt
(and backend/requirements-render.txt if async tests run there) so pytest-asyncio
is installed and the pytest.ini keys are supported; ensure the version
constraint is >=0.23.0 to guarantee support for
asyncio_default_fixture_loop_scope.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Refactors the /admin/stats admin endpoint to compute user counts in a single aggregated SQL query, reducing DB round-trips, and adds pytest asyncio configuration for running async tests.

Changes:

  • Consolidate total_users, admin_count, and active_users into one aggregate query in /admin/stats.
  • Add pytest.ini configuration enabling asyncio support in pytest runs.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.

File Description
backend/routers/admin.py Replaces multiple count() calls with a single aggregate query for admin stats.
pytest.ini Adds pytest asyncio configuration options (intended for pytest-asyncio).

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

You can also share your feedback on Copilot code review. Take the survey.

Comment on lines +1 to +3
[pytest]
asyncio_mode = auto
asyncio_default_fixture_loop_scope = function
Copy link

Copilot AI Mar 4, 2026

Choose a reason for hiding this comment

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

This adds asyncio_mode / asyncio_default_fixture_loop_scope, which are pytest-asyncio configuration options. The repo’s dependency lists (e.g., backend/requirements.txt) don’t appear to include pytest-asyncio, so pytest will likely emit “Unknown config option” warnings or fail to run async-marked tests depending on warning settings. Please add pytest-asyncio as a declared test/dev dependency (and consider pinning a minimum version that supports asyncio_default_fixture_loop_scope).

Copilot uses AI. Check for mistakes.
Comment on lines +28 to +32
stats = db.query(
func.count(User.id).label('total_users'),
func.sum(case((User.role == UserRole.ADMIN, 1), else_=0)).label('admin_count'),
func.sum(case((User.is_active == True, 1), else_=0)).label('active_users')
).first()
Copy link

Copilot AI Mar 4, 2026

Choose a reason for hiding this comment

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

The /admin/stats endpoint logic was refactored to an aggregate query, but there are currently no tests covering this endpoint. Please add a test that seeds a few users (admin/non-admin, active/inactive) and asserts the returned totals match expected counts so the refactor is protected against regressions.

Copilot uses AI. Check for mistakes.
@@ -1,5 +1,6 @@
from fastapi import APIRouter, Depends, HTTPException, status
Copy link

Copilot AI Mar 4, 2026

Choose a reason for hiding this comment

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

HTTPException and status are imported but not used anywhere in this module (and the new func/case import makes this import block part of the changed hunk). Please remove unused FastAPI imports to avoid lint warnings and keep imports minimal.

Suggested change
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi import APIRouter, Depends

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants