Spaces:
Runtime error
Runtime error
Download src/integrations/openproject/context_loader.py from BattleFiven/ai-tester-platform: direct link, hf CLI and curl.
- Browser
- Download file 8.71 kB
-
https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/src/integrations/openproject/context_loader.py
- Command line
-
hf download hf://spaces/BattleFiven/ai-tester-platform/src/integrations/openproject/context_loader.py
-
curl -L -o context_loader.py https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/src/integrations/openproject/context_loader.py
8.71 kB
| """Load TurnContext + screenshot bytes for a given BugTicket. | |
| Reads the conversation_log JSON of TestResultModel (the live screenshot | |
| references — local paths or sb:// URIs) and resolves them into bytes ready | |
| to be POSTed as multipart attachments to OpenProject. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| from pathlib import Path | |
| from typing import Any, Dict, List, Optional, Tuple | |
| from sqlalchemy.orm import Session | |
| from src.api.supabase_storage import SupabaseStorageManager, is_sb_ref | |
| from src.db.models import BotModel, TestResultModel, TestSessionModel | |
| from src.integrations.openproject.payload_builder import TurnContext | |
| from src.models import BugTicket | |
| from src.utils.logging import get_logger | |
| logger = get_logger(__name__) | |
| def _parse_log(raw: Any) -> List[Dict[str, Any]]: | |
| if not raw: | |
| return [] | |
| try: | |
| entries = json.loads(raw) if isinstance(raw, str) else raw | |
| except Exception: | |
| return [] | |
| if not isinstance(entries, list): | |
| return [] | |
| return [e for e in entries if isinstance(e, dict)] | |
| def _find_turn_entry( | |
| results: List[TestResultModel], turn_number: Optional[int], result_id: Optional[str] | |
| ) -> Optional[Tuple[TestResultModel, Dict[str, Any]]]: | |
| for r in results: | |
| if result_id and str(r.id) != str(result_id): | |
| continue | |
| for entry in _parse_log(r.conversation_log): | |
| try: | |
| t = int(entry.get("turn")) | |
| except (TypeError, ValueError): | |
| continue | |
| if turn_number is None or t == turn_number: | |
| return (r, entry) | |
| return None | |
| def load_turn_context_for_bug(db: Session, bug: BugTicket) -> TurnContext: | |
| """Build a TurnContext from the bug's session/result/turn pointers. | |
| Returns a partially-populated TurnContext if the data is no longer | |
| available (deleted session, missing log) — never raises. | |
| """ | |
| ctx = TurnContext( | |
| session_id=bug.session_id, | |
| result_id=bug.result_id, | |
| turn_number=bug.interaction_turn_number, | |
| bot_version=bug.bot_version_at_creation, | |
| ) | |
| if not bug.session_id: | |
| return ctx | |
| session_row = ( | |
| db.query(TestSessionModel).filter(TestSessionModel.id == str(bug.session_id)).first() | |
| ) | |
| if session_row: | |
| ctx.session_name = session_row.session_name | |
| if session_row.bot_id: | |
| bot_row = db.query(BotModel).filter(BotModel.id == str(session_row.bot_id)).first() | |
| if bot_row: | |
| ctx.bot_name = bot_row.name | |
| results = _load_results_for_bug_minimal(db, bug) | |
| found = _find_turn_entry(results, bug.interaction_turn_number, bug.result_id) | |
| if not found: | |
| return ctx | |
| _result_row, entry = found | |
| ctx.scenario_name = entry.get("scenario_name") or entry.get("subscenario_name") | |
| # Effective label = override (if any) ∪ engine label. | |
| ctx.effective_label = entry.get("correctness_label") | |
| ctx.correctness_reasoning = entry.get("correctness_reasoning") | |
| ctx.user_message = entry.get("user_message") | |
| ctx.bot_response = entry.get("bot_response") | |
| return ctx | |
| def _load_results_for_bug_minimal( | |
| db: Session, bug: BugTicket | |
| ) -> List[TestResultModel]: | |
| """Carica i TestResult necessari per arricchire un bug context. | |
| Fix egress 2026-05-22: prima caricava `SELECT *` su tutta la session | |
| (incluso `screenshot_urls` JSON, `steps_results` JSON, `scenario_results`). | |
| Solo `id` + `conversation_log` servono qui — il loop in | |
| `_find_turn_entry` legge solo quei due campi per cercare il turn. | |
| Inoltre: se il bug ha già un `result_id` valorizzato, restringiamo la | |
| query al singolo result (vs SELECT * su tutta la session). Su | |
| pg_stat_statements: il retry loop OpenProject genera 293+ calls in | |
| pochi minuti — questa è la singola query dominante post-fix round 2. | |
| """ | |
| # Minimal columns: bastano id + conversation_log a _find_turn_entry. | |
| base_q = db.query( | |
| TestResultModel.id, | |
| TestResultModel.conversation_log, | |
| ).filter(TestResultModel.session_id == str(bug.session_id)) | |
| # Filtro mirato: se conosciamo il result_id specifico, evitiamo di | |
| # caricare le altre N-1 row con il loro conversation_log. | |
| if bug.result_id: | |
| base_q = base_q.filter(TestResultModel.id == str(bug.result_id)) | |
| # SQLAlchemy ritorna Row (tuple-like). Convertiamo in pseudo-objects | |
| # con i 2 attributi che `_find_turn_entry` legge (`id`, | |
| # `conversation_log`). Niente Pydantic conversion — non serve. | |
| class _MinimalRow: | |
| __slots__ = ("id", "conversation_log") | |
| def __init__(self, row_id: str, log: Any) -> None: | |
| self.id = row_id | |
| self.conversation_log = log | |
| return [_MinimalRow(str(r.id), r.conversation_log) for r in base_q.all()] | |
| def _find_screenshot_ref_for_bug(db: Session, bug: BugTicket) -> Optional[str]: | |
| if not bug.session_id: | |
| return None | |
| # Stesso fix egress di load_turn_context_for_bug — query mirata | |
| # (id + conversation_log) anziché SELECT *. | |
| results = _load_results_for_bug_minimal(db, bug) | |
| found = _find_turn_entry(results, bug.interaction_turn_number, bug.result_id) | |
| if not found: | |
| return None | |
| _r, entry = found | |
| ref = entry.get("screenshot") | |
| return str(ref) if ref else None | |
| class ScreenshotProvider: | |
| """Resolve a turn screenshot ref into raw bytes for upload.""" | |
| def __init__(self, *, max_bytes: int = 26_214_400): | |
| self._max_bytes = max_bytes | |
| self._storage: Optional[SupabaseStorageManager] = SupabaseStorageManager.from_env() | |
| def get_bytes_for_bug( | |
| self, db: Session, bug: BugTicket | |
| ) -> Optional[Tuple[bytes, str, str]]: | |
| """Return (bytes, filename, content_type) or None when unavailable. | |
| Returns None — without raising — when the screenshot is missing, | |
| the file no longer exists, or it exceeds the configured size cap. | |
| """ | |
| ref = _find_screenshot_ref_for_bug(db, bug) | |
| if not ref: | |
| return None | |
| try: | |
| if is_sb_ref(ref): | |
| if not self._storage: | |
| logger.warning( | |
| "openproject_no_supabase_storage_for_screenshot", | |
| extra={"component": "openproject", "bug_id": bug.id, "ref": ref}, | |
| ) | |
| return None | |
| content, content_type = self._storage.download_bytes(ref) | |
| # Filename: take last path segment from sb://bucket/path/to/file.png | |
| filename = ref.rsplit("/", 1)[-1] or f"turn_{bug.interaction_turn_number}.png" | |
| else: | |
| path = Path(ref) | |
| if not path.exists() or not path.is_file(): | |
| logger.warning( | |
| "openproject_screenshot_local_missing", | |
| extra={"component": "openproject", "bug_id": bug.id, "path": str(path)}, | |
| ) | |
| return None | |
| size = path.stat().st_size | |
| if self._max_bytes and size > self._max_bytes: | |
| logger.warning( | |
| "openproject_screenshot_too_big", | |
| extra={ | |
| "component": "openproject", | |
| "bug_id": bug.id, | |
| "size": size, | |
| "max_bytes": self._max_bytes, | |
| }, | |
| ) | |
| return None | |
| content = path.read_bytes() | |
| filename = path.name | |
| ext = path.suffix.lower().lstrip(".") | |
| content_type_map = { | |
| "png": "image/png", | |
| "jpg": "image/jpeg", | |
| "jpeg": "image/jpeg", | |
| "webp": "image/webp", | |
| } | |
| content_type = content_type_map.get(ext, "application/octet-stream") | |
| except Exception as exc: # defensive: never let a bad ref break the sync | |
| logger.warning( | |
| "openproject_screenshot_load_failed", | |
| extra={"component": "openproject", "bug_id": bug.id, "error": str(exc)[:200]}, | |
| ) | |
| return None | |
| if self._max_bytes and len(content) > self._max_bytes: | |
| logger.warning( | |
| "openproject_screenshot_bytes_too_big", | |
| extra={ | |
| "component": "openproject", | |
| "bug_id": bug.id, | |
| "size": len(content), | |
| "max_bytes": self._max_bytes, | |
| }, | |
| ) | |
| return None | |
| return content, filename, content_type | |