Skip to content

Fix API prefixes in test suite and optimize grievance closure statistics query#608

Merged
RohanExploit merged 2 commits into
mainfrom
fix-api-prefixes-and-closure-stats-3386248015207979354
Mar 30, 2026
Merged

Fix API prefixes in test suite and optimize grievance closure statistics query#608
RohanExploit merged 2 commits into
mainfrom
fix-api-prefixes-and-closure-stats-3386248015207979354

Conversation

@RohanExploit
Copy link
Copy Markdown
Owner

@RohanExploit RohanExploit commented Mar 29, 2026

This commit addresses two items:

  1. Test Suite Fixes: Updates the endpoint URLs in several detection-related tests to include the missing /api prefix, aligning them with the actual router configuration in main.py. This resolves the 404 Not Found errors that were causing the test suite to fail.
  2. Performance Optimization: Refactors the get_closure_status endpoint in the grievances module to use conditional aggregation (func.sum(case(...))) to calculate both confirmations and disputes in a single database query, instead of retrieving multiple rows with group_by and iterating over them in Python. This reduces database scan overhead and network round-trips for this hot-path endpoint.

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


Summary by cubic

Fixes detection test 404s by adding the /api prefix and speeds up grievance closure stats with a single aggregate query.

  • Bug Fixes

    • Updated detection test endpoints to use /api/... to match the router.
  • Refactors

    • Optimized get_closure_status to compute confirmations/disputes in one DB query with func.sum(case(...)).
    • Removed obsolete bench script test_grievances_opt.py.

Written for commit 520fc23. Summary will update on new commits.

Summary by CodeRabbit

  • Improvements
    • API endpoints now use consistent /api prefix across detection and transcription services.
    • Database query performance optimized for grievance closure status operations.

…re stats aggregate

1. Fixed routing prefix issues in `test_detection_bytes.py`, `test_new_features.py`, and `test_severity.py` to match the actual API mount prefixes in `main.py`, resolving 404 errors during testing.
2. Optimized the `get_closure_status` endpoint in `backend/routers/grievances.py` by replacing a `group_by` iteration with a single database round-trip aggregate query utilizing `func.sum(case(...))`, improving execution times.
@google-labs-jules
Copy link
Copy Markdown
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.

Copilot AI review requested due to automatic review settings March 29, 2026 11:14
@netlify
Copy link
Copy Markdown

netlify Bot commented Mar 29, 2026

Deploy Preview for fixmybharat failed. Why did it fail? →

Name Link
🔨 Latest commit 520fc23
🔍 Latest deploy log https://app.netlify.com/projects/fixmybharat/deploys/69caa8a5c33e51000839ec6a

@github-actions
Copy link
Copy Markdown

🙏 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
Copy Markdown

coderabbitai Bot commented Mar 29, 2026

Warning

Rate limit exceeded

@RohanExploit has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 7 minutes and 1 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 7 minutes and 1 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f936b43e-4925-4625-ba99-9694cd79a5ca

📥 Commits

Reviewing files that changed from the base of the PR and between ed49d7c and 520fc23.

📒 Files selected for processing (1)
  • backend/routers/grievances.py
📝 Walkthrough

Walkthrough

The PR optimizes the get_closure_status function in backend/routers/grievances.py by consolidating confirmation and dispute counting into a single CASE-based aggregate query. Additionally, test endpoints across multiple files are updated to use the /api/ route prefix, and a benchmarking script is removed.

Changes

Cohort / File(s) Summary
Grievances Query Optimization
backend/routers/grievances.py
Changed confirmation/dispute counting logic from separate grouped queries to a single CASE-based conditional aggregate, reducing database round-trips while maintaining identical response behavior.
API Route Prefix Updates
backend/tests/test_detection_bytes.py, backend/tests/test_new_features.py, backend/tests/test_severity.py
Updated test endpoints to use /api/ prefix: /api/detect-vandalism, /api/detect-infrastructure, /api/detect-waste, /api/detect-civic-eye, /api/transcribe-audio, /api/detect-severity.
Benchmarking Script Removal
test_grievances_opt.py
Removed benchmarking script that compared old grouped-query approach against a placeholder new approach for get_closure_status confirmation counting.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

Suggested labels

size/s, medium

Poem

🐰 A query once scattered, now consolidated tight,
One CASE statement shines where two queries took flight,
Tests march to /api/ with standardized grace,
And benchmarks fade—optimized, their time and their place!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the two main changes: fixing API prefixes in tests and optimizing the grievance closure statistics query.
Description check ✅ Passed The PR description clearly articulates the two main changes: test suite fixes for API prefixes and a performance optimization in the grievances module.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-api-prefixes-and-closure-stats-3386248015207979354

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
Copy Markdown
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 5 files

Copy link
Copy Markdown
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

This PR fixes failing detection endpoint tests by aligning their request URLs with the app’s /api router prefix, and improves the grievance closure-status counting logic by using conditional aggregation to compute confirmation/dispute counts without a GROUP BY result iteration.

Changes:

  • Update multiple detection-related tests to call /api/* endpoints instead of unprefixed routes.
  • Refactor get_closure_status to compute confirmed/disputed counts via conditional aggregation (sum(case(...))).
  • Remove a root-level ad-hoc benchmark script (test_grievances_opt.py).

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
test_grievances_opt.py Removes an ad-hoc benchmark script that could be collected as a test.
backend/tests/test_severity.py Fixes endpoint path to include /api prefix.
backend/tests/test_new_features.py Fixes multiple endpoint paths to include /api prefix.
backend/tests/test_detection_bytes.py Fixes endpoint paths to include /api prefix.
backend/routers/grievances.py Uses conditional aggregation to compute closure confirmation/dispute counts.

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

Comment on lines +403 to 406
# Optimized: Use a single aggregate query to calculate total followers, confirmations and disputes in one database roundtrip
total_followers = db.query(func.count(GrievanceFollower.id)).filter(
GrievanceFollower.grievance_id == grievance_id
).scalar()
Copy link

Copilot AI Mar 29, 2026

Choose a reason for hiding this comment

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

The comment says this is a single aggregate query calculating total followers + confirmations/disputes in one DB roundtrip, but the implementation still issues two separate queries (one for follower count, one for confirmation stats). Please either update the comment to match reality, or actually combine these into a single query (e.g., via subqueries) if the intent is truly one roundtrip.

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown

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

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

404-411: Optional: Consider combining both queries into a single round-trip.

The total_followers and stats queries could be combined using a cross-table aggregate, though this would add complexity. The current implementation is already a solid improvement over the previous approach.

♻️ Example combined query (optional)
from sqlalchemy import literal

combined = db.query(
    func.count(func.distinct(GrievanceFollower.id)).label('total_followers'),
    func.sum(case((ClosureConfirmation.confirmation_type == 'confirmed', 1), else_=0)).label('confirmed'),
    func.sum(case((ClosureConfirmation.confirmation_type == 'disputed', 1), else_=0)).label('disputed')
).select_from(Grievance).outerjoin(
    GrievanceFollower, GrievanceFollower.grievance_id == Grievance.id
).outerjoin(
    ClosureConfirmation, ClosureConfirmation.grievance_id == Grievance.id
).filter(Grievance.id == grievance_id).first()

This approach trades simplicity for a single database call. The current two-query approach is perfectly acceptable.

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

In `@backend/routers/grievances.py` around lines 404 - 411, The two separate
queries (total_followers and stats) can be combined into a single DB round-trip:
replace the separate db.query calls that use GrievanceFollower and
ClosureConfirmation with one aggregated query that selects total_followers
(count distinct GrievanceFollower.id) and the two SUM(CASE...) aggregates
(confirmed and disputed) in the same query, using select_from(Grievance) and
outerjoin to GrievanceFollower and ClosureConfirmation and filtering on
Grievance.id == grievance_id; update the variables to pull total_followers,
confirmed, disputed from the single .first() result instead of two queries.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@backend/routers/grievances.py`:
- Around line 404-411: The two separate queries (total_followers and stats) can
be combined into a single DB round-trip: replace the separate db.query calls
that use GrievanceFollower and ClosureConfirmation with one aggregated query
that selects total_followers (count distinct GrievanceFollower.id) and the two
SUM(CASE...) aggregates (confirmed and disputed) in the same query, using
select_from(Grievance) and outerjoin to GrievanceFollower and
ClosureConfirmation and filtering on Grievance.id == grievance_id; update the
variables to pull total_followers, confirmed, disputed from the single .first()
result instead of two queries.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5811bbd3-2c4c-4732-93c2-1dccb20bca72

📥 Commits

Reviewing files that changed from the base of the PR and between 19ef62d and ed49d7c.

📒 Files selected for processing (5)
  • backend/routers/grievances.py
  • backend/tests/test_detection_bytes.py
  • backend/tests/test_new_features.py
  • backend/tests/test_severity.py
  • test_grievances_opt.py
💤 Files with no reviewable changes (1)
  • test_grievances_opt.py

@RohanExploit RohanExploit temporarily deployed to fix-api-prefixes-and-closure-stats-3386248015207979354 - vishwaguru-backend PR #608 March 30, 2026 16:45 — with Render Destroyed
@RohanExploit RohanExploit merged commit 6fee644 into main Mar 30, 2026
8 of 12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants