Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

11.2 KB
Raw Blame
"""Run the suites that need real model weights against pinned public checkpoints on CPU.

Suites, in the order they run:

* ``pins``: the handwritten output pins in ``test_all_models.py`` for the lane's models.
* ``parity``: adapter parity against goldens generated by the reference packages.
* ``server``: server integration tests that start their own CPU server.
* ``integrations``: the Python framework integration tests against one shared CPU server.
* ``typescript``: the TypeScript SDK and framework integration tests against that server.

Every selected suite runs even when an earlier one fails; the exit status is non-zero if any failed.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import os
import signal
import subprocess
import sys
import tempfile
from collections.abc import Iterator, Mapping, Sequence
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import Any

import yaml
from sie_sdk import SIEClient

from tools.ci.live_sdk import free_port, wait_for_api
from tools.mise_tasks import model_test_selection

MODELS_DIR = Path("packages/sie_server/models")
MODEL_TEST = Path("packages/sie_server/tests/test_all_models.py")
LOGS = Path(".cache/ci-logs")
CACHE_KEY_PREFIX = "real-models-hf-v1-"

SERVED_MODELS = (
    "BAAI/bge-m3",
    "jinaai/jina-reranker-v2-base-multilingual",
    "urchade/gliner_multi-v2.1",
)
PINNED_MODELS = (
    "BAAI/bge-m3",
    "BAAI/bge-m3:bge_m3_flag",
    "jinaai/jina-reranker-v2-base-multilingual",
    "urchade/gliner_multi-v2.1",
    "NeuML/gliner-bert-tiny",
    "sentence-transformers/all-MiniLM-L6-v2",
    "intfloat/e5-small-v2",
    "cross-encoder/ms-marco-MiniLM-L-12-v2",
    "ibm-granite/granite-embedding-30m-sparse",
    "answerdotai/answerai-colbert-small-v1",
    "answerdotai/answerai-colbert-small-v1:muvera",
    "knowledgator/gliclass-edge-v3.0",
    "knowledgator/gliner-bi-edge-v2.0",
    "knowledgator/opir-edge-v1.0",
)


@dataclass(frozen=True)
class ParitySuite:
    path: str
    keyword: str
    models: tuple[str, ...]


PARITY_SUITES = (
    ParitySuite(
        "packages/sie_server/tests/adapters/test_gliformer_parity.py",
        "knowledgator__gliformer-base-v1",
        ("knowledgator/gliformer-base-v1",),
    ),
    ParitySuite(
        "packages/sie_server/tests/adapters/test_laya_parity.py",
        "laya-multilingual or laya-typed-decisions",
        ("convaiinnovations/laya-multilingual", "convaiinnovations/laya-typed-decisions"),
    ),
)
SERVER_TESTS = (
    "packages/sie_server/tests/test_sdk_integration.py",
    "packages/sie_server/tests/api/test_extract_integration.py",
    "packages/sie_server/tests/test_sparse_integration.py",
)
SERVER_TEST_MODELS = ("BAAI/bge-m3", "NeuML/gliner-bert-tiny", "rasyosef/splade-mini")
PYTHON_INTEGRATIONS = (
    "sie_chroma",
    "sie_cognee",
    "sie_crewai",
    "sie_dspy",
    "sie_haystack",
    "sie_lancedb",
    "sie_langchain",
    "sie_llamaindex",
    "sie_qdrant",
    "sie_weaviate",
)
TYPESCRIPT_PACKAGES = (
    "packages/sie_ts_sdk",
    "integrations/sie_ts_chroma",
    "integrations/sie_ts_langchain",
    "integrations/sie_ts_llamaindex",
)
SUITES = ("pins", "parity", "server", "integrations", "typescript")
SHARED_SERVER_SUITES = frozenset({"integrations", "typescript"})
SERVER_READY_TIMEOUT_S = 600
WARM_UP_TIMEOUT_S = 1800
SCRUBBED_ENV = ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN", "SIE_API_KEY", "SIE_GATEWAY_URL", "SIE_NATS_URL")
PYTEST = (sys.executable, "-m", "pytest", "-c", "pyproject.toml", "-p", "no:cacheprovider", "-rfEsxX")


def lane_models() -> list[str]:
    models = {*SERVED_MODELS, *PINNED_MODELS, *SERVER_TEST_MODELS}
    for suite in PARITY_SUITES:
        models.update(suite.models)
    return sorted({model.split(":", 1)[0] for model in models})


def model_configs(models_dir: Path = MODELS_DIR) -> dict[str, dict[str, Any]]:
    configs: dict[str, dict[str, Any]] = {}
    for path in sorted(models_dir.glob("*.yaml")):
        config = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
        if "sie_id" in config:
            configs[config["sie_id"]] = config
    return configs


def weights_manifest(models_dir: Path = MODELS_DIR) -> dict[str, dict[str, Any]]:
    configs = model_configs(models_dir)
    manifest: dict[str, dict[str, Any]] = {}
    for model in lane_models():
        if model not in configs:
            raise ValueError(f"{model} has no model config in {models_dir}")
        config = configs[model]
        manifest[model] = {
            "hf_id": config.get("hf_id"),
            "hf_revision": config.get("hf_revision"),
            "hf_tokenizer_dependencies": config.get("hf_tokenizer_dependencies") or {},
        }
    return manifest


def cache_key(models_dir: Path = MODELS_DIR) -> str:
    canonical = json.dumps(weights_manifest(models_dir), sort_keys=True, separators=(",", ":"))
    return CACHE_KEY_PREFIX + hashlib.sha256(canonical.encode()).hexdigest()[:24]


def pinned_node_ids(models: Sequence[str] = PINNED_MODELS, test_file: Path = MODEL_TEST) -> list[str]:
    source = test_file.read_text(encoding="utf-8")
    node_ids: list[str] = []
    for model in models:
        selected = model_test_selection.select_node_ids(model, source, str(test_file))
        if not selected:
            raise ValueError(f"no handwritten model tests map exactly to {model!r}")
        node_ids.extend(selected)
    return node_ids


def suite_commands(suite: str, server_url: str | None = None) -> list[tuple[str, list[str]]]:
    if suite == "pins":
        return [("pins", [*PYTEST, "-m", "model", *pinned_node_ids()])]
    if suite == "parity":
        return [
            (f"parity {item.path}", [*PYTEST, "-m", "model", item.path, "-k", item.keyword]) for item in PARITY_SUITES
        ]
    if suite == "server":
        return [("server", [*PYTEST, "-m", "integration", *SERVER_TESTS])]
    if server_url is None:
        raise ValueError(f"{suite} needs a running server")
    if suite == "integrations":
        return [
            (f"integration {name}", [*PYTEST, "-m", "integration", f"integrations/{name}/tests"])
            for name in PYTHON_INTEGRATIONS
        ]
    if suite == "typescript":
        return [
            (f"typescript {package}", ["mise", "exec", "--", "pnpm", "--dir", package, "run", "test:integration"])
            for package in TYPESCRIPT_PACKAGES
        ]
    raise ValueError(f"unknown suite {suite!r}")


def suite_environment(base: Mapping[str, str], server_url: str | None = None) -> dict[str, str]:
    env = {key: value for key, value in base.items() if key not in SCRUBBED_ENV}
    env["PYTHONUNBUFFERED"] = "1"
    env["SIE_TELEMETRY_DISABLED"] = "1"
    if server_url is not None:
        env["SIE_SERVER_URL"] = server_url
    return env


def server_command(models: Sequence[str], port: int) -> list[str]:
    return [
        sys.executable,
        "-m",
        "sie_server.cli",
        "serve",
        "--host",
        "127.0.0.1",
        "-p",
        str(port),
        "-d",
        "cpu",
        "-m",
        ",".join(models),
    ]


def warm_up(url: str, models: Sequence[str], configs: Mapping[str, Mapping[str, Any]]) -> None:
    with SIEClient(url, timeout_s=WARM_UP_TIMEOUT_S) as client:
        for model in models:
            tasks = configs[model].get("tasks") or {}
            if tasks.get("encode") is not None:
                client.encode(model, {"text": "warm up"}, output_types=["dense"])
            elif tasks.get("score") is not None:
                client.score(model, {"text": "warm up"}, [{"text": "warm up"}])
            elif tasks.get("extract") is not None:
                client.extract(model, {"text": "Ada Lovelace lived in London."}, labels=["person", "location"])
            else:
                raise ValueError(f"{model} declares no encode, score, or extract task")
            print(f"Loaded {model}", flush=True)


@contextmanager
def serve(models: Sequence[str]) -> Iterator[str]:
    LOGS.mkdir(parents=True, exist_ok=True)
    port = free_port()
    url = f"http://127.0.0.1:{port}"
    with (
        tempfile.TemporaryDirectory(prefix="sie-real-", dir="/tmp") as runtime,
        (LOGS / "real-models-server.log").open("w") as log,
    ):
        env = suite_environment(os.environ)
        env["SIE_IPC_SOCKET_PATH"] = f"{runtime}/worker.sock"
        process = subprocess.Popen(
            server_command(models, port),
            env=env,
            stdout=log,
            stderr=subprocess.STDOUT,
            start_new_session=True,
        )
        try:
            wait_for_api(url, process, timeout=SERVER_READY_TIMEOUT_S)
            warm_up(url, models, model_configs())
            yield url
        finally:
            try:
                os.killpg(process.pid, signal.SIGTERM)
                process.wait(timeout=30)
            except subprocess.TimeoutExpired:
                os.killpg(process.pid, signal.SIGKILL)
                process.wait(timeout=10)
            except ProcessLookupError:
                pass


def run_commands(commands: Sequence[tuple[str, list[str]]], env: Mapping[str, str]) -> list[str]:
    failed: list[str] = []
    for label, command in commands:
        print(f"\n## {label}", flush=True)
        try:
            returncode = subprocess.run(command, env=dict(env), check=False).returncode
        except OSError as exc:
            print(f"{label} could not start: {exc}", file=sys.stderr)
            returncode = 1
        if returncode:
            failed.append(label)
    return failed


def run(suites: Sequence[str]) -> list[str]:
    failed: list[str] = []
    for suite in suites:
        if suite not in SHARED_SERVER_SUITES:
            failed.extend(run_commands(suite_commands(suite), suite_environment(os.environ)))
    shared = [suite for suite in suites if suite in SHARED_SERVER_SUITES]
    if shared:
        try:
            with serve(SERVED_MODELS) as url:
                for suite in shared:
                    failed.extend(run_commands(suite_commands(suite, url), suite_environment(os.environ, url)))
        except Exception as exc:  # noqa: BLE001 — report and keep the summary
            print(f"Shared CPU server failed: {exc}", file=sys.stderr)
            failed.append("shared server")
            log = LOGS / "real-models-server.log"
            if log.exists():
                print(log.read_text(errors="replace")[-12000:], file=sys.stderr)
    return failed


def main(argv: Sequence[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    commands = parser.add_subparsers(dest="command", required=True)
    commands.add_parser("cache-key", help="Print the weights cache key for the lane's pinned revisions.")
    runner = commands.add_parser("run", help="Run the selected suites (default: all).")
    runner.add_argument("--suite", action="append", choices=SUITES, help="Suite to run; repeat to select several.")
    args = parser.parse_args(argv)
    if args.command == "cache-key":
        print(cache_key())
        return 0
    selected = [suite for suite in SUITES if suite in (args.suite or SUITES)]
    failed = run(selected)
    if failed:
        print("\nReal-model suites failed:\n" + "\n".join(failed), file=sys.stderr)
        return 1
    print("\nEvery selected real-model suite passed.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())