Skip to content

OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.

Python
40.3 KB
Raw Blame
"""watsonx.ai on a Cloud Pak for Data cluster, routed through LiteLLM's watsonx provider."""

import os
from types import SimpleNamespace
from typing import Any

import pytest

import config.model_providers as model_providers
from config.config_manager import (
    AnthropicConfig,
    GenericProviderConfig,
    OllamaConfig,
    OpenAIConfig,
    ProvidersConfig,
    WatsonXConfig,
)
from enhancements.providers.watsonx import onprem as watsonx_onprem
from services import model_catalog
from services.llm_gateway import resolve_call, split_model_id

PROVIDER = watsonx_onprem.PROVIDER_KEY


@pytest.fixture(autouse=True)
def _reload_provider_config():
    model_providers.reload()
    yield
    model_providers.reload()


def _providers(**credentials) -> ProvidersConfig:
    return ProvidersConfig(
        openai=OpenAIConfig(),
        anthropic=AnthropicConfig(),
        watsonx=WatsonXConfig(),
        ollama=OllamaConfig(),
        custom={PROVIDER: GenericProviderConfig(credentials=dict(credentials), configured=True)},
    )


def _chat_api_params(params: dict[str, Any], model: str):
    """Call the Watsonx chat module's bound parameter helper.

    LiteLLM renamed this private helper to ``get_api_params`` in 1.106. Test
    the actual chat call site so the compatibility patch works across both
    layouts rather than importing either private spelling directly.
    """
    from litellm.llms.watsonx.chat import handler

    legacy_helper_name = "_get_api_params"
    get_api_params = getattr(handler, "get_api_params", None) or getattr(
        handler, legacy_helper_name
    )
    return get_api_params(params=params, model=model)


def test_zen_api_key_is_the_base64_cpd_docs_describe() -> None:
    # `echo "<username>:<apikey>" | base64`, which is what the cluster expects
    # after `Authorization: ZenApiKey `.
    assert watsonx_onprem.zen_api_key("cpduser", "APIKEY") == "Y3BkdXNlcjpBUElLRVk="


@pytest.mark.parametrize("username, api_key", [("", "APIKEY"), ("cpduser", ""), (None, None)])
def test_a_half_filled_form_yields_no_zen_key(username, api_key) -> None:
    """Better no credential than one that looks valid and 401s on first use."""
    assert watsonx_onprem.zen_api_key(username, api_key) == ""


def test_username_never_reaches_serializable_credentials() -> None:
    """Credential data stays serializable; runtime transport remains call-local."""
    stored = {
        "api_base": "https://cpd.example.com",
        "username": "cpduser",
        "api_key": "APIKEY",
    }
    credentials = watsonx_onprem.litellm_credentials(stored)
    client = watsonx_onprem.litellm_runtime_kwargs(stored)["client"]

    assert "username" not in credentials
    assert "ssl_verify" not in credentials
    assert "client" not in credentials
    assert client.ssl_verify is True
    assert client is watsonx_onprem.litellm_runtime_kwargs(stored)["client"]
    assert credentials["api_base"] == "https://cpd.example.com"
    # Both, and the same value: the embeddings path refuses the call outright
    # when api_key is unset, and builds its auth header from zen_api_key.
    assert credentials["zen_api_key"] == "Y3BkdXNlcjpBUElLRVk="
    assert credentials["api_key"] == "Y3BkdXNlcjpBUElLRVk="


def test_a_pasted_zen_key_is_used_as_given() -> None:
    credentials = watsonx_onprem.litellm_credentials(
        {"api_base": "https://cpd.example.com", "zen_api_key": "cHJlOmVuY29kZWQ="}
    )

    assert credentials["zen_api_key"] == "cHJlOmVuY29kZWQ="
    assert credentials["api_key"] == "cHJlOmVuY29kZWQ="


def test_an_api_key_with_no_username_authenticates_to_nothing() -> None:
    """Username is optional on the form, and leaving it blank used to fail silently.

    A Cloud Pak for Data API key is not a bearer token — the cluster trades a
    username *and* a key for one. Sending the raw key got a 401 that read as bad
    credentials rather than incomplete ones, and the model listing then fell
    back to the configured list with nothing on screen to say why.
    """
    stored = {"api_base": "https://cpd.example.com", "api_key": "APIKEY"}

    # Still handed to LiteLLM, which is free to make its own attempt with it.
    assert watsonx_onprem.litellm_credentials(stored)["api_key"] == "APIKEY"
    assert "zen_api_key" not in watsonx_onprem.litellm_credentials(stored)
    # But OpenRAG's own calls send no header, so the health check reports
    # missing credentials instead of the cluster reporting bad ones.
    assert watsonx_onprem.auth_header(stored) == ""
    assert watsonx_onprem.auth_header({**stored, "username": "cpduser"}).startswith("ZenApiKey ")


def test_a_deployment_scope_is_passed_through_untouched() -> None:
    credentials = watsonx_onprem.litellm_credentials(
        {
            "api_base": "https://cpd.example.com",
            "username": "cpduser",
            "api_key": "APIKEY",
            "space_id": "space-1",
            "project_id": "proj-1",
        }
    )

    assert credentials["space_id"] == "space-1"
    assert credentials["project_id"] == "proj-1"


def test_credential_values_translates_the_stored_form_as_data() -> None:
    from utils import provider_health_cache

    providers = _providers(api_base="https://cpd.example.com", username="cpduser", api_key="APIKEY")

    credentials = providers.credential_values(PROVIDER)
    assert credentials == {
        "api_base": "https://cpd.example.com",
        "zen_api_key": "Y3BkdXNlcjpBUElLRVk=",
        "api_key": "Y3BkdXNlcjpBUElLRVk=",
    }
    provider_health_cache.cache_key(
        provider=PROVIDER,
        embedding_provider=PROVIDER,
        test_completion=False,
        llm_model="model",
        embedding_model="embedding",
        endpoint=None,
        project_id=None,
        api_key=None,
        credentials=credentials,
    )


def test_pending_credentials_rebuilds_the_zen_key_from_a_submitted_change() -> None:
    """Validation runs before the write, on the union of stored and submitted.

    Merging after the translation would validate a new API key against a Zen
    key still built from the old one.
    """
    providers = _providers(api_base="https://cpd.example.com", username="cpduser", api_key="OLDKEY")

    pending = providers.pending_credentials(PROVIDER, {"api_key": "NEWKEY"})

    assert pending["zen_api_key"] == watsonx_onprem.zen_api_key("cpduser", "NEWKEY")
    assert pending["api_base"] == "https://cpd.example.com"


def test_the_gateway_routes_it_as_watsonx() -> None:
    """`watsonx_onprem/<model>` is not a prefix LiteLLM can resolve."""
    config = SimpleNamespace(
        providers=_providers(
            api_base="https://cpd.example.com", username="cpduser", api_key="APIKEY"
        ),
        agent=SimpleNamespace(llm_model="", llm_provider="openai"),
        knowledge=SimpleNamespace(embedding_model="", embedding_provider="openai"),
    )

    litellm_model, provider, credentials = resolve_call(
        f"{PROVIDER}:ibm/granite-3-3-8b-instruct", kind="chat", config=config
    )

    assert litellm_model == "watsonx/ibm/granite-3-3-8b-instruct"
    # The OpenRAG key is what the caller and the credential store still see.
    assert provider == PROVIDER
    assert credentials["zen_api_key"] == "Y3BkdXNlcjpBUElLRVk="
    assert "client" not in credentials


def test_the_alias_is_routable_so_ids_are_not_billed_to_the_default_provider() -> None:
    assert model_catalog.is_known_provider(PROVIDER)
    assert model_catalog.litellm_provider_key(PROVIDER) == "watsonx"
    assert model_catalog.litellm_provider_key("openai") == "openai"


def test_it_ships_on_prem_and_never_in_saas(monkeypatch) -> None:
    """on_prem is the mode it exists for; SaaS is the one it must never reach.

    Nothing is asserted about `oss`: that row gets flipped on for local testing
    the way `azure_ai`'s is, and a test that pins it only breaks the next person
    who needs the card in their dev stack.
    """
    monkeypatch.setenv("OPENRAG_RUN_MODE", "on_prem")
    assert PROVIDER in model_providers.visible_provider_keys()

    monkeypatch.setenv("OPENRAG_RUN_MODE", "saas")
    assert PROVIDER not in model_providers.visible_provider_keys()


def test_the_settings_form_asks_for_cluster_credentials_not_ibm_cloud_ones() -> None:
    fields = {field["key"]: field for field in model_catalog.credential_fields(PROVIDER)}

    assert fields["api_base"]["required"] is True
    assert set(fields) == {
        "api_base",
        "username",
        "api_key",
        "zen_api_key",
        "space_id",
        "project_id",
        "ssl_verify",
    }
    assert fields["ssl_verify"]["field_type"] == "tls_verify"
    assert fields["ssl_verify"]["default_value"] == "true"
    assert model_catalog.secret_field_keys(PROVIDER) == {"api_key", "zen_api_key"}


def test_its_models_come_from_config_not_ibm_clouds_price_table(monkeypatch) -> None:
    """Two providers sharing model ids would leave `catalog_owner` unable to pick one."""
    monkeypatch.setenv("OPENRAG_RUN_MODE", "on_prem")
    entries = {entry["key"]: entry for entry in model_catalog.catalog()["providers"]}

    onprem = entries[PROVIDER]
    declared = {entry.name: entry for entry in model_providers.visible_provider_entries()}[PROVIDER]

    assert {entry["model"] for entry in onprem["models"]} == set(declared.models)
    assert {entry["model"] for entry in onprem["embedding_models"]} == set(
        declared.embedding_models
    )
    assert onprem["embedding_models"], "an embedding provider with no ids can never be selected"


def test_an_id_both_watsonx_rows_serve_is_never_handed_to_its_prefix(monkeypatch) -> None:
    """`openai/gpt-oss-120b` is watsonx's model, not OpenAI's.

    A cluster that also serves it puts the id under two providers, so
    `catalog_owner` cannot pick one. The old fallback split on the slash and
    routed it to OpenAI — with OpenAI's key, for a model OpenAI does not have.
    """
    monkeypatch.setenv("OPENRAG_RUN_MODE", "on_prem")
    model = "openai/gpt-oss-120b"

    if len(model_catalog.catalog_owners(model)) < 2:
        pytest.skip("this deployment's config does not list the id under both watsonx rows")

    assert model_catalog.catalog_owner(model) is None
    # Untagged, so it goes to the configured default provider whole rather than
    # to whichever provider the prefix happens to name.
    assert split_model_id(model) == (None, model)


def test_a_scopeless_cluster_call_carries_no_null_space_id(monkeypatch) -> None:
    """The lightweight engine uses neither a project nor a space.

    LiteLLM 1.84 refuses the call locally and, past that, serialises the absent
    space as `"space_id": null`. Both are wrong for that install.
    """
    for name in (
        "WATSONX_PROJECT_ID",
        "WX_PROJECT_ID",
        "PROJECT_ID",
        "WATSONX_DEPLOYMENT_SPACE_ID",
        "WATSONX_SPACE_ID",
        "WX_SPACE_ID",
        "SPACE_ID",
    ):
        monkeypatch.delenv(name, raising=False)

    watsonx_onprem.install_litellm_compatibility()

    from litellm.llms.watsonx.chat.transformation import IBMWatsonXChatConfig

    api_params = _chat_api_params(params={}, model="ibm/granite-3-3-8b-instruct")
    payload = IBMWatsonXChatConfig().prepare_payload(
        model="ibm/granite-3-3-8b-instruct", api_params=api_params
    )

    assert payload == {"model_id": "ibm/granite-3-3-8b-instruct"}


def test_a_scope_that_is_set_still_reaches_the_cluster() -> None:
    watsonx_onprem.install_litellm_compatibility()

    from litellm.llms.watsonx.chat.transformation import IBMWatsonXChatConfig

    api_params = _chat_api_params(
        params={"space_id": "space-1"}, model="ibm/granite-3-3-8b-instruct"
    )
    payload = IBMWatsonXChatConfig().prepare_payload(
        model="ibm/granite-3-3-8b-instruct", api_params=api_params
    )

    assert payload == {"model_id": "ibm/granite-3-3-8b-instruct", "space_id": "space-1"}


def test_an_explicit_onprem_space_ignores_the_cloud_project_environment(monkeypatch) -> None:
    """Cloud and on-prem watsonx scopes must not leak into each other."""
    monkeypatch.setenv("WATSONX_PROJECT_ID", "cloud-project")
    watsonx_onprem.install_litellm_compatibility()

    from litellm.llms.watsonx.chat.transformation import IBMWatsonXChatConfig

    api_params = _chat_api_params(
        params={"space_id": "onprem-space"}, model="ibm/granite-3-3-8b-instruct"
    )
    payload = IBMWatsonXChatConfig().prepare_payload(
        model="ibm/granite-3-3-8b-instruct", api_params=api_params
    )

    assert payload == {
        "model_id": "ibm/granite-3-3-8b-instruct",
        "space_id": "onprem-space",
    }


def test_a_self_signed_cluster_cert_is_reported_as_a_trust_problem() -> None:
    """The request never leaves the process, so there is no provider error to quote.

    Without this the message collapses to "could not be reached", which sends an
    operator hunting for a network fault instead of a missing CA.
    """
    from services.llm_gateway import _upstream_client_message

    detail = (
        "InternalServerError: WatsonxException - Cannot connect to host "
        "cpd.example.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: "
        "CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed "
        "certificate in certificate chain (_ssl.c:1032)')]"
    )

    message = _upstream_client_message(detail, PROVIDER, "watsonx/ibm/granite-3-3-8b-instruct")

    assert "TLS certificate is not trusted" in message
    assert "CA certificate" in message
    # Not mistaken for a bad key: rotating a working ZenApiKey fixes nothing.
    assert "API key" not in message


def test_a_revoked_key_still_reads_as_a_credential_problem() -> None:
    from services.llm_gateway import _upstream_client_message

    message = _upstream_client_message(
        'InternalServerError: {"errorCode":"BXNIM0415E","errorMessage":"Provided API key '
        'could not be found."}',
        PROVIDER,
        "watsonx/ibm/granite-3-3-8b-instruct",
    )

    assert "API key is invalid" in message


def test_a_shared_id_reaches_the_cluster_under_the_selected_provider(monkeypatch) -> None:
    """The real failure: `openai/gpt-oss-120b` picked while watsonx_onprem is selected.

    Settings stores the provider and the bare model id separately, so the id
    arrives untagged. Splitting it on the slash threw away the selected provider
    and called OpenAI with OpenAI's key for a model OpenAI does not serve.
    """
    monkeypatch.setenv("OPENRAG_RUN_MODE", "on_prem")
    model = "openai/gpt-oss-120b"
    if len(model_catalog.catalog_owners(model)) < 2:
        pytest.skip("this deployment's config does not list the id under both watsonx rows")

    config = SimpleNamespace(
        providers=_providers(
            api_base="https://cpd.example.com", username="cpduser", api_key="APIKEY"
        ),
        agent=SimpleNamespace(llm_model=model, llm_provider=PROVIDER),
        knowledge=SimpleNamespace(embedding_model="", embedding_provider="openai"),
    )

    litellm_model, provider, credentials = resolve_call(None, kind="chat", config=config)

    assert provider == PROVIDER
    assert litellm_model == f"watsonx/{model}"
    assert credentials["zen_api_key"] == "Y3BkdXNlcjpBUElLRVk="


@pytest.mark.asyncio
async def test_health_needs_no_model_selected(monkeypatch) -> None:
    """The banner reported "A model is required to validate the provider".

    Every generic provider is validated by making a real call, so one that is
    configured but has no model chosen yet failed validation and surfaced as a
    provider error — pointing at the credentials dialog for something that was
    never a credentials problem. The cluster's catalogue endpoint needs no
    model, no project and no space.
    """
    from api import provider_validation

    called: dict[str, Any] = {}

    async def _fake_request(method, url, **kwargs):
        called["method"] = method
        called["url"] = url
        called["params"] = kwargs.get("params") or {}
        called["auth"] = kwargs.get("headers", {}).get("Authorization")
        return SimpleNamespace(status_code=200, text="{}", json=lambda: {"resources": []})

    monkeypatch.setattr(watsonx_onprem, "_http_request_with_retry", _fake_request)

    credentials = watsonx_onprem.litellm_credentials(
        {"api_base": "https://cpd.example.com/", "username": "cpduser", "api_key": "APIKEY"}
    )
    await provider_validation.validate_provider_setup(
        provider=PROVIDER, credentials=credentials, llm_model=None, embedding_model=None
    )

    assert called["method"] == "GET"
    # No query on the URL: httpx replaces a URL's query when it is given
    # `params`, and a `?version=` baked into the URL is then silently dropped —
    # the cluster answers `invalid_version_date_pattern` for the empty version
    # that results.
    assert called["url"] == "https://cpd.example.com/ml/v1/foundation_model_specs"
    assert called["params"]["version"] == watsonx_onprem.API_VERSION
    assert called["auth"] == "ZenApiKey Y3BkdXNlcjpBUElLRVk="


@pytest.mark.asyncio
async def test_health_reports_a_rejected_zen_key_as_a_credential_problem(monkeypatch) -> None:
    from api import provider_validation
    from api.provider_validation import is_provider_credential_error

    async def _fake_request(method, url, **kwargs):
        return SimpleNamespace(
            status_code=401,
            text='{"errors":[{"message":"Failed to authenticate the request"}]}',
            json=lambda: {"errors": [{"message": "Failed to authenticate the request"}]},
        )

    monkeypatch.setattr(watsonx_onprem, "_http_request_with_retry", _fake_request)

    credentials = watsonx_onprem.litellm_credentials(
        {"api_base": "https://cpd.example.com", "username": "cpduser", "api_key": "APIKEY"}
    )
    with pytest.raises(Exception) as excinfo:
        await provider_validation.validate_provider_setup(
            provider=PROVIDER, credentials=credentials, llm_model=None, embedding_model=None
        )

    # Classified as a credential failure so the banner offers "update the key"
    # rather than "the provider could not be reached".
    assert is_provider_credential_error(str(excinfo.value))


def test_tls_setting_is_scoped_to_the_onprem_provider(monkeypatch) -> None:
    """The stored value wins without mutating LiteLLM's process-wide setting."""
    monkeypatch.setenv("SSL_VERIFY", "false")

    secure = watsonx_onprem.litellm_runtime_kwargs(
        {
            "api_base": "https://cpd.example.com",
            "username": "cpduser",
            "api_key": "APIKEY",
            "ssl_verify": "true",
        }
    )
    insecure = watsonx_onprem.litellm_runtime_kwargs(
        {
            "api_base": "https://cpd.example.com",
            "username": "cpduser",
            "api_key": "APIKEY",
            "ssl_verify": "false",
        }
    )

    assert secure["client"].ssl_verify is True
    assert insecure["client"].ssl_verify is False
    assert secure["client"] is not insecure["client"]
    assert "ssl_verify" not in secure
    assert "ssl_verify" not in insecure
    assert watsonx_onprem.ssl_verify({"ssl_verify": "true"}) is True
    assert watsonx_onprem.ssl_verify({"ssl_verify": "false"}) is False
    assert watsonx_onprem.ssl_verify({}) is True
    assert os.environ["SSL_VERIFY"] == "false"


def test_custom_ca_bundle_must_exist(tmp_path) -> None:
    ca = tmp_path / "openrag-ca.pem"
    ca.write_text("combined bundle", encoding="utf-8")

    assert watsonx_onprem.resolve_ssl_verify(str(ca)) == str(ca)
    with pytest.raises(ValueError, match="CA bundle path is not usable"):
        watsonx_onprem.resolve_ssl_verify(str(tmp_path / "missing.pem"))


@pytest.mark.asyncio
async def test_missing_ca_bundle_does_not_break_the_shared_model_catalog(tmp_path) -> None:
    models = await watsonx_onprem.fetch_models(
        {
            "api_base": "https://cpd.example.com",
            "username": "cpduser",
            "api_key": "APIKEY",
            "ssl_verify": str(tmp_path / "missing.pem"),
        }
    )

    assert models is None


@pytest.mark.asyncio
async def test_health_check_uses_the_saved_tls_policy(monkeypatch) -> None:
    seen: dict[str, Any] = {}

    class _Client:
        def __init__(self, *, verify):
            seen["verify"] = verify

        async def __aenter__(self):
            return self

        async def __aexit__(self, *exc):
            return False

        async def request(self, method, url, **kwargs):
            return SimpleNamespace(status_code=200, text="{}", json=lambda: {"resources": []})

    monkeypatch.setattr("httpx.AsyncClient", _Client)

    await watsonx_onprem.lightweight_health_check(
        {
            "api_base": "https://cpd.example.com",
            "username": "cpduser",
            "api_key": "APIKEY",
            "ssl_verify": "false",
        }
    )

    assert seen["verify"] is False


@pytest.mark.asyncio
async def test_space_listing_rejects_cleartext_credentials() -> None:
    with pytest.raises(ValueError, match="must use HTTPS"):
        await watsonx_onprem.list_spaces(
            {
                "api_base": "http://cpd.example.com",
                "username": "cpduser",
                "api_key": "APIKEY",
            }
        )


@pytest.mark.asyncio
async def test_space_listing_uses_bearer_tls_and_rebases_pagination(monkeypatch) -> None:
    seen: dict[str, Any] = {"requests": []}
    responses = [
        {"accessToken": "cpd-access-token"},
        {
            "resources": [
                {"metadata": {"id": "space-1", "name": "Production"}},
                {"metadata": {"id": "space-1", "name": "Duplicate"}},
            ],
            "next": {"href": "https://internal-cpd/v2/spaces?version=2024-03-13&start=2"},
        },
        {
            "resources": [
                {"metadata": {"id": "space-2", "name": "Development"}},
            ]
        },
    ]

    class _Client:
        def __init__(self, *, verify, timeout):
            seen["verify"] = verify
            seen["timeout"] = timeout

        async def __aenter__(self):
            return self

        async def __aexit__(self, *exc):
            return False

        async def request(self, method, url, **kwargs):
            seen["requests"].append((method, url, kwargs))
            body = responses.pop(0)
            return SimpleNamespace(status_code=200, text="{}", json=lambda: body)

    monkeypatch.setattr("httpx.AsyncClient", _Client)

    spaces = await watsonx_onprem.list_spaces(
        {
            "api_base": "https://cpd.example.com",
            "username": "cpduser",
            "api_key": "APIKEY",
        }
    )

    assert spaces == [
        {"id": "space-1", "name": "Production"},
        {"id": "space-2", "name": "Development"},
    ]
    assert seen["verify"] is True
    assert [(method, url) for method, url, _ in seen["requests"]] == [
        ("POST", "https://cpd.example.com/icp4d-api/v1/authorize"),
        ("GET", "https://cpd.example.com/v2/spaces"),
        ("GET", "https://cpd.example.com/v2/spaces?version=2024-03-13&start=2"),
    ]
    assert seen["requests"][0][2]["json"] == {
        "username": "cpduser",
        "api_key": "APIKEY",
    }
    assert all(
        kwargs["headers"]["Authorization"] == "Bearer cpd-access-token"
        for _, _, kwargs in seen["requests"][1:]
    )


@pytest.mark.asyncio
async def test_space_listing_exchanges_a_pasted_zen_key_for_bearer(monkeypatch) -> None:
    requests: list[tuple[str, str, dict[str, Any]]] = []
    responses = [
        (200, {"token": "cpd-access-token"}),
        (
            200,
            {
                "resources": [
                    {"metadata": {"id": "space-1", "name": "Production"}},
                ]
            },
        ),
    ]

    class _Client:
        def __init__(self, *, verify, timeout):
            assert verify is True

        async def __aenter__(self):
            return self

        async def __aexit__(self, *exc):
            return False

        async def request(self, method, url, **kwargs):
            requests.append((method, url, kwargs))
            status_code, body = responses.pop(0)
            return SimpleNamespace(
                status_code=status_code,
                text=str(body),
                json=lambda: body,
            )

    monkeypatch.setattr("httpx.AsyncClient", _Client)

    spaces = await watsonx_onprem.list_spaces(
        {
            "api_base": "https://cpd.example.com",
            "zen_api_key": "Y3BkdXNlcjpBUElLRVk=",
        }
    )

    assert spaces == [{"id": "space-1", "name": "Production"}]
    assert [(method, url) for method, url, _ in requests] == [
        ("POST", "https://cpd.example.com/icp4d-api/v1/authorize"),
        ("GET", "https://cpd.example.com/v2/spaces"),
    ]
    assert requests[0][2]["json"] == {
        "username": "cpduser",
        "api_key": "APIKEY",
    }
    assert requests[1][2]["headers"]["Authorization"] == "Bearer cpd-access-token"


def test_auth_method_changes_preserve_the_tls_policy() -> None:
    providers = _providers(
        api_base="https://cpd.example.com",
        username="cpduser",
        api_key="APIKEY",
        ssl_verify="false",
    )

    providers.set_credentials(
        PROVIDER,
        {"zen_api_key": "cHJlOmVuY29kZWQ="},
        auth_method="zen_api_key",
    )

    assert providers.stored_credentials(PROVIDER) == {
        "api_base": "https://cpd.example.com",
        "zen_api_key": "cHJlOmVuY29kZWQ=",
        "ssl_verify": "false",
    }


@pytest.mark.parametrize(
    "stored, expected",
    [
        ({"zen_api_key": "cHJlOmVuY29kZWQ="}, "zen_api_key"),
        ({"username": "cpduser", "api_key": "APIKEY"}, "username_api_key"),
        # A blank Zen key is not a Zen key.
        ({"zen_api_key": "  ", "username": "cpduser"}, "username_api_key"),
        ({}, "username_api_key"),
        (None, "username_api_key"),
    ],
)
def test_the_default_auth_method_follows_the_saved_secret(stored, expected) -> None:
    assert watsonx_onprem.default_auth_method(stored) == expected


def test_the_registry_exposes_the_default_auth_method(monkeypatch) -> None:
    from enhancements.providers import registry

    assert (
        registry.default_auth_method_for(PROVIDER, {"zen_api_key": "cHJlOmVuY29kZWQ="})
        == "zen_api_key"
    )
    # No hook: nothing to assume.
    assert registry.default_auth_method_for("openai", {}) is None

    def broken(stored):
        raise RuntimeError("boom")

    monkeypatch.setattr(watsonx_onprem, "default_auth_method", broken)
    assert registry.default_auth_method_for(PROVIDER, {}) is None


def test_cleared_optional_credential_is_removed() -> None:
    providers = _providers(
        api_base="https://cpd.example.com",
        username="cpduser",
        api_key="APIKEY",
        space_id="deployment-space",
    )
    providers.set_credentials(
        PROVIDER,
        {"api_base": "https://cpd.example.com"},
        auth_method="username_api_key",
        remove={"space_id"},
    )

    assert "space_id" not in providers.stored_credentials(PROVIDER)


@pytest.mark.asyncio
async def test_switching_to_a_model_the_cluster_lacks_is_still_blocked(monkeypatch) -> None:
    """Settings validates before it writes and returns 400 on failure.

    The catalogue check added for the no-model case must not become the check
    for *every* case: with a model in hand the probe has to be a real call, or a
    switch to a model the cluster does not serve saves silently and only fails
    later in chat.
    """
    import litellm

    from api import provider_validation

    probes: list[str] = []

    async def _unexpected_http(method, url, **kwargs):
        probes.append("catalogue")
        return SimpleNamespace(status_code=200, text="{}", json=lambda: {"resources": []})

    async def _fake_completion(**kwargs):
        probes.append("real-call")
        raise Exception('{"errors":[{"message":"Model \'ibm/nope\' is not supported"}]}')

    monkeypatch.setattr(watsonx_onprem, "_http_request_with_retry", _unexpected_http)
    monkeypatch.setattr(litellm, "acompletion", _fake_completion)

    credentials = watsonx_onprem.litellm_credentials(
        {"api_base": "https://cpd.example.com", "username": "cpduser", "api_key": "APIKEY"}
    )
    with pytest.raises(Exception, match="not supported"):
        await provider_validation.validate_provider_setup(
            provider=PROVIDER,
            credentials=credentials,
            llm_model="ibm/nope",
            embedding_model=None,
            verify_model=True,
        )

    assert probes == ["real-call"], "a model in hand must be probed for real"


@pytest.mark.asyncio
async def test_switching_an_embedding_model_is_probed_for_real(monkeypatch) -> None:
    import litellm

    from api import provider_validation

    probes: list[str] = []

    async def _fake_embedding(**kwargs):
        probes.append(kwargs.get("model"))
        return {"data": []}

    monkeypatch.setattr(litellm, "aembedding", _fake_embedding)

    credentials = watsonx_onprem.litellm_credentials(
        {"api_base": "https://cpd.example.com", "username": "cpduser", "api_key": "APIKEY"}
    )
    await provider_validation.validate_provider_setup(
        provider=PROVIDER,
        credentials=credentials,
        llm_model=None,
        embedding_model="ibm/slate-125m-english-rtrvr-v2",
        verify_model=True,
    )

    assert probes == ["watsonx/ibm/slate-125m-english-rtrvr-v2"]


@pytest.fixture
def _forget_cluster_models():
    watsonx_onprem.forget_models()
    yield
    watsonx_onprem.forget_models()


def _specs_response(resources, status_code=200):
    return SimpleNamespace(
        status_code=status_code,
        text="",
        json=lambda: {"resources": [dict(entry) for entry in resources]},
    )


#: Trimmed from a real Cloud Pak for Data cluster's `foundation_model_specs`
#: response. The shapes matter: `functions` is a list of `{"id": ...}`,
#: `lifecycle` is a list rather than a string, and the chat model's own name
#: begins with another provider's key.
CLUSTER_RESOURCES = [
    {
        "model_id": "ibm/slate-30m-english-rtrvr",
        "functions": [{"id": "embedding"}, {"id": "rerank"}, {"id": "similarity"}],
        "lifecycle": [{"id": "available", "current_state": True}],
        "input_tier": "class_c1",
    },
    {
        "model_id": "openai/gpt-oss-120b",
        "functions": [{"id": "autoai_rag"}, {"id": "text_chat"}],
        "task_ids": ["summarization", "generation", "function_calling"],
        "lifecycle": [{"id": "available", "current_state": True}],
        "input_tier": "class_8",
    },
    {
        "model_id": "ibm/granite-preview",
        "functions": [{"id": "text_chat"}],
        "input_tier": "tech_preview",
    },
    {
        "model_id": "ibm/granite-retired",
        "functions": [{"id": "text_chat"}],
        "lifecycle": [{"id": "withdrawn", "current_state": True}],
    },
]


def test_a_cluster_listing_is_split_into_the_two_pickers() -> None:
    """Split locally rather than with the API's `filters` grammar.

    The grammar is a SaaS convenience; a cluster that does not accept it would
    answer 400 and leave both pickers empty.
    """
    models = watsonx_onprem.split_models(CLUSTER_RESOURCES)

    assert models.chat == ("openai/gpt-oss-120b",)
    assert models.embedding == ("ibm/slate-30m-english-rtrvr",)
    # tech_preview is not requestable on every deployment; withdrawn is retired.
    assert "ibm/granite-preview" not in models.chat
    assert "ibm/granite-retired" not in models.chat


@pytest.mark.asyncio
async def test_the_picker_shows_what_the_cluster_serves(
    monkeypatch, _forget_cluster_models
) -> None:
    """A cluster serves whatever its operator deployed.

    The configured `models:` rows can only ever be a guess, so a model the
    cluster does not have would otherwise sit in the picker waiting to be
    chosen and fail at the first call.
    """
    monkeypatch.setenv("OPENRAG_RUN_MODE", "on_prem")
    seen: dict[str, Any] = {}

    class _Client:
        def __init__(self, **kwargs):
            pass

        async def __aenter__(self):
            return self

        async def __aexit__(self, *exc):
            return False

        async def get(self, url, headers=None, params=None):
            seen["url"] = url
            seen["params"] = dict(params or {})
            assert headers["Authorization"].startswith("ZenApiKey ")
            return _specs_response(CLUSTER_RESOURCES)

    monkeypatch.setattr("httpx.AsyncClient", _Client)

    models = await watsonx_onprem.fetch_models(
        {"api_base": "https://cpd.example.com", "username": "u", "api_key": "k"}
    )

    # The version has to travel in `params`; httpx would drop it from the URL.
    assert seen["url"] == "https://cpd.example.com/ml/v1/foundation_model_specs"
    assert seen["params"]["version"] == watsonx_onprem.API_VERSION
    # No project: a lightweight-engine install has none, and sending one 404s.
    assert "project_id" not in seen["params"]

    assert models.chat == ("openai/gpt-oss-120b",)
    assert models.embedding == ("ibm/slate-30m-english-rtrvr",)

    entry = {e["key"]: e for e in model_catalog.catalog()["providers"]}[PROVIDER]
    assert [m["model"] for m in entry["models"]] == ["openai/gpt-oss-120b"]
    assert [m["model"] for m in entry["embedding_models"]] == ["ibm/slate-30m-english-rtrvr"]


@pytest.mark.asyncio
async def test_a_next_page_is_re_based_on_the_operators_cluster_url(
    monkeypatch, _forget_cluster_models
) -> None:
    """A cluster names itself internally in its own pagination links.

    This one answers `https://wx-inference-proxy-upstream/ml/v1/...`, which does
    not resolve outside the cluster. Following it verbatim strands the listing
    on page one.
    """
    urls: list[str] = []

    class _Client:
        def __init__(self, **kwargs):
            pass

        async def __aenter__(self):
            return self

        async def __aexit__(self, *exc):
            return False

        async def get(self, url, headers=None, params=None):
            urls.append(url)
            if len(urls) == 1:
                return SimpleNamespace(
                    status_code=200,
                    text="",
                    json=lambda: {
                        "resources": [CLUSTER_RESOURCES[1]],
                        "next": {
                            "href": "https://wx-inference-proxy-upstream"
                            "/ml/v1/foundation_model_specs?version=2024-03-13&start=2"
                        },
                    },
                )
            return _specs_response([CLUSTER_RESOURCES[0]])

    monkeypatch.setattr("httpx.AsyncClient", _Client)

    models = await watsonx_onprem.fetch_models(
        {"api_base": "https://cpd.example.com", "username": "u", "api_key": "k"}
    )

    assert urls[1].startswith("https://cpd.example.com/ml/v1/foundation_model_specs")
    assert "wx-inference-proxy-upstream" not in urls[1]
    assert "start=2" in urls[1]
    assert models.chat == ("openai/gpt-oss-120b",)
    assert models.embedding == ("ibm/slate-30m-english-rtrvr",)


@pytest.mark.asyncio
async def test_an_unreachable_cluster_keeps_the_configured_fallback(
    monkeypatch, _forget_cluster_models
) -> None:
    """A catalogue request must never fail because the cluster is down."""
    monkeypatch.setenv("OPENRAG_RUN_MODE", "on_prem")

    class _Client:
        def __init__(self, **kwargs):
            pass

        async def __aenter__(self):
            return self

        async def __aexit__(self, *exc):
            return False

        async def get(self, url, headers=None, params=None):
            raise OSError("cluster unreachable")

    monkeypatch.setattr("httpx.AsyncClient", _Client)

    assert (
        await watsonx_onprem.fetch_models(
            {"api_base": "https://cpd.example.com", "username": "u", "api_key": "k"}
        )
        is None
    )

    declared = {e.name: e for e in model_providers.visible_provider_entries()}[PROVIDER]
    entry = {e["key"]: e for e in model_catalog.catalog()["providers"]}[PROVIDER]
    assert {m["model"] for m in entry["models"]} == set(declared.models)


@pytest.mark.asyncio
async def test_an_empty_listing_is_treated_as_a_bad_filter_not_an_empty_cluster(
    monkeypatch, _forget_cluster_models
) -> None:
    """Emptying both pickers on a guess would be worse than showing the fallback."""

    class _Client:
        def __init__(self, **kwargs):
            pass

        async def __aenter__(self):
            return self

        async def __aexit__(self, *exc):
            return False

        async def get(self, url, headers=None, params=None):
            return _specs_response([])

    monkeypatch.setattr("httpx.AsyncClient", _Client)

    assert (
        await watsonx_onprem.fetch_models(
            {"api_base": "https://cpd.example.com", "username": "u", "api_key": "k"}
        )
        is None
    )
    assert watsonx_onprem.cached_models() is None


@pytest.mark.asyncio
async def test_draft_discovery_lists_without_caching(monkeypatch, _forget_cluster_models) -> None:
    """Onboarding lists a cluster before its credentials are saved; that answer
    must not reach the catalogue through `cached_models()`."""

    class _Client:
        def __init__(self, **kwargs):
            pass

        async def __aenter__(self):
            return self

        async def __aexit__(self, *exc):
            return False

        async def get(self, url, headers=None, params=None):
            return _specs_response(CLUSTER_RESOURCES)

    monkeypatch.setattr("httpx.AsyncClient", _Client)
    credentials = {"api_base": "https://cpd.example.com", "username": "u", "api_key": "k"}

    models = await watsonx_onprem.list_cluster_models(credentials)

    assert models.chat == ("openai/gpt-oss-120b",)
    assert models.embedding == ("ibm/slate-30m-english-rtrvr",)
    assert watsonx_onprem.cached_models() is None

    await watsonx_onprem.fetch_models(credentials)
    assert watsonx_onprem.cached_models() == models


@pytest.mark.asyncio
async def test_draft_discovery_with_incomplete_credentials_makes_no_request(
    monkeypatch,
) -> None:
    def _explode(**kwargs):
        raise AssertionError("no HTTP call should be made")

    monkeypatch.setattr("httpx.AsyncClient", _explode)

    assert await watsonx_onprem.list_cluster_models({"api_base": "https://cpd.example.com"}) is None


@pytest.mark.asyncio
async def test_validating_an_embedding_model_sends_a_list_not_a_string(monkeypatch) -> None:
    """watsonx.ai takes `inputs` only as an array.

    OpenAI accepts a bare string, so the validator sent one and LiteLLM
    forwarded it verbatim. The cluster answered "Mismatch type []string with
    value string", which failed the pre-save check for *every* embedding model
    and left a wrongly-chosen one impossible to change.
    """
    import litellm

    from api import provider_validation

    sent: dict[str, object] = {}

    async def _fake_embedding(**kwargs):
        sent.update(kwargs)
        return {"data": [{"embedding": [0.1]}]}

    monkeypatch.setattr(litellm, "aembedding", _fake_embedding)

    await provider_validation.validate_provider_setup(
        provider=PROVIDER,
        credentials=watsonx_onprem.litellm_credentials(
            {"api_base": "https://cpd.example.com", "username": "u", "api_key": "k"}
        ),
        llm_model=None,
        embedding_model="ibm/slate-30m-english-rtrvr",
        verify_model=True,
    )

    assert isinstance(sent["input"], list), sent["input"]
    assert "client" in sent


@pytest.mark.asyncio
async def test_a_client_sending_a_bare_string_input_still_embeds(monkeypatch) -> None:
    """OpenAI's own contract allows a string, so clients send one."""
    import litellm

    from services.llm_gateway import embeddings

    sent: dict[str, object] = {}

    async def _fake_embedding(**kwargs):
        sent.update(kwargs)
        return {"data": [{"embedding": [0.1]}], "model": "m", "object": "list"}

    monkeypatch.setattr(litellm, "aembedding", _fake_embedding)

    config = SimpleNamespace(
        providers=_providers(
            api_base="https://cpd.example.com", username="cpduser", api_key="APIKEY"
        ),
        agent=SimpleNamespace(llm_model="", llm_provider=PROVIDER),
        knowledge=SimpleNamespace(
            embedding_model="ibm/slate-30m-english-rtrvr",
            embedding_provider=PROVIDER,
            legacy_embedding_provider_map={},
        ),
    )
    await embeddings(
        {"model": f"{PROVIDER}:ibm/slate-30m-english-rtrvr", "input": "hello"}, config=config
    )

    assert sent["input"] == ["hello"]
    assert "client" in sent


def test_a_token_array_input_is_left_alone() -> None:
    """Only a string is wrapped; OpenAI's token-array forms pass through."""
    from services.llm_gateway import _embedding_input

    assert _embedding_input("hello") == ["hello"]
    assert _embedding_input(["a", "b"]) == ["a", "b"]
    assert _embedding_input([[1, 2], [3]]) == [[1, 2], [3]]
    assert _embedding_input([1, 2, 3]) == [1, 2, 3]