-
Notifications
You must be signed in to change notification settings - Fork 36
⚡ Bolt: [performance improvement] optimize closure status queries using GROUP BY #558
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
RohanExploit
wants to merge
6
commits into
main
Choose a base branch
from
bolt-optimize-closure-count-queries-6106104410388610831
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
a054a83
⚡ Bolt: [performance improvement] optimize closure status queries usi…
RohanExploit 8fb1b17
Initial plan
Copilot 62206ab
Fix benchmark file issues: remove unused imports, fix Grievance seed …
Copilot f7abfcc
Merge pull request #561 from RohanExploit/copilot/sub-pr-558
RohanExploit 2fb714d
fix: restore _redirects to fix Netlify deployment and resolve merge c…
RohanExploit 6c34338
fix: resolve missing httpx import and Netlify issues
RohanExploit File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -402,15 +402,15 @@ def get_closure_status( | |
| GrievanceFollower.grievance_id == grievance_id | ||
| ).scalar() | ||
|
|
||
| confirmations_count = db.query(func.count(ClosureConfirmation.id)).filter( | ||
| ClosureConfirmation.grievance_id == grievance_id, | ||
| ClosureConfirmation.confirmation_type == "confirmed" | ||
| ).scalar() | ||
| # Get all confirmation counts in a single query instead of multiple round-trips | ||
| counts = db.query( | ||
| ClosureConfirmation.confirmation_type, | ||
| func.count(ClosureConfirmation.id) | ||
| ).filter(ClosureConfirmation.grievance_id == grievance_id).group_by(ClosureConfirmation.confirmation_type).all() | ||
|
|
||
| disputes_count = db.query(func.count(ClosureConfirmation.id)).filter( | ||
| ClosureConfirmation.grievance_id == grievance_id, | ||
| ClosureConfirmation.confirmation_type == "disputed" | ||
| ).scalar() | ||
| counts_dict = {ctype: count for ctype, count in counts} | ||
| confirmations_count = counts_dict.get("confirmed", 0) | ||
| disputes_count = counts_dict.get("disputed", 0) | ||
|
|
||
| required_confirmations = max(1, int(total_followers * ClosureService.CONFIRMATION_THRESHOLD)) | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| import time | ||
| import collections | ||
| import threading | ||
| import sys | ||
| import os | ||
|
|
||
| # Add parent directory to path to import backend.cache | ||
| sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))) | ||
|
|
||
| from backend.cache import ThreadSafeCache | ||
|
|
||
| def benchmark_cache(cache_size, num_ops): | ||
| cache = ThreadSafeCache(ttl=300, max_size=cache_size) | ||
|
|
||
| # Fill cache | ||
| for i in range(cache_size): | ||
| cache.set(data=i, key=f"key{i}") | ||
|
|
||
| start_time = time.time() | ||
| for i in range(num_ops): | ||
| # Update existing keys to keep the cache full and trigger cleanup | ||
| cache.set(data=i, key=f"key{i % cache_size}") | ||
| end_time = time.time() | ||
|
|
||
| return end_time - start_time | ||
|
|
||
| if __name__ == "__main__": | ||
| size = 1000 | ||
| ops = 5000 | ||
| print(f"Benchmarking ThreadSafeCache with size={size}, ops={ops}...") | ||
| duration = benchmark_cache(size, ops) | ||
| print(f"Duration: {duration:.4f} seconds") | ||
| print(f"Ops/sec: {ops / duration:.2f}") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| import sys | ||
| import time | ||
| import os | ||
|
|
||
| from sqlalchemy import create_engine | ||
| from sqlalchemy.orm import sessionmaker | ||
|
|
||
| sys.path.insert(0, os.path.abspath('.')) | ||
|
|
||
| from backend.database import Base, get_db | ||
| from backend.models import Grievance, GrievanceFollower, ClosureConfirmation | ||
| from backend.routers.grievances import get_closure_status | ||
| from backend.closure_service import ClosureService | ||
| from unittest.mock import patch, MagicMock | ||
|
|
||
| # In-memory SQLite for testing | ||
| engine = create_engine('sqlite:///:memory:', connect_args={"check_same_thread": False}) | ||
| TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) | ||
|
|
||
| Base.metadata.create_all(bind=engine) | ||
|
|
||
| def seed_data(db): | ||
| grievance = Grievance( | ||
cubic-dev-ai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| unique_id="G123", | ||
| category="pothole", | ||
| status="open", | ||
| description="test", | ||
| pincode="123456", | ||
| city="city", | ||
| district="district", | ||
| state="state" | ||
| ) | ||
| db.add(grievance) | ||
| db.commit() | ||
| db.refresh(grievance) | ||
RohanExploit marked this conversation as resolved.
Show resolved
Hide resolved
RohanExploit marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| # Add followers | ||
| for i in range(100): | ||
| db.add(GrievanceFollower(grievance_id=grievance.id, user_email=f"user{i}@test.com")) | ||
|
|
||
| # Add confirmations | ||
| for i in range(50): | ||
| db.add(ClosureConfirmation( | ||
| grievance_id=grievance.id, | ||
| user_email=f"cuser{i}@test.com", | ||
| confirmation_type="confirmed" if i % 2 == 0 else "disputed" | ||
| )) | ||
|
|
||
| db.commit() | ||
| return grievance.id | ||
|
|
||
| def run_benchmark(): | ||
| db = TestingSessionLocal() | ||
| gid = seed_data(db) | ||
|
|
||
| start = time.perf_counter() | ||
| for _ in range(100): | ||
| get_closure_status(grievance_id=gid, db=db) | ||
| end = time.perf_counter() | ||
|
|
||
| print(f"Time taken for 100 calls: {(end - start) * 1000:.2f} ms") | ||
| db.close() | ||
|
|
||
| if __name__ == '__main__': | ||
| run_benchmark() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| import time | ||
| import collections | ||
|
|
||
| def run_bench(): | ||
| N = 1000 | ||
| ops = 10000 | ||
| timestamps = {f"key{i}": time.time() for i in range(N)} | ||
| current_time = time.time() | ||
| ttl = 300 | ||
|
|
||
| start = time.time() | ||
| for _ in range(ops): | ||
| expired_keys = [ | ||
| key for key, timestamp in timestamps.items() | ||
| if current_time - timestamp >= ttl | ||
| ] | ||
| print(f"Current O(N) cleanup time for {ops} ops: {time.time() - start:.4f}s") | ||
|
|
||
| # Optimized version | ||
| timestamps_od = collections.OrderedDict(timestamps) | ||
| start = time.time() | ||
| for _ in range(ops): | ||
| # Simulated optimized cleanup | ||
| # In real code we use next(iter(self._timestamps.items())) | ||
| for key, ts in timestamps_od.items(): | ||
| if current_time - ts >= ttl: | ||
| pass | ||
| else: | ||
| break | ||
| print(f"Optimized O(K) cleanup time (K=0) for {ops} ops: {time.time() - start:.4f}s") | ||
|
|
||
| if __name__ == "__main__": | ||
| run_bench() |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P1: The new
/api/detect-emotionimage-processing flow is incompatible with utility function contracts and can fail at runtime before calling the model.Prompt for AI agents