tests/suites/test_openai_live_acceptance.py

"""Opt-in live acceptance of the public OpenAI Responses runtime.

The suite copies only config.yaml, isolates all XDG paths, and leaves auth loading
to the service. It never emits model output,
headers, provider IDs, or raw errors. Run only with ``--live-openai``.
"""

from __future__ import annotations

import json
import sqlite3
import subprocess
import tempfile
import time
from pathlib import Path

import pytest

from client import SocketClient
from conftest import BIN_AGENT, BIN_SERVICE, get_leaf_turn_ids

pytestmark = [pytest.mark.llm, pytest.mark.live_openai]

def _classify_create_error(frame: dict) -> str:
    """Classify local create_leaf validation; it is never provider evidence."""
    code = str(frame.get("code", "")).lower()
    if code == "invalid_model":
        return "model_not_configured"
    return f"local_prerequisite_{code or 'unknown'}"


def _preflight_outcome(results: dict[str, str], transport_events: list[dict]) -> tuple[str, list[str]]:
    """Summarize pre-provider checks without claiming HTTP/WS/auth activity."""
    if transport_events:
        return "preflight_transport_observed", []
    blocked = [f"{label}={status}" for label, status in results.items() if status != "pass"]
    if blocked:
        return "blocked", blocked
    return "pass", []


def _status_class(value: str) -> str:
    text = value.lower()
    if any(word in text for word in ("unauthorized", "authentication", "invalid_api_key", "oauth", "token expired")):
        return "auth_unavailable"
    if "model" in text and any(word in text for word in ("not found", "does not exist", "unsupported", "unknown")):
        return "model_unavailable"
    field_classes = {
        "prompt_cache_key": "request_rejected_prompt_cache_key",
        "parallel_tool_calls": "request_rejected_parallel_tool_calls",
        "tool_choice": "request_rejected_tool_choice",
        "additional_tools": "request_rejected_additional_tools",
        "client_metadata": "request_rejected_client_metadata",
        "reasoning.context": "request_rejected_reasoning_context",
        "all_turns": "request_rejected_reasoning_context",
        "max_output_tokens": "request_rejected_max_output_tokens",
        "encrypted_content": "request_rejected_encrypted_reasoning",
        "include": "request_rejected_include",
        "stream": "request_rejected_stream",
        "store": "request_rejected_store",
    }
    if any(word in text for word in ("invalid", "unsupported", "unknown", "unrecognized", "not allowed")):
        for field, classification in field_classes.items():
            if field in text:
                return classification
        return "request_rejected_invalid"
    if any(word in text for word in ("rate_limit", "rate limit", "too many requests")):
        return "rate_limited"
    if any(word in text for word in ("quota", "billing")):
        return "quota_unavailable"
    if any(word in text for word in ("websocket", "connection", "timeout", "timed out", "network")):
        return "transport_error"
    return "provider_error"


def _connect(daemon: dict, identity: str) -> SocketClient:
    client = SocketClient(daemon["socket_path"])
    client.connect()
    client.handshake(name=identity)
    return client


def _create_leaf(
    client: SocketClient, model: str, *, with_tools: bool = True, request_id: str = "phase7-create",
) -> tuple[str | None, str]:
    client.send({
        "type": "create_leaf", "cwd": "/tmp", "name": f"phase7-{request_id}", "model": model,
        "active_tools": (["buffer"] if with_tools else []), "active_plugins": [],
        "tools_explicit": True, "plugins_explicit": True,
        "autosubscribe": True, "request_id": request_id,
    })
    deadline = time.time() + 15
    while time.time() < deadline:
        frame = client.recv_frame(timeout=max(0.1, deadline - time.time()))
        if frame is None:
            break
        if frame.get("type") == "leaf_created":
            leaf_id = frame.get("leaf_id")
            # Live acceptance isolates transport/model behavior from configured
            # auto-title or other assistant/idle LLM triggers without editing
            # normal config. These are leaf-local runtime settings.
            for suffix, key in (
                ("assistant", "active_assistant_triggers"),
                ("idle", "active_idle_triggers"),
            ):
                config_request = f"{request_id}-{suffix}"
                client.send({
                    "type": "set_leaf_config", "leaf_id": leaf_id,
                    "key": key, "value": "[]", "request_id": config_request,
                })
                config_deadline = time.time() + 5
                configured = False
                while time.time() < config_deadline:
                    reply = client.recv_frame(timeout=max(0.1, config_deadline - time.time()))
                    if reply is None:
                        break
                    if reply.get("type") == "leaf_config_set" and reply.get("request_id") == config_request:
                        configured = True
                        break
                    if reply.get("type") == "error" and reply.get("request_id") == config_request:
                        return None, "local_prerequisite_trigger_override"
                if not configured:
                    return None, "local_prerequisite_trigger_override"
            return leaf_id, "pass"
        if frame.get("type") == "error":
            return None, _classify_create_error(frame)
    return None, "protocol_timeout"


def _leaf_tip(client: SocketClient, leaf_id: str, request_id: str) -> str | None:
    client.send({"type": "list_leaves", "request_id": f"{request_id}-tip"})
    deadline = time.time() + 10
    while time.time() < deadline:
        frame = client.recv_frame(timeout=max(0.1, deadline - time.time()))
        if frame is None:
            break
        if frame.get("type") != "leaf_list":
            continue
        for leaf in frame.get("leaves", []):
            if leaf.get("id") == leaf_id:
                return leaf.get("turn_id") or None
        return None
    return None


def _prompt(client: SocketClient, leaf_id: str, text: str, request_id: str) -> str:
    # Prompt starts asynchronously before prompt_accepted is sent, so a fast run
    # may finish first. A pre-subscribed observer's agent_start/agent_end pair is
    # the authoritative run lifecycle; origin RPC frames are diagnostic only.
    observer = SocketClient(client.socket_path)
    observer.connect()
    observer.handshake(name="phase7-observer", leaf_id=leaf_id)
    try:
        prompt = {
            "type": "prompt",
            "leaf_id": leaf_id,
            "turn": {"kind": "user", "content_type": "text", "content": text},
            "request_id": request_id,
        }
        parent_turn_id = _leaf_tip(client, leaf_id, request_id)
        if parent_turn_id is not None:
            prompt["parent_turn_id"] = parent_turn_id
        client.send(prompt)
        started = False
        pending_error = None
        initial_deadline = time.time() + 30
        run_deadline = initial_deadline
        while time.time() < run_deadline:
            origin = client.recv_frame(timeout=0.01)
            if origin is not None and origin.get("type") == "error" and origin.get("request_id") == request_id:
                pending_error = "prompt_rpc_" + _status_class(
                    f"{origin.get('code', '')} {origin.get('message', '')}"
                )
            frame = observer.recv_frame(timeout=min(1.0, max(0.1, run_deadline - time.time())))
            if frame is None:
                continue
            if frame.get("leaf_id") != leaf_id:
                continue
            if frame.get("type") == "agent_start":
                started = True
                run_deadline = time.time() + 600
                continue
            if frame.get("type") != "agent_end":
                continue
            reason = str(frame.get("reason", ""))
            if reason in {"error", "failed"}:
                return "observer_" + _status_class(str(frame.get("message", "")))
            return "pass"
        if not started and pending_error is not None:
            return pending_error
        return "protocol_timeout"
    finally:
        observer.close()


def _transport_events(log_path, offset: int) -> list[dict]:
    if not log_path.exists():
        return []
    with log_path.open("rb") as stream:
        stream.seek(offset)
        lines = stream.read().splitlines()
    events = []
    for line in lines:
        try:
            event = json.loads(line)
        except (UnicodeDecodeError, json.JSONDecodeError):
            continue
        if event.get("msg") == "OpenAI Responses transport request":
            events.append(event)
    return events


def _log_size(log_path) -> int:
    return log_path.stat().st_size if log_path.exists() else 0


def _transport_outcome(events: list[dict], expected: str, *, reconnect: bool = False) -> str:
    """Check secret-free public Responses telemetry, independent of model names."""
    if any(event.get("transport") != expected for event in events):
        return "unexpected_transport"
    if not events:
        return f"{expected}_not_observed"
    if expected == "http":
        return "pass"
    if not any(event.get("new_connection") is True and event.get("continuation") is False for event in events):
        return "full_context_reconnect_not_observed" if reconnect else "initial_full_context_not_observed"
    if not reconnect and not any(
        event.get("continuation") is True and event.get("new_connection") is False
        for event in events
    ):
        return "same_socket_continuation_not_observed"
    return "pass"


def _preflight_models(daemon: dict, model_refs: dict[str, str]) -> tuple[dict[str, str], list[dict]]:
    """Validate configured refs with create_leaf only, before any provider I/O."""
    start = _log_size(daemon["log_path"])
    client = _connect(daemon, "phase7-preflight")
    results = {}
    try:
        for index, (label, model_ref) in enumerate(model_refs.items()):
            _, results[label] = _create_leaf(
                client, model_ref, with_tools=False, request_id=f"phase7-preflight-{index}",
            )
    finally:
        client.close()
    return results, _transport_events(daemon["log_path"], start)


def _require_preflight(daemon: dict, model_refs: dict[str, str], option_hint: str) -> None:
    results, events = _preflight_models(daemon, model_refs)
    outcome, blocked = _preflight_outcome(results, events)
    if outcome == "preflight_transport_observed":
        pytest.fail("local model preflight unexpectedly emitted transport telemetry", pytrace=False)
    if outcome == "blocked":
        pytest.skip(
            "external prerequisite: configured model refs required; "
            + ", ".join(blocked)
            + f"; map normal configured refs with {option_hint}"
        )


def _tool_result_count(db_path, leaf_id: str) -> int:
    with sqlite3.connect(str(db_path)) as db:
        turn_ids = get_leaf_turn_ids(db, leaf_id)
        if not turn_ids:
            return 0
        marks = ",".join("?" for _ in turn_ids)
        return db.execute(
            f"SELECT count(*) FROM turns WHERE id IN ({marks}) "
            "AND kind='tool_result' AND tool_name='buffer' AND state='sent'",
            turn_ids,
        ).fetchone()[0]


def _buffer_read_completed(db_path, leaf_id: str, marker: str) -> bool:
    """Require a successful durable read, not a model-dependent call count."""
    with sqlite3.connect(str(db_path)) as db:
        turn_ids = get_leaf_turn_ids(db, leaf_id)
        if not turn_ids:
            return False
        marks = ",".join("?" for _ in turn_ids)
        rows = db.execute(
            f"SELECT c.content FROM turns t JOIN turn_content c ON c.id=t.content_id "
            f"WHERE t.id IN ({marks}) AND t.kind='tool_result' "
            "AND t.tool_name='buffer' AND t.state='sent'",
            turn_ids,
        ).fetchall()
    return any(marker in (content or "") for (content,) in rows)


def _restart(daemon: dict) -> str:
    result = subprocess.run(
        [str(BIN_AGENT), "--no-autolaunch", "--stop"],
        capture_output=True, timeout=10,
    )
    old_proc = daemon["proc"]
    try:
        old_proc.wait(timeout=10)
    except subprocess.TimeoutExpired:
        old_proc.kill()
        old_proc.wait()
        return "unclean_daemon_stop"
    if result.returncode != 0:
        return "unclean_daemon_stop"

    proc = subprocess.Popen(
        [str(BIN_SERVICE)], cwd=str(daemon["runtime_dir"]),
        stdout=subprocess.PIPE, stderr=subprocess.PIPE,
    )
    daemon["proc"] = proc
    for _ in range(100):
        if daemon["socket_path"].exists():
            time.sleep(0.1)
            return "pass"
        if proc.poll() is not None:
            return "daemon_restart_failed"
        time.sleep(0.1)
    return "daemon_restart_timeout"


def _exercise_model(
    daemon: dict, model_ref: str,
    expected_transport: str = "websocket",
) -> str:
    start = _log_size(daemon["log_path"])
    client = _connect(daemon, "live-openai")
    try:
        leaf_id, status = _create_leaf(client, model_ref)
        if status != "pass" or leaf_id is None:
            return status

        status = _prompt(client, leaf_id, "Reply briefly. Do not call any tool.", "phase7-no-tool")
        if status != "pass":
            return status
        db_path = daemon["state_dir"] / "ez-agent" / "ez-agent.db"
        if _tool_result_count(db_path, leaf_id) != 0:
            return "unexpected_tool_call"

        marker = "live-openai-buffer-read-ok"
        with tempfile.TemporaryDirectory(prefix="ez-agent-live-", dir="/tmp") as directory:
            test_file = Path(directory) / "buffer.txt"
            test_file.write_text(marker + "\n")
            status = _prompt(
                client, leaf_id,
                "Read this harmless local test file using buffer once: "
                f'operator="read", buffer_name="file:{test_file}". '
                "Keep the exact file: namespace and absolute path. Then reply briefly.",
                "phase7-tool",
            )
        if status != "pass":
            return status
        if not _buffer_read_completed(db_path, leaf_id, marker):
            return "successful_buffer_read_not_observed"

        status = _prompt(client, leaf_id, "Give a brief follow-up without calling a tool.", "phase7-followup")
        if status != "pass":
            return status
    finally:
        client.close()

    events = _transport_events(daemon["log_path"], start)
    status = _transport_outcome(events, expected_transport)
    if status != "pass":
        return status

    if _restart(daemon) != "pass":
        return "unclean_daemon_restart"
    reconnect_start = _log_size(daemon["log_path"])
    client = _connect(daemon, "live-openai-reconnect")
    try:
        status = _prompt(client, leaf_id, "Give one final brief follow-up without a tool.", "phase7-reconnect")
    finally:
        client.close()
    if status != "pass":
        return status
    reconnect = _transport_events(daemon["log_path"], reconnect_start)
    return _transport_outcome(reconnect, expected_transport, reconnect=True)


def test_public_responses_model_ref(live_openai_daemon, live_openai_case):
    """Every configured ref exercises the same encoder, tool loop, and reconnect."""
    model_ref, transport = live_openai_case
    _require_preflight(
        live_openai_daemon, {"model_ref": model_ref},
        "--live-openai-{subscription,api,http}-ref",
    )
    status = _exercise_model(live_openai_daemon, model_ref, expected_transport=transport)
    if status != "pass":
        pytest.fail(f"live Responses acceptance: {status}", pytrace=False)