inference icon indicating copy to clipboard operation
inference copied to clipboard

Token Router reload permits two active backend admissions with max_active=1

Open Jackmeson1 opened this issue 3 weeks ago • 0 comments

System Info / 系統信息

Colab CPU environment: Linux-6.6.159+-x86_64-with-glibc2.39.

The test ran in a virtual environment with Python 3.12.3, pytest 9.2.0, pluggy 1.7.0, pytest-asyncio 1.4.1.post1, anyio 4.16.0, and pytest-timeout 2.4.0. Pytest reported asyncio: mode=Mode.AUTO.

No model or GPU was used.

Running Xinference with Docker? / 是否使用 Docker 运行 Xinfernece?

  • [ ] docker / docker
  • [x] pip install / 通过 pip install 安装
  • [x] installation from source / 从源码安装

Installed from the source checkout with pip install -e .. The reproduction runs in-process through pytest.

Version info / 版本信息

Source commit 3e8b25e73f612b39588f9fac08d6d2f93e4970c5.

The command used to start Xinference / 用以启动 xinference 的命令

No Xinference server needs to be started. From the checkout root, run:

pytest xinference/router/tests/test_reload_admission.py

Reproduction / 复现过程

With backend admission configured as max_active=1 and max_queue=0, applying a newer configuration admits a second slot for an unchanged backend while its original slot remains occupied. Before acquiring that second slot, runtime.summary() reports zero active requests for the backend.

The primary case changes only the configuration revision. The backend ID, model UID, backend URL, routing rules, and capacity settings remain unchanged. A second case removes and re-adds the same backend while the original request remains held; it produces the same results.

Save the following as xinference/router/tests/test_reload_admission.py and run the command above. It uses the real configuration parser, runtime snapshot builder, and admission gates. Only tokenization is replaced. Events keep the original slot occupied, and no backend HTTP requests are sent. A spare backend keeps the intermediate removal configuration valid.

# Copyright 2022-2026 Xinference Holdings Pte. Ltd
# CI: linux
from __future__ import annotations

import asyncio
from pathlib import Path
from typing import Any, AsyncIterator

import pytest

from xinference.router import runtime as runtime_module
from xinference.router.admission import AdmissionRejected, GateSnapshot
from xinference.router.config import RouterConfig, config_from_control_plane
from xinference.router.runtime import RouterRuntime, RuntimeSnapshot


class FakeTokenization:
    asset_revision = ""
    asset_fingerprint = ""
    worker_pids: tuple[int, ...] = ()

    def __init__(self, *args: Any, **kwargs: Any) -> None:
        pass

    async def start(self) -> None:
        pass

    async def aclose(self) -> None:
        pass

    async def snapshot(self) -> GateSnapshot:
        return GateSnapshot(active=0, waiting=0, max_active=1, max_queue=0)


def _config(
    tokenizer_path: Path,
    revision: int,
    backend_ids: tuple[str, ...] = ("limited", "spare"),
) -> RouterConfig:
    return config_from_control_plane(
        {
            "config_version": 2,
            "enabled": True,
            "revision": revision,
            "virtual_model_uid": "router-model",
            "tokenizer_path": str(tokenizer_path),
            "backend_url": "http://backend.invalid",
            "backends": [
                {
                    "id": backend_id,
                    "model_uid": f"{backend_id}-model",
                    "max_context_tokens": 4096,
                    "admission": {"max_active": 1, "max_queue": 0},
                }
                for backend_id in backend_ids
            ],
            "routing": {
                "rules": [
                    {
                        "id": "route",
                        "priority": 1,
                        "match": {"total_tokens_gte": 0},
                        "action": {"type": "route", "backend_id": backend_ids[0]},
                    }
                ],
                "default_action": {"type": "reject", "reason": "no_route"},
            },
            "tokenization": {"max_workers": 1, "max_active": 1, "max_queue": 0},
        }
    )


@pytest.fixture(params=[False, True], ids=["reload", "remove-readd"])
async def reloaded_runtime(
    request: pytest.FixtureRequest,
    tmp_path: Path,
    monkeypatch: pytest.MonkeyPatch,
) -> AsyncIterator[tuple[RouterRuntime, RuntimeSnapshot]]:
    # Exercise the real snapshot builder and gates without tokenizer processes.
    monkeypatch.setattr(runtime_module, "TokenizationService", FakeTokenization)
    runtime = RouterRuntime(_config(tmp_path, 1))
    await runtime.start()
    held = await runtime.acquire()
    entered = asyncio.Event()
    finish = asyncio.Event()

    async def hold_request() -> None:
        gate = held.gates["limited"]
        await gate.acquire()
        try:
            entered.set()
            await finish.wait()
        finally:
            await gate.release()

    holding = asyncio.create_task(hold_request())
    try:
        await asyncio.wait_for(entered.wait(), timeout=5)
        # Controls: accounting and the zero-length queue work before reload.
        assert (await held.gates["limited"].snapshot()).active == 1
        assert (await runtime.summary())["pools"]["limited"]["active"] == 1
        with pytest.raises(AdmissionRejected) as exc_info:
            await held.gates["limited"].acquire()
        assert exc_info.value.reason == "queue_full"

        if request.param:
            # Keep a valid backend/rule while removing only the held backend.
            await runtime.apply(_config(tmp_path, 2, backend_ids=("spare",)))
            assert "limited" not in runtime.current.gates
        await runtime.apply(_config(tmp_path, 3))

        assert held.draining is True
        assert held.closed is False
        assert (await held.gates["limited"].snapshot()).active == 1
        yield runtime, held
    finally:
        finish.set()
        try:
            await holding
        finally:
            await runtime.release(held)
            await runtime.aclose()


@pytest.mark.asyncio
async def test_reload_preserves_backend_admission(
    reloaded_runtime: tuple[RouterRuntime, RuntimeSnapshot],
) -> None:
    runtime, held = reloaded_runtime
    current = await runtime.acquire()
    gate = current.gates["limited"]
    admitted = False
    try:
        with pytest.raises(AdmissionRejected) as exc_info:
            await gate.acquire()
            admitted = True
            assert (await held.gates["limited"].snapshot()).active == 1
        assert exc_info.value.reason == "queue_full"
    finally:
        if admitted:
            await gate.release()
        await runtime.release(current)


@pytest.mark.asyncio
async def test_reload_summary_counts_inflight_backend_request(
    reloaded_runtime: tuple[RouterRuntime, RuntimeSnapshot],
) -> None:
    runtime, _ = reloaded_runtime
    summary = await runtime.summary()
    assert summary["pools"]["limited"]["active"] == 1, summary

The Colab CPU run at the commit above produced:

FAILED xinference/router/tests/test_reload_admission.py::test_reload_preserves_backend_admission[reload]
FAILED xinference/router/tests/test_reload_admission.py::test_reload_preserves_backend_admission[remove-readd]
FAILED xinference/router/tests/test_reload_admission.py::test_reload_summary_counts_inflight_backend_request[reload]
FAILED xinference/router/tests/test_reload_admission.py::test_reload_summary_counts_inflight_backend_request[remove-readd]
============================== 4 failed in 1.08s ===============================

Both admission cases failed at line 134 with:

E           Failed: DID NOT RAISE AdmissionRejected

The second acquire succeeded while the assertion that the original gate remained active also passed.

Both summary cases failed at line 151 with:

E       assert 0 == 1

The returned summary had revision 3, active_requests: 0, and pools["limited"]["active"]: 0.

Check Expected Observed in both lifecycle cases
Before replacement Old gate and summary count 1; another acquire rejects with queue_full Controls passed
After replacement, original slot still held Original snapshot remains open and draining; old gate counts 1 Controls passed
Second acquire for limited Reject with queue_full Acquire succeeded while the old slot remained occupied
Summary with only the original slot held Backend active count 1 Backend active count 0

The source explains these results:

  • xinference/router/runtime.py:97–106 constructs new CapacityGate objects for every snapshot.
  • xinference/router/runtime.py:152–176 publishes the replacement while the previous snapshot drains. Its occupied gate remains attached to the old snapshot.
  • xinference/router/runtime.py:187–198 builds the summary from the current snapshot only.

This path is used by normal configuration polling: xinference/router/control_plane.py:311–328 applies newer revisions through runtime.apply().

The HTTP request handler acquires the request's snapshot gate at xinference/router/app.py:609–612, maps admission rejection to HTTP 429 at lines 613–645, and sends upstream after acquisition. /healthz includes the runtime summary at app.py:223–237. Those HTTP implications follow from the source; this reproduction directly exercises runtime admission and summary collection.

The demonstrated impact is two simultaneously occupied admission slots for a backend configured for one, within a single Router process during configuration replacement. The summary omits work still held by the previous snapshot. Actual model execution, backend overload, repeated reloads, and behavior across multiple Router processes were not measured.

Expected behavior / 期待表现

For an unchanged backend ID, model UID, backend URL, and admission configuration within one Router process, I expect an existing request to continue consuming capacity across a configuration reload. With max_active=1 and max_queue=0, another acquire should raise AdmissionRejected with reason queue_full until that request releases its slot.

I would also expect the backend's active count to remain 1 while that work is held. The summary currently includes a configuration revision, so whether its counts intentionally describe only that revision needs clarification.

The schema defines backend admission limits at xinference/api/schemas/router.py:38–41 and describes the V2 backend identifier as stable at line 60. Existing tests separately cover capacity rejection and draining replaced snapshots. I found no explicit cross-reload concurrency guarantee under doc/source/; the expectation above concerns the same backend whose original work is still active.

The removal/re-addition case is included as a secondary observation. It restores the same backend identity and endpoint without finishing the original work. Whether removal intentionally starts a new admission lifetime is less clear; the unchanged-backend reload reproduces the issue independently.

AI disclosure: this was prepared with AI assistance (Claude Opus 5.5 and Claude Sonnet 5.5).

Jackmeson1 avatar Nov 11 '26 23:11 Jackmeson1