Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,7 @@
## 2026-05-20 - Joined Queries for Integrity Verification
**Learning:** Performing multiple sequential database queries to verify cryptographically chained records (e.g., fetching a record and then its associated token/metadata from another table) introduces unnecessary latency and increases database load.
**Action:** Consolidate associated data retrieval into a single SQL `JOIN` query within the verification hot-path. This reduces database round-trips and improves end-to-end latency for blockchain-style integrity checks.

## 2026-05-25 - Group-By Consolidation for Single Scan
**Learning:** Consolidating multiple database aggregate queries into a single query using SQLAlchemy `func.sum(case(...))` for categorical counts alongside other aggregates (like `avg` and `count(distinct)`) measurably improves performance by reducing database roundtrips and redundant table scans.
**Action:** Use a single SQLAlchemy query with `func.count(func.distinct())`, `func.avg()`, and `func.sum(case(...))` to calculate all metrics in one go when calculating global statistics.
41 changes: 13 additions & 28 deletions backend/routers/field_officer.py
Original file line number Diff line number Diff line change
Expand Up @@ -438,37 +438,22 @@ def get_visit_statistics(db: Session = Depends(get_db)):
return Response(content=cached_json, media_type="application/json")

# Optimized: Use a single aggregate query to fetch multiple statistics in one database roundtrip
agg_stats = db.query(
stats = db.query(
func.count(func.distinct(FieldOfficerVisit.officer_email)).label('unique_officers'),
func.avg(FieldOfficerVisit.distance_from_site).label('avg_distance')
func.avg(FieldOfficerVisit.distance_from_site).label('avg_distance'),
func.count(FieldOfficerVisit.id).label('total_visits'),
func.sum(case((FieldOfficerVisit.verified_at.isnot(None), 1), else_=0)).label('verified_visits'),
func.sum(case((FieldOfficerVisit.within_geofence == True, 1), else_=0)).label('within_geofence_count'),
func.sum(case((FieldOfficerVisit.within_geofence == False, 1), else_=0)).label('outside_geofence_count')
Comment on lines +446 to +447
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify remaining non-idiomatic boolean comparisons in SQLAlchemy predicates.
rg -nP --type=py '==\s*True|==\s*False' backend/routers/field_officer.py

Repository: RohanExploit/VishwaGuru

Length of output: 382


Use SQLAlchemy .is_(True/False) instead of == True/False in boolean predicates

  • Line 387: FieldOfficerVisit.is_public == True
  • Lines 446-447: FieldOfficerVisit.within_geofence == True/False
💡 Suggested fix (line 387)
-            query = query.filter(FieldOfficerVisit.is_public == True)
+            query = query.filter(FieldOfficerVisit.is_public.is_(True))
💡 Suggested fix (lines 446-447)
-            func.sum(case((FieldOfficerVisit.within_geofence == True, 1), else_=0)).label('within_geofence_count'),
-            func.sum(case((FieldOfficerVisit.within_geofence == False, 1), else_=0)).label('outside_geofence_count')
+            func.sum(case((FieldOfficerVisit.within_geofence.is_(True), 1), else_=0)).label('within_geofence_count'),
+            func.sum(case((FieldOfficerVisit.within_geofence.is_(False), 1), else_=0)).label('outside_geofence_count')
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func.sum(case((FieldOfficerVisit.within_geofence == True, 1), else_=0)).label('within_geofence_count'),
func.sum(case((FieldOfficerVisit.within_geofence == False, 1), else_=0)).label('outside_geofence_count')
func.sum(case((FieldOfficerVisit.within_geofence.is_(True), 1), else_=0)).label('within_geofence_count'),
func.sum(case((FieldOfficerVisit.within_geofence.is_(False), 1), else_=0)).label('outside_geofence_count')
🧰 Tools
🪛 Ruff (0.15.13)

[error] 446-446: Avoid equality comparisons to True; use FieldOfficerVisit.within_geofence: for truth checks

Replace with FieldOfficerVisit.within_geofence

(E712)


[error] 447-447: Avoid equality comparisons to False; use not FieldOfficerVisit.within_geofence: for false checks

Replace with not FieldOfficerVisit.within_geofence

(E712)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/routers/field_officer.py` around lines 446 - 447, Replace boolean
equality comparisons that use == True/False with SQLAlchemy's .is_() for safe
boolean predicates: change FieldOfficerVisit.is_public == True to
FieldOfficerVisit.is_public.is_(True), and change the predicates inside the
case() expressions (FieldOfficerVisit.within_geofence == True and == False used
in the
func.sum(case(...)).label('within_geofence_count'/'outside_geofence_count')) to
FieldOfficerVisit.within_geofence.is_(True) and
FieldOfficerVisit.within_geofence.is_(False) respectively so the ORM generates
correct boolean SQL.

).first()

counts = db.query(
FieldOfficerVisit.verified_at.isnot(None).label("is_verified"),
FieldOfficerVisit.within_geofence,
func.count(FieldOfficerVisit.id)
).group_by(
FieldOfficerVisit.verified_at.isnot(None),
FieldOfficerVisit.within_geofence
).all()

total_visits = 0
verified_visits = 0
within_geofence_count = 0
outside_geofence_count = 0

for is_verified, within_geofence, count in counts:
c = count or 0
total_visits += c
if is_verified:
verified_visits += c
if within_geofence is True:
within_geofence_count += c
elif within_geofence is False:
outside_geofence_count += c

unique_officers = agg_stats.unique_officers or 0
average_distance = agg_stats.avg_distance
total_visits = int(stats.total_visits or 0)
verified_visits = int(stats.verified_visits or 0)
within_geofence_count = int(stats.within_geofence_count or 0)
outside_geofence_count = int(stats.outside_geofence_count or 0)
unique_officers = int(stats.unique_officers or 0)

average_distance = stats.avg_distance

# Round to 2 decimals if not None
if average_distance is not None:
Expand Down
Loading