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
42 changes: 16 additions & 26 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import json
import os
import io
import sys

# Add the project root to sys.path so we can import 'backend' modules
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
Expand Down Expand Up @@ -226,37 +227,23 @@ async def create_issue(
image: UploadFile = File(...),
db: Session = Depends(get_db)
):
try:
# Save the uploaded image
os.makedirs("data/uploads", exist_ok=True)
filename = f"{uuid.uuid4()}_{image.filename}"
file_location = f"data/uploads/{filename}"
# Save the uploaded image
os.makedirs("data/uploads", exist_ok=True)
filename = f"{uuid.uuid4()}_{image.filename}"
file_location = f"data/uploads/{filename}"

# Offload blocking file I/O to a thread
def save_file():
with open(file_location, "wb") as buffer:
shutil.copyfileobj(image.file, buffer)

# Offload blocking file I/O to a thread
def save_file():
with open(image_path, "wb") as buffer:
shutil.copyfileobj(image.file, buffer)
await asyncio.to_thread(save_file)

await asyncio.to_thread(save_file)
# Generate Action Plan (AI)
action_plan = await generate_action_plan(description, category, file_location)

# Offload blocking DB operations to a thread
def save_to_db():
new_issue = Issue(
description=description,
category=category,
image_path=image_path,
source="web"
)
db.add(new_issue)
db.commit()
db.refresh(new_issue)
return new_issue

new_issue = await asyncio.to_thread(save_to_db)

# Generate Action Plan (AI)
action_plan = await generate_action_plan(description, category, file_location)

db_issue = Issue(
description=description,
category=category,
Expand All @@ -267,6 +254,9 @@ def save_to_db():
db.add(db_issue)
db.commit()
db.refresh(db_issue)
return db_issue

new_issue = await asyncio.to_thread(save_to_db)

return {
"id": new_issue.id,
Expand Down
7 changes: 7 additions & 0 deletions backend/spatial_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,17 @@ def find_nearby_issues(
"""
nearby_issues = []

# Pre-filter using bounding box with 5% epsilon to optimize expensive haversine calculations
min_lat, max_lat, min_lon, max_lon = get_bounding_box(target_lat, target_lon, radius_meters * 1.05)

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.

P3: Bounding box pre-filter can silently drop valid nearby issues when the search crosses the 180th meridian. get_bounding_box subtracts/adds lon_offset from raw longitude without normalizing to [-180, 180], so near ±180° the box wraps incorrectly. For example, target_lon=179° with a large radius produces min_lon=172°, max_lon=186°, and an issue at -178° (2° away) fails the chained comparison and gets skipped. Consider normalizing the bounding box longitude range in get_bounding_box, or at least note the limitation. The PR default radius of 50m makes this very rare in practice; flagging for awareness.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/spatial_utils.py, line 80:

<comment>Bounding box pre-filter can silently drop valid nearby issues when the search crosses the 180th meridian. `get_bounding_box` subtracts/adds `lon_offset` from raw longitude without normalizing to [-180, 180], so near ±180° the box wraps incorrectly. For example, target_lon=179° with a large radius produces min_lon=172°, max_lon=186°, and an issue at -178° (2° away) fails the chained comparison and gets skipped. Consider normalizing the bounding box longitude range in `get_bounding_box`, or at least note the limitation. The PR default radius of 50m makes this very rare in practice; flagging for awareness.</comment>

<file context>
@@ -76,10 +76,17 @@ def find_nearby_issues(
     nearby_issues = []
 
+    # Pre-filter using bounding box with 5% epsilon to optimize expensive haversine calculations
+    min_lat, max_lat, min_lon, max_lon = get_bounding_box(target_lat, target_lon, radius_meters * 1.05)
+
     for issue in issues:
</file context>


for issue in issues:
if issue.latitude is None or issue.longitude is None:
continue

# Fast bounding box pre-filter check
if not (min_lat <= issue.latitude <= max_lat and min_lon <= issue.longitude <= max_lon):
continue

Comment on lines +79 to +89

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== backend/spatial_utils.py (relevant slice) =="
nl -ba backend/spatial_utils.py | sed -n '1,220p'

echo
echo "== Search for longitude normalization / antimeridian handling =="
rg -n "longitude|antimeridian|180|normalize|bounding box|haversine" backend tests . -g '!**/.git/**' || true

echo
echo "== File list for nearby spatial tests =="
fd -a -t f "test|spec" backend tests . || true

Repository: RohanExploit/VishwaGuru

Length of output: 249


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== backend/spatial_utils.py (relevant slice) =="
cat -n backend/spatial_utils.py | sed -n '1,220p'

echo
echo "== Search for longitude normalization / antimeridian handling =="
rg -n "longitude|antimeridian|180|normalize|bounding box|haversine" backend tests . -g '!**/.git/**' || true

echo
echo "== Files with tests/specs =="
fd -a -t f "test|spec" backend tests . || true

Repository: RohanExploit/VishwaGuru

Length of output: 50380


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== longitude validation contract =="
cat -n backend/schemas.py | sed -n '40,70p'
echo
cat -n backend/main_fixed.py | sed -n '315,335p'

echo
echo "== spatial test coverage =="
cat -n tests/test_spatial_deduplication.py | sed -n '1,220p'

echo
echo "== antimeridian edge-case probe =="
python3 - <<'PY'
import math

def get_bounding_box(lat, lon, radius_meters):
    R = 6378137.0
    effective_lat = max(min(lat, 89.9), -89.9)
    dlat = radius_meters / R
    dlon = radius_meters / (R * math.cos(math.pi * effective_lat / 180.0))
    lat_offset = dlat * 180.0 / math.pi
    lon_offset = dlon * 180.0 / math.pi
    return lat - lat_offset, lat + lat_offset, lon - lon_offset, lon + lon_offset

def haversine_distance(lat1, lon1, lat2, lon2):
    R = 6371000.0
    phi1, phi2 = math.radians(lat1), math.radians(lat2)
    dphi = math.radians(lat2 - lat1)
    dlambda = math.radians(lon2 - lon1)
    a = math.sin(dphi / 2)**2 + math.cos(phi1) * math.cos(phi2) * math.sin(dlambda / 2)**2
    return R * (2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)))

target_lat, target_lon, radius = 0.0, 179.9999, 50.0
issue_lat, issue_lon = 0.0, -179.9999
min_lat, max_lat, min_lon, max_lon = get_bounding_box(target_lat, target_lon, radius * 1.05)

print("bbox:", (min_lat, max_lat, min_lon, max_lon))
print("bbox_contains_issue:", min_lat <= issue_lat <= max_lat and min_lon <= issue_lon <= max_lon)
print("distance_m:", haversine_distance(target_lat, target_lon, issue_lat, issue_lon))
PY

Repository: RohanExploit/VishwaGuru

Length of output: 11117


Handle longitude ranges that cross the antimeridian. backend/spatial_utils.py:79-89 The bounding-box prefilter can drop valid nearby issues when the longitude window wraps past ±180° (for example, 179.9999 vs -179.9999), even though haversine_distance() would include them. Split or wrap the longitude check in that case, and add a regression test.

🤖 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/spatial_utils.py` around lines 79 - 89, Update the bounding-box
longitude filtering in the spatial query flow around get_bounding_box and the
issue loop to correctly handle ranges crossing the antimeridian, accepting
longitudes on either side of ±180° while preserving the latitude check and
normal filtering behavior. Add a regression test covering nearby coordinates
such as 179.9999 and -179.9999 that haversine_distance() considers within range.

distance = haversine_distance(
target_lat, target_lon,
issue.latitude, issue.longitude
Expand Down
Loading