Spaces:
Runtime error
Runtime error
Download src/api/session_runner.py from BattleFiven/ai-tester-platform: direct link, hf CLI and curl.
- Browser
- Download file 64.5 kB
-
https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/src/api/session_runner.py
- Command line
-
hf download hf://spaces/BattleFiven/ai-tester-platform/src/api/session_runner.py
-
curl -L -o session_runner.py https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/src/api/session_runner.py
64.5 kB
"""Session runner and event streaming utilities."""
from __future__ import annotations
import asyncio
import json
import os
import threading
import time
from collections import deque
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
from uuid import UUID
from sqlalchemy import text
from sqlalchemy.exc import OperationalError
from src.api.supabase_storage import SupabaseStorageManager, is_sb_ref
from src.core.ai_client import (
SESSION_PROMPT_CONFIG_KEY,
AIClient,
get_ai_client_from_env,
get_effective_session_prompt,
get_evaluator_client_from_env,
)
from src.core.rag_evaluator import RAGEvaluator
from src.core.test_engine import TestEngine
from src.core.tone_evaluator import ToneEvaluator
from src.core.turn_evaluator import TurnEvaluator
from src.db import BotRepository, PersonaRepository, ScenarioRepository, SessionRepository, get_db
from src.models import SessionStatus
from src.utils.env import env_bool, env_int
from src.utils.logging import get_logger
logger = get_logger(__name__)
class SessionEventBus:
"""In-memory pub/sub for session events."""
# Terminal statuses that trigger scheduled cleanup of the event history.
_TERMINAL_STATUSES = frozenset(
{
"completed",
"passed",
"failed",
"cancelled",
"manual_completed",
"completed_in_scope_pass",
"completed_in_scope_fail",
"completed_out_of_scope_fallback_pass",
"completed_out_of_scope_fallback_fail",
"completed_mixed",
}
)
def __init__(self) -> None:
self._subscribers: Dict[str, List[Tuple[asyncio.Queue, asyncio.AbstractEventLoop]]] = {}
# 2000 default copre ~100 turni × ~15 eventi/turno con margine; trascurabile come RAM.
replay_limit = os.getenv("SESSION_EVENT_REPLAY_LIMIT", "2000")
try:
self._history_limit = max(0, int(replay_limit))
except ValueError:
self._history_limit = 2000
self._history: Dict[str, deque[Dict[str, Any]]] = {}
self._cleanup_timers: Dict[str, threading.Timer] = {}
self._lock = threading.Lock()
async def subscribe(self, session_id: str, replay_last: Optional[int] = None) -> asyncio.Queue:
queue: asyncio.Queue = asyncio.Queue()
loop = asyncio.get_running_loop()
history: List[Dict[str, Any]] = []
with self._lock:
self._subscribers.setdefault(session_id, []).append((queue, loop))
if self._history_limit > 0:
history = list(self._history.get(session_id, []))
if replay_last is not None:
if replay_last <= 0:
history = []
else:
history = history[-replay_last:]
for event in history:
queue.put_nowait(dict(event))
return queue
def unsubscribe(self, session_id: str, queue: asyncio.Queue) -> None:
with self._lock:
subscribers = self._subscribers.get(session_id, [])
self._subscribers[session_id] = [
(q, loop) for (q, loop) in subscribers if q is not queue
]
if not self._subscribers[session_id]:
self._subscribers.pop(session_id, None)
def publish(self, session_id: str, event: Dict[str, Any]) -> None:
event_copy = dict(event)
with self._lock:
if self._history_limit > 0:
history = self._history.setdefault(
session_id, deque(maxlen=self._history_limit)
)
history.append(event_copy)
subscribers = list(self._subscribers.get(session_id, []))
for queue, loop in subscribers:
loop.call_soon_threadsafe(queue.put_nowait, dict(event_copy))
# On terminal events, schedule cleanup of the in-memory history so
# long-running processes don't accumulate per-session buffers.
# The retention window gives reconnecting clients time to fetch the
# final replay; 0 disables auto-cleanup.
if event_copy.get("type") == "status" and event_copy.get("status") in self._TERMINAL_STATUSES:
try:
retention_sec = int(os.getenv("SESSION_EVENT_RETENTION_SEC", "3600"))
except (TypeError, ValueError):
retention_sec = 3600
if retention_sec > 0:
self._schedule_history_cleanup(session_id, retention_sec)
def _schedule_history_cleanup(self, session_id: str, delay_sec: int) -> None:
"""Schedule a one-shot cleanup of this session's event history."""
with self._lock:
existing = self._cleanup_timers.pop(session_id, None)
if existing is not None:
try:
existing.cancel()
except Exception:
pass
def _cleanup() -> None:
with self._lock:
self._history.pop(session_id, None)
self._cleanup_timers.pop(session_id, None)
try:
logger.info(
"session_event_history_cleaned",
extra={"session_id": session_id, "delay_sec": delay_sec},
)
except Exception:
pass
timer = threading.Timer(float(delay_sec), _cleanup)
timer.daemon = True
with self._lock:
self._cleanup_timers[session_id] = timer
timer.start()
def get_recent_events(self, session_id: str, limit: int = 200) -> List[Dict[str, Any]]:
"""Return a copy of recent events for a session."""
bounded_limit = max(0, int(limit or 0))
with self._lock:
events = list(self._history.get(session_id, []))
if bounded_limit == 0:
return []
return [dict(item) for item in events[-bounded_limit:]]
def get_runtime_snapshot(self, session_id: str) -> Dict[str, Any]:
"""Build a lightweight runtime snapshot from replayable events."""
events = self.get_recent_events(session_id, limit=300)
if not events:
return {}
def _to_iso(ts: Any) -> Optional[str]:
if ts is None:
return None
try:
numeric = float(ts)
if numeric > 1_000_000_000_000:
numeric = numeric / 1000.0
return datetime.fromtimestamp(numeric).isoformat()
except Exception:
text = str(ts).strip()
return text or None
status = None
current_scenario = None
current_turn = 0
last_event_at = None
last_screenshot = None
last_logs: List[str] = []
for event in events:
last_event_at = _to_iso(event.get("ts")) or last_event_at
event_type = str(event.get("type") or "").strip().lower()
if event_type == "status":
status = str(event.get("status") or "").strip().lower() or status
elif event_type == "progress":
scenario_label = str(event.get("scenario") or "").strip()
persona_label = str(event.get("persona") or "").strip()
if scenario_label and persona_label:
current_scenario = f"{scenario_label} · {persona_label}"
elif scenario_label:
current_scenario = scenario_label
elif event_type == "chat" and str(event.get("sender") or "").strip().lower() == "bot":
current_turn += 1
elif event_type == "screenshot":
screenshot = str(
event.get("url") or event.get("path") or event.get("image") or ""
).strip()
if screenshot:
last_screenshot = screenshot
elif event_type == "log":
message = str(event.get("message") or "").strip()
if message:
last_logs.append(message)
if len(last_logs) > 3:
last_logs = last_logs[-3:]
if status in {"running", "stopping"}:
if current_scenario:
live_summary = f"In corso · {current_scenario} · Turno {current_turn}"
else:
live_summary = f"In corso · Turno {current_turn}"
elif status:
live_summary = f"Stato sessione: {status}"
else:
live_summary = "Sessione in inizializzazione"
return {
"status": status,
"current_turn": current_turn,
"current_scenario": current_scenario,
"last_event_at": last_event_at,
"live_summary": live_summary,
"last_screenshot": last_screenshot,
"last_logs": last_logs,
}
class SessionRunner:
"""Runs sessions in background threads and emits events."""
def __init__(self, event_bus: SessionEventBus) -> None:
self._event_bus = event_bus
self._threads: Dict[str, threading.Thread] = {}
self._stop_events: Dict[str, threading.Event] = {}
self._lock = threading.Lock()
def start(self, session_id: UUID) -> bool:
session_key = str(session_id)
with self._lock:
existing = self._threads.get(session_key)
if existing and existing.is_alive():
return False
self._stop_events[session_key] = threading.Event()
thread = threading.Thread(
target=self._run_session,
args=(session_key,),
daemon=True,
)
self._threads[session_key] = thread
thread.start()
return True
def stop(self, session_id: UUID) -> bool:
"""Request graceful stop for a running session."""
session_key = str(session_id)
with self._lock:
event = self._stop_events.get(session_key)
thread = self._threads.get(session_key)
is_running = bool(thread and thread.is_alive())
if not event:
return False
event.set()
self._event_bus.publish(session_key, {
"type": "status",
"status": "stopping",
"session_id": session_key,
"ts": int(time.time() * 1000),
})
self._event_bus.publish(session_key, {
"type": "log",
"level": "warning",
"message": "Stop requested. Waiting for current action to finish...",
"session_id": session_key,
"ts": int(time.time() * 1000),
})
return is_running
def is_running(self, session_id: UUID | str) -> bool:
session_key = str(session_id)
with self._lock:
thread = self._threads.get(session_key)
return bool(thread and thread.is_alive())
def recover_orphan_sessions(self) -> int:
"""Finalize sessions left in RUNNING after a process restart.
Why this exists:
Each session runs in a `daemon=True` thread. When the Python
process is killed (Render redeploy, OOM, manual restart), the
thread dies but the DB row stays in `running` forever — there's
no auto-resume. This method runs at lifespan startup to:
1. Find all sessions with status == RUNNING.
2. Skip those whose worker thread is still alive in this
process (shouldn't happen at boot, but defensive).
3. For each orphan: mark associated TestResult rows that are
still `in_progress` as `failed` with a clear reason, so
the UI doesn't show ghost in-flight scenarios.
4. Mark the TestSession itself as `failed` with
`error_message='process_restart_recovered'` and a
`metadata.crash_recovery=True` flag.
Why mark-as-failed instead of resume:
Resuming a Playwright + AI test session mid-run is brittle —
we'd need to recreate the browser, the conversation history,
the AI client mid-token. The chunks committed turn-by-turn
cover progress; the operator can re-launch the session for
the remaining scenarios manually. See docs/known-follow-ups.md
section "Test session recovery — option B (resume)" for the
future enhancement plan.
Idempotent: safe to call multiple times. Returns the number of
sessions finalized.
"""
recovered = 0
try:
db = get_db()
with db.get_session() as session:
repo = SessionRepository(session)
# `list_sessions(status=...)` filter not exposed; pull all
# then filter — sessions table is bounded, low cost.
sessions = repo.list_sessions()
orphan_sessions = [
s for s in sessions if s.status == SessionStatus.RUNNING
]
if not orphan_sessions:
return 0
with self._lock:
in_flight = set(self._threads.keys())
for ts in orphan_sessions:
sid = str(ts.id)
if sid in in_flight and self._threads[sid].is_alive():
# Worker still running in THIS process — leave alone.
continue
# 1) Mark in-progress TestResults as failed.
try:
results = repo.get_session_results(ts.id)
except Exception:
results = []
failed_results = 0
for result in results or []:
rstatus = str(getattr(result, "status", "") or "").lower()
if rstatus in ("pending", "in_progress", "running"):
try:
repo.update_result(result.id, {
"status": "failed",
"error_message": "process_restart_recovered",
})
failed_results += 1
except Exception:
logger.exception(
"session-recovery: failed to update result",
extra={"session_id": sid, "result_id": str(result.id)},
)
# 2) Mark the session as failed. Tag the recovery in
# `config` (JSON) so the UI / reports can distinguish a
# crash-recovered session from a real test failure.
# 2026-05-17: aggiunto calcolo verdict dai turn parziali
# già persistiti — prima di questo fix le session
# crash-recovered dopo container restart (frequente su
# HF Space free tier) mostravano AIS "—" nella tabella
# anche con N turn validi nel conversation_log. Adesso
# l'operatore vede subito i risultati parziali.
update_payload: Dict[str, Any] = {
"status": SessionStatus.FAILED.value,
"error_message": (
"process_restart_recovered: la sessione era "
"in esecuzione quando il processo è stato "
"riavviato. I turni completati prima del "
"riavvio sono preservati."
),
"completed_at": datetime.now(),
}
try:
verdict_fields = self._compute_verdict_fields_from_logs(
repo, sid
)
if verdict_fields:
update_payload.update(verdict_fields)
except Exception:
logger.exception(
"session-recovery: verdict computation failed (best-effort)",
extra={"session_id": sid},
)
try:
config = dict(getattr(ts, "config", None) or {})
config["crash_recovery"] = True
config["recovered_at"] = datetime.now().isoformat()
update_payload["config"] = config
repo.update_session(ts.id, update_payload)
session.commit()
logger.info(
"session-recovery: marked orphan session as failed",
extra={
"session_id": sid,
"results_failed": failed_results,
},
)
recovered += 1
except Exception:
session.rollback()
logger.exception(
"session-recovery: update_session failed",
extra={"session_id": sid},
)
except Exception as exc:
# Most common cause on a fresh install: the test_sessions table
# doesn't exist yet (init_db hasn't run for some reason). Log
# at debug + return 0 instead of stack-tracing — startup must
# not fail just because there are no sessions to recover.
msg = str(exc).lower()
if "no such table" in msg or "does not exist" in msg or "undefinedtable" in msg:
logger.debug(
"session-recovery: skipped (tables not ready yet): %s",
str(exc)[:200],
)
else:
logger.exception("session-recovery: top-level failure (non-fatal)")
return recovered
def _run_session(self, session_id: str) -> None:
output_root = Path("./output").resolve()
with self._lock:
stop_event = self._stop_events.get(session_id)
def should_stop() -> bool:
return bool(stop_event and stop_event.is_set())
def emit(event: Dict[str, Any]) -> None:
if "ts" not in event:
event["ts"] = int(time.time() * 1000)
event.setdefault("session_id", session_id)
path = event.pop("path", None)
if path:
event["url"] = self._to_output_url(output_root, path)
self._event_bus.publish(session_id, event)
def _scenario_goal_text(scenario: Any) -> str:
description = str(getattr(scenario, "description", "") or "").strip()
if description:
return description
success_criteria = getattr(scenario, "success_criteria", None)
expected_intent = (
str(getattr(success_criteria, "expected_intent", "") or "").strip()
if success_criteria
else ""
)
if expected_intent:
return expected_intent
return f"Complete scenario '{getattr(scenario, 'name', 'scenario')}'."
def _build_group_prompt(persona: Any, scenarios: List[Any]) -> str:
scenario_overview = []
for idx, scenario in enumerate(list(scenarios or [])[:12], start=1):
scenario_overview.append(
f"{idx}. {getattr(scenario, 'name', f'Scenario {idx}')}: {_scenario_goal_text(scenario)}"
)
if len(scenarios or []) > 12:
scenario_overview.append(
f"... plus {len(scenarios) - 12} additional scenario(s) in this run."
)
return AIClient.build_persona_system_prompt(
persona=persona,
scenario_overview=scenario_overview,
)
def log(message: str, level: str = "info") -> None:
emit({"type": "log", "level": level, "message": message})
log("Session runner started")
storage_mgr = SupabaseStorageManager.from_env()
uploaded_local: Dict[str, str] = {}
storage_initialized = False
def _resolve_local_artifact(value: Optional[str]) -> Optional[Path]:
if not value:
return None
raw = str(value).strip()
if not raw or is_sb_ref(raw) or raw.startswith("http://") or raw.startswith("https://"):
return None
# `/output/...` is a URL path. Map back to the local artifact directory.
if raw.startswith("/output/"):
candidate = output_root / raw[len("/output/") :]
if candidate.exists():
return candidate
# If an absolute/relative filesystem path exists, use it directly.
direct = Path(raw)
if direct.exists():
return direct
# If we have an absolute path that contains `/output/`, map to output_root.
marker = "/output/"
idx = raw.find(marker)
if idx >= 0:
candidate = output_root / raw[idx + len(marker) :]
if candidate.exists():
return candidate
return None
def _persist_artifact(value: Optional[str], result_id: str) -> Optional[str]:
nonlocal storage_initialized
if not value:
return value
raw = str(value).strip()
if not raw or is_sb_ref(raw) or not storage_mgr:
return value
local_file = _resolve_local_artifact(raw)
if not local_file:
return value
# Live preview is overwritten constantly; don't persist it as evidence.
if local_file.name.lower().startswith("live."):
return value
local_key = str(local_file.resolve())
if local_key in uploaded_local:
return uploaded_local[local_key]
if not storage_initialized:
try:
storage_mgr.ensure_bucket()
storage_initialized = True
except Exception as e:
log(f"Supabase Storage not available (screenshots will stay local): {e}", "warning")
return value
object_path = f"sessions/{session_id}/results/{result_id}/{local_file.name}"
try:
ref = storage_mgr.upload_file(local_file, object_path)
except Exception as e:
log(f"Failed to upload screenshot to Supabase Storage: {e}", "warning")
return value
uploaded_local[local_key] = ref
return ref
def _persist_result_artifacts(result: Any) -> None:
if not storage_mgr:
return
result_id = str(getattr(result, "id", "")) or "unknown"
# result.screenshot_urls
try:
urls = list(getattr(result, "screenshot_urls", []) or [])
if urls:
result.screenshot_urls = [_persist_artifact(u, result_id) for u in urls if u]
except Exception:
pass
# steps_results[*].screenshot
try:
for step in getattr(result, "steps_results", []) or []:
if isinstance(step, dict) and step.get("screenshot"):
step["screenshot"] = _persist_artifact(step.get("screenshot"), result_id)
except Exception:
pass
# scenario_results[*].turns[*].screenshot
try:
scenario_map = getattr(result, "scenario_results", None)
if isinstance(scenario_map, dict):
for scenario in scenario_map.values():
turns = scenario.get("turns") if isinstance(scenario, dict) else None
if not isinstance(turns, list):
continue
for turn in turns:
if isinstance(turn, dict) and turn.get("screenshot"):
turn["screenshot"] = _persist_artifact(turn.get("screenshot"), result_id)
except Exception:
pass
# conversation_log JSON string (optional; keeps traceability consistent)
try:
conv = getattr(result, "conversation_log", None)
if not conv:
return
data = json.loads(conv)
changed = False
if isinstance(data, list):
for turn in data:
if not isinstance(turn, dict) or not turn.get("screenshot"):
continue
new_val = _persist_artifact(turn.get("screenshot"), result_id)
if new_val != turn.get("screenshot"):
turn["screenshot"] = new_val
changed = True
if changed:
result.conversation_log = json.dumps(data, ensure_ascii=False, default=str)
except Exception:
pass
try:
# Initialize AI client based on configuration
try:
ai_client = get_ai_client_from_env()
log(f"AI Provider: {os.getenv('AI_PROVIDER', 'kimi')}")
except ValueError as e:
log(f"AI configuration error: {e}", "error")
self._mark_failed(session_id, str(e))
emit({"type": "status", "status": SessionStatus.FAILED.value})
return
is_render = bool(
os.getenv("RENDER")
or os.getenv("RENDER_SERVICE_ID")
or os.getenv("RENDER_EXTERNAL_HOSTNAME")
or os.getenv("RENDER_INSTANCE_ID")
)
headless = env_bool("BROWSER_HEADLESS", default=is_render)
log(f"Browser: headless={headless}")
db = get_db()
with db.get_session() as db_session:
session_repo = SessionRepository(db_session)
bot_repo = BotRepository(db_session)
scenario_repo = ScenarioRepository(db_session)
persona_repo = PersonaRepository(db_session)
session = session_repo.get_session(UUID(session_id))
if not session:
log(f"Session not found: {session_id}", "error")
return
# Apply optional per-session model overrides (temperature, max_tokens, top_p).
try:
session_config = getattr(session, "config", None) or {}
overrides = (
session_config.get("model_overrides")
if isinstance(session_config, dict)
else None
) or {}
if overrides:
applied = {}
if "temperature" in overrides and overrides["temperature"] is not None:
ai_client.temperature = float(overrides["temperature"])
applied["temperature"] = ai_client.temperature
if "max_tokens" in overrides and overrides["max_tokens"] is not None:
ai_client.max_tokens = int(overrides["max_tokens"])
applied["max_tokens"] = ai_client.max_tokens
if "top_p" in overrides and overrides["top_p"] is not None:
setattr(ai_client, "top_p", float(overrides["top_p"]))
applied["top_p"] = overrides["top_p"]
if applied:
log(f"Session model overrides applied: {applied}")
except Exception as exc: # pragma: no cover - defensive
log(f"Could not apply session model overrides: {exc}", "warning")
bot = bot_repo.get_by_id(session.bot_id)
if not bot:
log("Bot not found for session", "error")
session_repo.update_session(UUID(session_id), {
"status": SessionStatus.FAILED.value,
"error_message": "Bot not found",
})
db_session.commit()
emit({"type": "status", "status": SessionStatus.FAILED.value})
return
pairs = self._get_session_pairs(db_session, session_id, bot.id, scenario_repo, persona_repo, log)
if not pairs:
log("No scenarios/personas linked to this session.", "error")
session_repo.update_session(UUID(session_id), {
"status": SessionStatus.FAILED.value,
"error_message": "No scenarios/personas linked",
})
db_session.commit()
emit({"type": "status", "status": SessionStatus.FAILED.value})
return
# Backfill session-level prompt for legacy sessions.
session_config = dict(getattr(session, "config", None) or {})
if not get_effective_session_prompt(session_config):
first_persona = pairs[0][1]
scenario_overview: List[str] = []
seen_scenarios: List[str] = []
seen_ids = set()
for scenario, _ in pairs:
sid = str(getattr(scenario, "id", "") or "")
if sid in seen_ids:
continue
seen_ids.add(sid)
seen_scenarios.append(sid)
name = str(getattr(scenario, "name", "Scenario") or "Scenario").strip()
goal = str(getattr(scenario, "description", "") or "").strip()
if not goal:
success_criteria = getattr(scenario, "success_criteria", None)
goal = (
str(getattr(success_criteria, "expected_intent", "") or "").strip()
if success_criteria
else ""
)
if not goal:
goal = f"Complete scenario '{name}'."
scenario_overview.append(f"{len(scenario_overview)+1}. {name}: {goal}")
session_config[SESSION_PROMPT_CONFIG_KEY] = {
"generated_prompt": AIClient.build_persona_system_prompt(
persona=first_persona,
scenario_overview=scenario_overview,
),
"generated_at": datetime.now().isoformat(),
"persona_id": str(getattr(first_persona, "id", "") or ""),
"scenario_ids": seen_scenarios,
}
updated_session = session_repo.update_session(
UUID(session_id),
{"config": session_config},
)
if updated_session:
session = updated_session
log("Session prompt generated at runtime for this run.")
total_tests = len(pairs)
session_repo.update_session(UUID(session_id), {
"status": SessionStatus.RUNNING.value,
"started_at": datetime.now(),
"total_tests": total_tests,
"passed": 0,
"failed": 0,
"messages_sent": 0,
})
db_session.commit()
emit({"type": "status", "status": SessionStatus.RUNNING.value, "total_tests": total_tests})
log(f"Starting session with {total_tests} test(s).")
rag_eval = RAGEvaluator(ai_client)
tone_eval = ToneEvaluator(ai_client)
# Dialogic per-turn evaluator. Default ON so every turn gets an
# AIS / intent verdict; disable only for lightweight smoke runs.
# `LIVE_JUDGE_ENABLED` (post-session branch) vince su
# `ENABLE_TURN_EVALUATOR` (legacy). Quando il post-session
# judge è attivo (default su questo branch), il TurnEvaluator
# inline è disattivato → il judge gira batch a fine sessione
# via `_run_session_judge_sync`.
live_judge_raw = os.getenv("LIVE_JUDGE_ENABLED")
if live_judge_raw is not None:
turn_eval_enabled = live_judge_raw.strip().lower() in {"1", "true", "yes", "on"}
else:
turn_eval_enabled = env_bool("ENABLE_TURN_EVALUATOR", True)
turn_eval = None
if turn_eval_enabled:
try:
evaluator_client = get_evaluator_client_from_env()
except ValueError as exc:
log(f"Evaluator client config error: {exc}", "error")
evaluator_client = ai_client
is_dedicated = evaluator_client is not ai_client
turn_eval = TurnEvaluator(evaluator_client)
if is_dedicated:
log(
f"TurnEvaluator enabled with dedicated judge model "
f"({getattr(evaluator_client, 'model', 'unknown')})."
)
else:
log(
"TurnEvaluator enabled but reusing the generator AI client "
"(no EVALUATOR_* env vars). For higher-quality AIS labels, "
"configure a dedicated judge (e.g. EVALUATOR_PROVIDER=anthropic, "
"EVALUATOR_MODEL=claude-sonnet-4-6).",
"warning",
)
else:
log(
"TurnEvaluator disabled (ENABLE_TURN_EVALUATOR=false). "
"Turns will not carry an AIS verdict.",
"warning",
)
base_prompt_override = get_effective_session_prompt(getattr(session, "config", None))
if base_prompt_override:
log("Using session-level AI tester prompt override.")
output_dir = output_root / session_id
output_dir.mkdir(parents=True, exist_ok=True)
# Create a callback to save intermediate results
def save_intermediate_result(result):
"""Save partial results to database during test execution.
Retries solo su OperationalError (connection blip / pool issue).
Altre eccezioni si comportano come prima: log + continue.
"""
import logging
save_logger = logging.getLogger(__name__)
save_logger.info(f"save_intermediate_result called: session_id={result.session_id}, steps={len(result.steps_results) if result.steps_results else 0}")
max_retries = max(1, env_int("INTERMEDIATE_SAVE_MAX_RETRIES", 3))
base_ms = max(0, env_int("INTERMEDIATE_SAVE_RETRY_BASE_MS", 500))
for attempt in range(max_retries):
try:
db = get_db()
with db.get_session() as save_session:
save_repo = SessionRepository(save_session)
# Light lookup: solo l'id, evita SELECT * con
# conversation_log MB-size. Fix egress round 6.
existing_id = save_repo.get_result_id_by_session_and_scenario(
result.session_id, result.scenario_id, result.persona_id
)
if existing_id:
save_logger.info(f"Updating existing result: {existing_id}")
save_repo.update_result(existing_id, {
"conversation_log": result.conversation_log,
"scenario_results": result.scenario_results,
"steps_results": result.steps_results,
"screenshot_urls": result.screenshot_urls,
"total_steps": result.total_steps,
"passed_steps": result.passed_steps,
"failed_steps": result.failed_steps,
"status": "in_progress" if result.status == "pending" else result.status,
})
else:
save_logger.info(f"Creating new result for session={result.session_id}")
original_status = result.status
if result.status == "pending":
result.status = "in_progress"
save_repo.add_result(result)
result.status = original_status
save_session.commit()
save_logger.info(f"Saved intermediate result: {len(result.conversation_log or '')} chars, {len(result.steps_results or [])} steps")
return
except OperationalError as e:
if attempt >= max_retries - 1:
save_logger.error(
"intermediate_save_failed_after_retries",
extra={"attempts": attempt + 1, "error": str(e)[:240]},
)
log(f"Failed to save intermediate result after {attempt + 1} attempts: {e}", "warning")
return
backoff_sec = (base_ms / 1000.0) * (2 ** attempt)
save_logger.warning(
"intermediate_save_retry",
extra={"attempt": attempt + 1, "backoff_sec": backoff_sec, "error": str(e)[:240]},
)
time.sleep(backoff_sec)
except Exception as e:
save_logger.error(f"Failed to save intermediate result: {e}")
log(f"Failed to save intermediate result: {e}", "warning")
return
engine = TestEngine(
ai_client=ai_client,
rag_evaluator=rag_eval,
tone_evaluator=tone_eval,
turn_evaluator=turn_eval,
output_dir=str(output_dir),
event_handler=emit,
stop_requested=should_stop,
save_callback=save_intermediate_result,
max_messages=(session.max_turns or session.max_messages),
persona_system_prompt_override=base_prompt_override,
)
# Group pairs by persona - run all scenarios for each persona in one continuous test
persona_groups: Dict[str, List] = {}
for scenario, persona in pairs:
persona_key = str(persona.id)
if persona_key not in persona_groups:
persona_groups[persona_key] = {"persona": persona, "scenarios": []}
persona_groups[persona_key]["scenarios"].append(scenario)
passed = 0
failed = 0
response_times: List[int] = []
rag_scores: List[float] = []
tone_scores: List[float] = []
outcome_counters: Dict[str, int] = {
"in_scope_pass": 0,
"in_scope_fail": 0,
"out_of_scope_fallback_pass": 0,
"out_of_scope_fallback_fail": 0,
}
cancelled = False
session_messages_sent = 0
for persona_key, group in persona_groups.items():
if should_stop():
cancelled = True
log("Stop requested. Cancelling session...", "warning")
break
persona = group["persona"]
scenarios = group["scenarios"]
engine.persona_system_prompt_override = (
base_prompt_override or _build_group_prompt(persona, scenarios)
)
log(f"Running {len(scenarios)} scenario(s) as {persona.name}")
emit({
"type": "progress",
"scenario": f"{len(scenarios)} scenarios",
"persona": persona.name,
})
# Run all scenarios in one continuous conversation
result = engine.run_multi_scenario_test(
bot=bot,
scenarios=scenarios,
persona=persona,
session=session,
headless=headless,
)
session_messages_sent += engine.messages_sent_count
# Fast-fail su engine-level error (bug 2026-05-17:
# session bloccata "In esecuzione" indefinitamente).
# Quando l'engine torna result.status == "error"
# (es. browser startup failure permanente perché il
# bot URL non risponde, errore Playwright, ecc.), il
# result è degenere: scenario_id=None, conversation
# vuota, scenario_results_map vuoto. Continuare la
# logica downstream comporta query DB con scenario_id
# nullo, save_result che può fallire silenziosamente,
# e nessuna transizione di stato della session →
# rimane "running" finché non interviene
# recover_orphan_sessions al prossimo restart del
# processo. Solleviamo qui così l'outer `except`
# finalizza la session come FAILED con motivo chiaro.
if result.status == "error":
raise RuntimeError(
result.error_message
or "Test engine reported error status without detail"
)
if should_stop():
cancelled = True
if result.avg_response_time_ms is not None:
response_times.append(result.avg_response_time_ms)
if result.rag_faithfulness_avg is not None:
rag_scores.append(result.rag_faithfulness_avg)
if result.tone_match_avg is not None:
tone_scores.append(result.tone_match_avg)
result_scenario_passed = 0
result_scenario_failed = 0
scenario_results_map = result.scenario_results or {}
for scenario_info in scenario_results_map.values():
outcome_type = scenario_info.get("outcome_type")
if outcome_type in outcome_counters:
outcome_counters[outcome_type] += 1
if outcome_type and str(outcome_type).endswith("_pass"):
result_scenario_passed += 1
elif outcome_type and str(outcome_type).endswith("_fail"):
result_scenario_failed += 1
elif scenario_info.get("completed"):
result_scenario_passed += 1
else:
result_scenario_failed += 1
# Legacy fallback when scenario-level outcomes are not available.
if (result_scenario_passed + result_scenario_failed) == 0:
if result.status == "passed":
result_scenario_passed = 1
else:
result_scenario_failed = 1
passed += result_scenario_passed
failed += result_scenario_failed
self._normalize_result_paths(output_root, result)
_persist_result_artifacts(result)
# Check if result already exists (might have been created by save_callback).
# Light lookup: solo l'id, evita SELECT * con conversation_log MB-size.
existing_id = session_repo.get_result_id_by_session_and_scenario(
result.session_id, result.scenario_id, result.persona_id
)
if existing_id:
# Update existing result with final data
session_repo.update_result(existing_id, {
"status": result.status,
"conversation_log": result.conversation_log,
"scenario_results": result.scenario_results,
"steps_results": result.steps_results,
"screenshot_urls": result.screenshot_urls,
"total_steps": result.total_steps,
"passed_steps": result.passed_steps,
"failed_steps": result.failed_steps,
"avg_response_time_ms": result.avg_response_time_ms,
"rag_faithfulness_avg": result.rag_faithfulness_avg,
"tone_match_avg": result.tone_match_avg,
"error_message": result.error_message,
"completed_at": result.completed_at,
})
else:
# Create new result
session_repo.add_result(result)
session_repo.update_session(UUID(session_id), {
"passed": passed,
"failed": failed,
"messages_sent": session_messages_sent,
})
db_session.commit()
log(
(
f"Result: {result.status} | scenarios passed={result_scenario_passed} failed={result_scenario_failed}"
+ (f" | error={result.error_message}" if result.status == "error" and result.error_message else "")
),
"success" if result.status == "passed" else "error",
)
if cancelled:
break
avg_response = int(sum(response_times) / len(response_times)) if response_times else None
avg_rag = sum(rag_scores) / len(rag_scores) if rag_scores else None
avg_tone = sum(tone_scores) / len(tone_scores) if tone_scores else None
if cancelled:
# Use MANUAL_COMPLETED instead of CANCELLED to preserve data
session_repo.update_session(UUID(session_id), {
"status": SessionStatus.MANUAL_COMPLETED.value,
"completed_at": datetime.now(),
"passed": passed,
"failed": failed,
"messages_sent": session_messages_sent,
"avg_response_time_ms": avg_response,
"rag_faithfulness_avg": avg_rag,
"tone_match_avg": avg_tone,
"error_message": "Stopped manually - partial results saved",
})
db_session.commit()
log("Session stopped manually - partial results saved", "warning")
emit({"type": "status", "status": SessionStatus.MANUAL_COMPLETED.value, "passed": passed, "failed": failed})
else:
final_status = self._derive_completed_status(outcome_counters, passed, failed)
update_payload: Dict[str, Any] = {
"status": final_status,
"completed_at": datetime.now(),
"passed": passed,
"failed": failed,
"messages_sent": session_messages_sent,
"avg_response_time_ms": avg_response,
"rag_faithfulness_avg": avg_rag,
"tone_match_avg": avg_tone,
}
# If the AIS Wilson verdict is enabled, compute it now from
# the persisted conversation_log so the session row carries
# the modern verdict instead of the legacy goal-based one.
# The legacy `status` field stays mapped to a "completed_*"
# value (never raw "failed", which the UI shows as
# "Errore di esecuzione").
try:
from src.utils.feature_flags import wilson_session_verdict_enabled
from src.core.session_verdict import compute_session_verdict
if wilson_session_verdict_enabled():
results_for_verdict = session_repo.get_session_results(UUID(session_id))
verdict_turns: List[Dict[str, Any]] = []
for r in results_for_verdict:
raw_log = getattr(r, "conversation_log", None)
if not raw_log:
continue
try:
entries = json.loads(raw_log) if isinstance(raw_log, str) else raw_log
except Exception:
continue
if not isinstance(entries, list):
continue
for entry in entries:
if isinstance(entry, dict):
verdict_turns.append({
"correctness_label": entry.get("correctness_label"),
"human_override_label": None,
"intent_label": entry.get("intent_label"),
})
verdict_obj = compute_session_verdict(verdict_turns)
update_payload.update({
"verdict_label": verdict_obj["verdict"],
"verdict_p_hat": verdict_obj["p_hat"],
"verdict_lower_bound": verdict_obj["lower_bound"],
"verdict_upper_bound": verdict_obj["upper_bound"],
"verdict_threshold": verdict_obj["threshold"],
"verdict_n": verdict_obj["n"],
})
# Map AIS verdict → a "completed_*" status so the
# UI never shows "Errore di esecuzione" for a
# session that actually executed turns.
if verdict_turns:
if verdict_obj["verdict"] == "passed":
update_payload["status"] = SessionStatus.COMPLETED_IN_SCOPE_PASS.value
elif verdict_obj["verdict"] == "failed":
update_payload["status"] = SessionStatus.COMPLETED_IN_SCOPE_FAIL.value
else:
# inconclusive → keep the original
# _derive_completed_status (mixed/etc.)
pass
log(
f"AIS verdict (Wilson 95% CI): {verdict_obj['verdict']} "
f"p_hat={verdict_obj['p_hat']:.2f} n={verdict_obj['n']}"
)
except Exception as exc: # pragma: no cover
log(f"Could not compute AIS verdict at session end: {exc}", "warning")
session_repo.update_session(UUID(session_id), update_payload)
db_session.commit()
log(f"Session completed with status: {update_payload['status']}", "success")
emit({"type": "status", "status": update_payload["status"], "passed": passed, "failed": failed})
except Exception as exc:
if should_stop():
log("Session stopped manually - saving partial results", "warning")
self._mark_manual_completed(session_id, "Stopped manually - partial results saved")
emit({"type": "status", "status": SessionStatus.MANUAL_COMPLETED.value})
else:
log(f"Session error: {exc}", "error")
self._mark_failed(session_id, str(exc))
emit({"type": "status", "status": SessionStatus.FAILED.value})
finally:
# Cleanup browser if engine was created
if 'engine' in locals() and engine.browser:
engine.browser.cleanup()
with self._lock:
self._threads.pop(session_id, None)
self._stop_events.pop(session_id, None)
def _compute_verdict_fields_from_logs(
self,
session_repo: SessionRepository,
session_id: str,
) -> Dict[str, Any]:
"""Ricalcola i campi verdict (AIS + intent Wilson 95% CI) dai
conversation_log salvati nei TestResult della sessione.
Usato sia nel happy path (a fine sessione normale) sia nel
catch quando la session fallisce a metà — in questo modo la
tabella sessions mostra valori coerenti col detail anche per
session uscite in `failed`. Senza questo, `session.verdict_p_hat`
restava NULL e la tabella mostrava "0% / Inconclusiva" mentre
il detail ricalcolava al volo da `conversation_log`.
Ritorna un dict con i campi da merge nell'update_payload, o {}
se non c'è nulla da calcolare (no results / feature flag off /
eccezione).
"""
try:
from src.utils.feature_flags import wilson_session_verdict_enabled
from src.core.session_verdict import (
compute_session_verdict,
compute_intent_verdict,
)
if not wilson_session_verdict_enabled():
return {}
results_for_verdict = session_repo.get_session_results(UUID(session_id))
if not results_for_verdict:
return {}
verdict_turns: List[Dict[str, Any]] = []
for r in results_for_verdict:
raw_log = getattr(r, "conversation_log", None)
if not raw_log:
continue
try:
entries = json.loads(raw_log) if isinstance(raw_log, str) else raw_log
except Exception:
continue
if not isinstance(entries, list):
continue
for entry in entries:
if isinstance(entry, dict):
verdict_turns.append({
"correctness_label": entry.get("correctness_label"),
"human_override_label": None,
"intent_label": entry.get("intent_label"),
})
if not verdict_turns:
return {}
verdict_obj = compute_session_verdict(verdict_turns)
fields: Dict[str, Any] = {
"verdict_label": verdict_obj["verdict"],
"verdict_p_hat": verdict_obj["p_hat"],
"verdict_lower_bound": verdict_obj["lower_bound"],
"verdict_upper_bound": verdict_obj["upper_bound"],
"verdict_threshold": verdict_obj["threshold"],
"verdict_n": verdict_obj["n"],
}
# Intent verdict (Wilson sui soli intent_label).
try:
intent_obj = compute_intent_verdict(verdict_turns)
fields.update({
"intent_verdict_label": intent_obj["verdict"],
"intent_verdict_p_hat": intent_obj["p_hat"],
"intent_verdict_lower_bound": intent_obj["lower_bound"],
"intent_verdict_upper_bound": intent_obj["upper_bound"],
"intent_verdict_threshold": intent_obj["threshold"],
"intent_verdict_n": intent_obj["n"],
})
except Exception:
pass # intent verdict best-effort
return fields
except Exception:
return {}
def _mark_failed(self, session_id: str, error_message: str) -> None:
db = get_db()
with db.get_session() as db_session:
session_repo = SessionRepository(db_session)
update_payload: Dict[str, Any] = {
"status": SessionStatus.FAILED.value,
"error_message": error_message,
}
# Calcola verdict dai turni già salvati PRIMA di marcare failed,
# così la tabella sessions list mostra valori coerenti col detail
# anche per session uscite in errore (issue 2 fix 2026-05-14).
verdict_fields = self._compute_verdict_fields_from_logs(
session_repo, session_id
)
if verdict_fields:
update_payload.update(verdict_fields)
session_repo.update_session(UUID(session_id), update_payload)
db_session.commit()
def _mark_cancelled(self, session_id: str, message: str) -> None:
db = get_db()
with db.get_session() as db_session:
session_repo = SessionRepository(db_session)
session_repo.update_session(UUID(session_id), {
"status": SessionStatus.CANCELLED.value,
"completed_at": datetime.now(),
"error_message": message,
})
db_session.commit()
def _derive_completed_status(
self,
outcome_counters: Dict[str, int],
passed: int,
failed: int,
) -> str:
"""Derive final completed status from scenario outcome counters."""
in_scope_total = outcome_counters.get("in_scope_pass", 0) + outcome_counters.get("in_scope_fail", 0)
out_scope_total = outcome_counters.get("out_of_scope_fallback_pass", 0) + outcome_counters.get("out_of_scope_fallback_fail", 0)
if in_scope_total > 0 and out_scope_total > 0:
return SessionStatus.COMPLETED_MIXED.value
if in_scope_total > 0:
return (
SessionStatus.COMPLETED_IN_SCOPE_PASS.value
if outcome_counters.get("in_scope_fail", 0) == 0
else SessionStatus.COMPLETED_IN_SCOPE_FAIL.value
)
if out_scope_total > 0:
return (
SessionStatus.COMPLETED_OUT_OF_SCOPE_FALLBACK_PASS.value
if outcome_counters.get("out_of_scope_fallback_fail", 0) == 0
else SessionStatus.COMPLETED_OUT_OF_SCOPE_FALLBACK_FAIL.value
)
# Fallback for legacy sessions where detailed outcome is not available.
if failed == 0 and passed > 0:
return SessionStatus.COMPLETED.value
return SessionStatus.FAILED.value
def _mark_manual_completed(self, session_id: str, message: str) -> None:
"""Mark session as manually stopped but with partial results preserved."""
db = get_db()
with db.get_session() as db_session:
session_repo = SessionRepository(db_session)
session_repo.update_session(UUID(session_id), {
"status": SessionStatus.MANUAL_COMPLETED.value,
"completed_at": datetime.now(),
"error_message": message,
})
db_session.commit()
def _get_session_pairs(
self,
db_session,
session_id: str,
bot_id: UUID,
scenario_repo: ScenarioRepository,
persona_repo: PersonaRepository,
log,
) -> List[Tuple[Any, Any]]:
rows = db_session.execute(
text(
"SELECT scenario_id, persona_id FROM session_scenario_links WHERE session_id = :sid"
),
{"sid": session_id},
).fetchall()
pairs: List[Tuple[Any, Any]] = []
seen = set()
if rows:
for row in rows:
scenario_id = row[0]
persona_id = row[1]
key = (scenario_id, persona_id)
if key in seen:
continue
seen.add(key)
scenario = scenario_repo.get_by_id(UUID(scenario_id))
persona = persona_repo.get_by_id(UUID(persona_id))
if scenario and persona:
# Validate that scenario belongs to this bot
if str(scenario.bot_id) != str(bot_id):
log(f"Skipping scenario '{scenario.name}' - belongs to different bot", "warning")
continue
pairs.append((scenario, persona))
else:
scenarios = scenario_repo.list_all(bot_id=bot_id)
personas = persona_repo.list_all()
if scenarios and personas:
log("No explicit session links found. Using all scenarios/personas.", "warning")
for scenario in scenarios:
for persona in personas:
pairs.append((scenario, persona))
return pairs
@staticmethod
def _to_output_url(output_root: Path, path: str) -> str:
try:
rel = Path(path).resolve().relative_to(output_root)
return f"/output/{rel.as_posix()}"
except Exception:
return path
def _normalize_result_paths(self, output_root: Path, result) -> None:
normalized_screens = [self._to_output_url(output_root, p) for p in result.screenshot_urls]
result.screenshot_urls = normalized_screens
normalized_steps = []
for step in result.steps_results:
step = dict(step)
screenshot = step.get("screenshot")
if screenshot:
step["screenshot"] = self._to_output_url(output_root, screenshot)
normalized_steps.append(step)
result.steps_results = normalized_steps
if result.conversation_log:
try:
json.loads(result.conversation_log)
except Exception:
pass
session_event_bus = SessionEventBus()
session_runner = SessionRunner(session_event_bus)
"""Session runner and event streaming utilities."""
from __future__ import annotations
import asyncio
import json
import os
import threading
import time
from collections import deque
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
from uuid import UUID
from sqlalchemy import text
from sqlalchemy.exc import OperationalError
from src.api.supabase_storage import SupabaseStorageManager, is_sb_ref
from src.core.ai_client import (
SESSION_PROMPT_CONFIG_KEY,
AIClient,
get_ai_client_from_env,
get_effective_session_prompt,
get_evaluator_client_from_env,
)
from src.core.rag_evaluator import RAGEvaluator
from src.core.test_engine import TestEngine
from src.core.tone_evaluator import ToneEvaluator
from src.core.turn_evaluator import TurnEvaluator
from src.db import BotRepository, PersonaRepository, ScenarioRepository, SessionRepository, get_db
from src.models import SessionStatus
from src.utils.env import env_bool, env_int
from src.utils.logging import get_logger
logger = get_logger(__name__)
class SessionEventBus:
"""In-memory pub/sub for session events."""
# Terminal statuses that trigger scheduled cleanup of the event history.
_TERMINAL_STATUSES = frozenset(
{
"completed",
"passed",
"failed",
"cancelled",
"manual_completed",
"completed_in_scope_pass",
"completed_in_scope_fail",
"completed_out_of_scope_fallback_pass",
"completed_out_of_scope_fallback_fail",
"completed_mixed",
}
)
def __init__(self) -> None:
self._subscribers: Dict[str, List[Tuple[asyncio.Queue, asyncio.AbstractEventLoop]]] = {}
# 2000 default copre ~100 turni × ~15 eventi/turno con margine; trascurabile come RAM.
replay_limit = os.getenv("SESSION_EVENT_REPLAY_LIMIT", "2000")
try:
self._history_limit = max(0, int(replay_limit))
except ValueError:
self._history_limit = 2000
self._history: Dict[str, deque[Dict[str, Any]]] = {}
self._cleanup_timers: Dict[str, threading.Timer] = {}
self._lock = threading.Lock()
async def subscribe(self, session_id: str, replay_last: Optional[int] = None) -> asyncio.Queue:
queue: asyncio.Queue = asyncio.Queue()
loop = asyncio.get_running_loop()
history: List[Dict[str, Any]] = []
with self._lock:
self._subscribers.setdefault(session_id, []).append((queue, loop))
if self._history_limit > 0:
history = list(self._history.get(session_id, []))
if replay_last is not None:
if replay_last <= 0:
history = []
else:
history = history[-replay_last:]
for event in history:
queue.put_nowait(dict(event))
return queue
def unsubscribe(self, session_id: str, queue: asyncio.Queue) -> None:
with self._lock:
subscribers = self._subscribers.get(session_id, [])
self._subscribers[session_id] = [
(q, loop) for (q, loop) in subscribers if q is not queue
]
if not self._subscribers[session_id]:
self._subscribers.pop(session_id, None)
def publish(self, session_id: str, event: Dict[str, Any]) -> None:
event_copy = dict(event)
with self._lock:
if self._history_limit > 0: