Spaces:
Runtime error

File size: 8,713 Bytes
ed86a97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
"""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