From 1d540330dd6b9a442bef5d5b6aaecb6eda2722b1 Mon Sep 17 00:00:00 2001 From: Igx22 Date: Mon, 16 Nov 2026 19:40:19 +0700 Subject: [PATCH 1/7] Add Gateway usage metering and minute-batch delivery Implement DS-002 with verified subject/service counters, JSON and SSE token usage, durable minute checkpoints, and fetch/commit/ACK delivery to server receipts. Add the local Python testbed, six acceptance scenarios, and ingress coverage. Keep quota enforcement outside this change. --- contributing/PROXY.md | 26 ++ pyproject.toml | 1 + src/dstack/_internal/proxy/gateway/app.py | 49 ++- src/dstack/_internal/proxy/gateway/auth.py | 32 +- src/dstack/_internal/proxy/gateway/deps.py | 19 + src/dstack/_internal/proxy/gateway/models.py | 7 +- .../_internal/proxy/gateway/routers/config.py | 56 ++- .../_internal/proxy/gateway/routers/usage.py | 31 ++ .../_internal/proxy/gateway/schemas/config.py | 3 +- .../proxy/gateway/services/metering.py | 310 ++++++++++++++ .../proxy/gateway/services/metering_store.py | 105 +++++ src/dstack/_internal/proxy/lib/auth.py | 5 + .../_internal/proxy/lib/cancellation.py | 23 ++ src/dstack/_internal/proxy/lib/deps.py | 13 + .../proxy/lib/routers/model_proxy.py | 114 +++++- .../proxy/lib/schemas/model_proxy.py | 11 + .../_internal/proxy/lib/schemas/usage.py | 106 +++++ .../lib/services/model_proxy/clients/base.py | 9 +- .../services/model_proxy/clients/openai.py | 120 ++++-- .../lib/services/model_proxy/clients/tgi.py | 9 +- .../proxy/lib/services/model_proxy/sse.py | 47 +++ .../_internal/proxy/lib/services/usage.py | 63 +++ .../background/scheduled_tasks/__init__.py | 2 + .../background/scheduled_tasks/usage.py | 90 +++++ ..._9a2e8f1f3c37_add_gateway_usage_batches.py | 88 ++++ src/dstack/_internal/server/models.py | 43 ++ .../_internal/server/routers/projects.py | 9 + .../server/services/gateways/client.py | 25 ++ src/dstack/_internal/server/services/usage.py | 94 +++++ .../proxy/gateway/metering/__init__.py | 0 .../proxy/gateway/metering/backend.py | 102 +++++ .../proxy/gateway/metering/benchmark.py | 114 ++++++ .../proxy/gateway/metering/conftest.py | 26 ++ .../proxy/gateway/metering/fixtures.json | 7 + .../proxy/gateway/metering/harness.py | 378 ++++++++++++++++++ .../proxy/gateway/metering/receiver.py | 152 +++++++ .../proxy/gateway/metering/test_helpers.py | 111 +++++ .../proxy/gateway/metering/test_scenarios.py | 337 ++++++++++++++++ .../proxy/gateway/metering/traffic.py | 138 +++++++ .../proxy/gateway/routers/test_config.py | 92 +++++ .../proxy/gateway/routers/test_usage.py | 51 +++ .../proxy/gateway/services/test_metering.py | 276 +++++++++++++ .../gateway/services/test_metering_store.py | 101 +++++ .../_internal/proxy/gateway/test_auth.py | 39 ++ .../proxy/gateway/test_metering_ingress.py | 206 ++++++++++ .../proxy/lib/routers/test_model_proxy.py | 8 +- .../proxy/lib/services/test_openai_usage.py | 278 +++++++++++++ .../_internal/proxy/lib/services/test_sse.py | 28 ++ src/tests/_internal/proxy/lib/test_usage.py | 110 +++++ .../background/scheduled_tasks/test_usage.py | 167 ++++++++ .../_internal/server/routers/test_projects.py | 30 ++ .../services/gateways/test_usage_client.py | 53 +++ .../_internal/server/services/test_usage.py | 96 +++++ 53 files changed, 4329 insertions(+), 81 deletions(-) create mode 100644 src/dstack/_internal/proxy/gateway/routers/usage.py create mode 100644 src/dstack/_internal/proxy/gateway/services/metering.py create mode 100644 src/dstack/_internal/proxy/gateway/services/metering_store.py create mode 100644 src/dstack/_internal/proxy/lib/cancellation.py create mode 100644 src/dstack/_internal/proxy/lib/schemas/usage.py create mode 100644 src/dstack/_internal/proxy/lib/services/model_proxy/sse.py create mode 100644 src/dstack/_internal/proxy/lib/services/usage.py create mode 100644 src/dstack/_internal/server/background/scheduled_tasks/usage.py create mode 100644 src/dstack/_internal/server/migrations/versions/2026/11_16_1201_9a2e8f1f3c37_add_gateway_usage_batches.py create mode 100644 src/dstack/_internal/server/services/usage.py create mode 100644 src/tests/_internal/proxy/gateway/metering/__init__.py create mode 100644 src/tests/_internal/proxy/gateway/metering/backend.py create mode 100644 src/tests/_internal/proxy/gateway/metering/benchmark.py create mode 100644 src/tests/_internal/proxy/gateway/metering/conftest.py create mode 100644 src/tests/_internal/proxy/gateway/metering/fixtures.json create mode 100644 src/tests/_internal/proxy/gateway/metering/harness.py create mode 100644 src/tests/_internal/proxy/gateway/metering/receiver.py create mode 100644 src/tests/_internal/proxy/gateway/metering/test_helpers.py create mode 100644 src/tests/_internal/proxy/gateway/metering/test_scenarios.py create mode 100644 src/tests/_internal/proxy/gateway/metering/traffic.py create mode 100644 src/tests/_internal/proxy/gateway/routers/test_config.py create mode 100644 src/tests/_internal/proxy/gateway/routers/test_usage.py create mode 100644 src/tests/_internal/proxy/gateway/services/test_metering.py create mode 100644 src/tests/_internal/proxy/gateway/services/test_metering_store.py create mode 100644 src/tests/_internal/proxy/gateway/test_metering_ingress.py create mode 100644 src/tests/_internal/proxy/lib/services/test_openai_usage.py create mode 100644 src/tests/_internal/proxy/lib/services/test_sse.py create mode 100644 src/tests/_internal/proxy/lib/test_usage.py create mode 100644 src/tests/_internal/server/background/scheduled_tasks/test_usage.py create mode 100644 src/tests/_internal/server/services/gateways/test_usage_client.py create mode 100644 src/tests/_internal/server/services/test_usage.py diff --git a/contributing/PROXY.md b/contributing/PROXY.md index d053b43d88..b098adf539 100644 --- a/contributing/PROXY.md +++ b/contributing/PROXY.md @@ -169,3 +169,29 @@ sqlite3 ~/.dstack/server/data/sqlite.db "SELECT ssh_private_key FROM gateway_com chmod 600 /tmp/gateway.key ssh -i /tmp/gateway.key ubuntu@$GATEWAY_IP_ADDR sudo journalctl -u dstack.gateway.service ``` + +## Gateway usage metering (DS-002) + +Metering is opt-in per registered OpenAI service via the private `/api/config` field +`usage_metering_profiles` (`service.id` → `vllm-0.19.1-prompt-details`). Legacy updates +that omit the field preserve it; an empty map disables it. Drain changed services +and cross a minute boundary before changing the profile. + +The existing Python model proxy observes backend JSON/SSE usage and obtains a verified +user ID from server's additive `authorize_proxy` endpoint. Counters use that user ID +and the service ID. They describe measured usage, not a payer or a charge. + +Gateway owns `/home/ubuntu/dstack/usage-counters.json` with an active minute and immutable +pending batches. Atomic checkpoints and exact-ID ACK protect closed data; active +observations since the last successful checkpoint can be lost on forced termination. +The `.lock` sidecar enforces one process, and `.initialized` detects missing established state. +Never delete/reset these files as a routine repair: reconcile identity/history first. + +Server polls `/api/usage/batches` over the existing private SSH management connection, +commits idempotent receipts/entries, then POSTs `/api/usage/batches/ack`. No network +work happens inside its database transaction. Old Gateways lacking this API are skipped. + +Public project model endpoints traverse metering; direct service hostnames still bypass it. +Resolve that routing policy before paid use. Token quotas are outside DS-002. Local +scenarios live in `src/tests/_internal/proxy/gateway/metering`; real-minute and real-Nginx +checks are explicit opt-ins. diff --git a/pyproject.toml b/pyproject.toml index 027baa4057..e879f28f06 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -135,6 +135,7 @@ addopts = [ asyncio_default_fixture_loop_scope = "session" asyncio_default_test_loop_scope = "session" markers = [ + "metering_realtime: explicit actual-minute DS-002 acceptance run", "shim_version", "dockerized", ] diff --git a/src/dstack/_internal/proxy/gateway/app.py b/src/dstack/_internal/proxy/gateway/app.py index 6627e9e3f3..f5049581c9 100644 --- a/src/dstack/_internal/proxy/gateway/app.py +++ b/src/dstack/_internal/proxy/gateway/app.py @@ -1,5 +1,8 @@ """FastAPI app running on a gateway.""" +import asyncio +import contextlib +import time from contextlib import asynccontextmanager from pathlib import Path from typing import Optional @@ -24,12 +27,17 @@ from dstack._internal.proxy.gateway.routers.registry import router as registry_router from dstack._internal.proxy.gateway.routers.services import router as services_router from dstack._internal.proxy.gateway.routers.stats import router as stats_router +from dstack._internal.proxy.gateway.routers.usage import router as usage_router +from dstack._internal.proxy.gateway.services.metering import Clock, MeteringCollector +from dstack._internal.proxy.gateway.services.metering_store import MeteringStore from dstack._internal.proxy.gateway.services.nginx import Nginx from dstack._internal.proxy.gateway.services.registry import ACCESS_LOG_PATH, apply_all from dstack._internal.proxy.gateway.services.server_client import HTTPMultiClient from dstack._internal.proxy.gateway.services.stats import StatsCollector +from dstack._internal.proxy.lib.errors import ProxyError from dstack._internal.proxy.lib.routers.model_proxy import router as model_proxy_router from dstack._internal.utils.common import run_async +from dstack._internal.utils.logging import get_logger from dstack.version import __version__ STATE_FILE = DSTACK_DIR_ON_GATEWAY / "state-v2.json" @@ -46,12 +54,27 @@ async def lifespan(app: FastAPI): await run_async(nginx.write_global_conf) await apply_all(repo, nginx, service_conn_pool) - yield + metering = injector.get_metering() + await metering.configure_profiles((await repo.get_config()).usage_metering_profiles) + maintenance = asyncio.create_task(_metering_maintenance(metering)) + try: + yield + finally: + maintenance.cancel() + with contextlib.suppress(asyncio.CancelledError): + await maintenance + try: + await metering.close() + finally: + await service_conn_pool.remove_all() - await service_conn_pool.remove_all() - -def make_app(repo: Optional[GatewayProxyRepo] = None, nginx: Optional[Nginx] = None) -> FastAPI: +def make_app( + repo: Optional[GatewayProxyRepo] = None, + nginx: Optional[Nginx] = None, + metering_store: MeteringStore | None = None, + clock: Clock | None = None, +) -> FastAPI: if repo is None: migrate_from_state_v1( v1_file=LEGACY_STATE_FILE, v2_file=STATE_FILE, keys_dir=LEGACY_KEYS_DIR @@ -66,6 +89,10 @@ def make_app(repo: Optional[GatewayProxyRepo] = None, nginx: Optional[Nginx] = N ), nginx=nginx or Nginx(), stats_collector=StatsCollector(ACCESS_LOG_PATH), + metering=MeteringCollector( + metering_store or MeteringStore(DSTACK_DIR_ON_GATEWAY / "usage-counters.json"), + clock=clock, + ), ) # TODO: add CORS only to openai routers once fastapi supports it. @@ -83,9 +110,23 @@ def make_app(repo: Optional[GatewayProxyRepo] = None, nginx: Optional[Nginx] = N app.include_router(registry_router, prefix="/api/registry") app.include_router(services_router, prefix="/api/services") app.include_router(stats_router, prefix="/api/stats") + app.include_router(usage_router, prefix="/api/usage") @app.get("/") def get_info(): return {"version": __version__} return app + + +async def _metering_maintenance(metering: MeteringCollector) -> None: + last_checkpoint = time.monotonic() + while True: + await asyncio.sleep(1) + try: + await metering.rotate_if_due() + if time.monotonic() - last_checkpoint >= 60: + await metering.checkpoint() + last_checkpoint = time.monotonic() + except (OSError, ValueError, ProxyError): + get_logger(__name__).exception("Usage maintenance failed; metered admission paused") diff --git a/src/dstack/_internal/proxy/gateway/auth.py b/src/dstack/_internal/proxy/gateway/auth.py index f71f9845d1..c55b3b80d7 100644 --- a/src/dstack/_internal/proxy/gateway/auth.py +++ b/src/dstack/_internal/proxy/gateway/auth.py @@ -1,8 +1,12 @@ +import uuid + import httpx2 as httpx from aiocache import cached +from pydantic import ValidationError from dstack._internal.proxy.lib.auth import BaseProxyAuthProvider from dstack._internal.proxy.lib.errors import UnexpectedProxyError +from dstack._internal.proxy.lib.schemas.usage import AuthorizedSubject _AUTH_CACHE_TTL_SECONDS = 60 """Seconds to cache allowed or denied access for each project/token pair.""" @@ -11,8 +15,13 @@ class GatewayProxyAuthProvider(BaseProxyAuthProvider): def __init__(self, server_client: httpx.AsyncClient) -> None: self._server_client = server_client + self._cache_namespace = uuid.uuid4().hex - @cached(ttl=_AUTH_CACHE_TTL_SECONDS, noself=True, skip_cache_func=lambda r: r is None) + @cached( + ttl=_AUTH_CACHE_TTL_SECONDS, + key_builder=lambda f, self, project, token: repr((self._cache_namespace, project, token)), + skip_cache_func=lambda r: r is None, + ) async def is_project_member(self, project_name: str, token: str) -> bool: try: resp = await self._server_client.post( @@ -27,3 +36,24 @@ async def is_project_member(self, project_name: str, token: str) -> bool: f"Failed requesting dstack-server to check access: {e!r}" ) from e return True + + async def resolve_subject(self, project_name: str, token: str) -> AuthorizedSubject | None: + return await self._resolve_subject(project_name, token) + + @cached( + ttl=_AUTH_CACHE_TTL_SECONDS, + key_builder=lambda f, self, project, token: repr((self._cache_namespace, project, token)), + skip_cache_func=lambda result: result is None, + ) + async def _resolve_subject(self, project_name: str, token: str) -> AuthorizedSubject | None: + try: + response = await self._server_client.post( + f"/api/projects/{project_name}/authorize_proxy", + headers={"Authorization": f"Bearer {token}"}, + ) + if response.status_code in (401, 403, 404, 405): + return None + response.raise_for_status() + return AuthorizedSubject.model_validate_json(response.content) + except (httpx.HTTPError, ValidationError) as exc: + raise UnexpectedProxyError("Failed to resolve verified proxy identity") from exc diff --git a/src/dstack/_internal/proxy/gateway/deps.py b/src/dstack/_internal/proxy/gateway/deps.py index 009ce8da15..44debc0750 100644 --- a/src/dstack/_internal/proxy/gateway/deps.py +++ b/src/dstack/_internal/proxy/gateway/deps.py @@ -1,8 +1,10 @@ +import asyncio from typing import Annotated, AsyncGenerator from fastapi import Depends, FastAPI, Request from dstack._internal.proxy.gateway.repo.repo import GatewayProxyRepo +from dstack._internal.proxy.gateway.services.metering import MeteringCollector from dstack._internal.proxy.gateway.services.nginx import Nginx from dstack._internal.proxy.gateway.services.stats import StatsCollector from dstack._internal.proxy.lib.auth import BaseProxyAuthProvider @@ -22,12 +24,15 @@ def __init__( auth: BaseProxyAuthProvider, nginx: Nginx, stats_collector: StatsCollector, + metering: MeteringCollector | None = None, ) -> None: super().__init__() self._repo = repo self._auth = auth self._nginx = nginx self._stats_collector = stats_collector + self._metering = metering + self.config_lock = asyncio.Lock() async def get_repo(self) -> AsyncGenerator[BaseProxyRepo, None]: yield self._repo @@ -35,6 +40,14 @@ async def get_repo(self) -> AsyncGenerator[BaseProxyRepo, None]: async def get_auth_provider(self) -> AsyncGenerator[BaseProxyAuthProvider, None]: yield self._auth + def get_usage_observer(self): + return self._metering or super().get_usage_observer() + + def get_metering(self) -> MeteringCollector: + if self._metering is None: + raise UnexpectedProxyError("Gateway metering dependency is missing") + return self._metering + def get_nginx(self) -> Nginx: return self._nginx @@ -71,3 +84,9 @@ async def get_stats_collector( injector: Annotated[GatewayDependencyInjector, Depends(get_gateway_injector)], ) -> StatsCollector: return injector.get_stats_collector() + + +async def get_metering( + injector: Annotated[GatewayDependencyInjector, Depends(get_gateway_injector)], +) -> MeteringCollector: + return injector.get_metering() diff --git a/src/dstack/_internal/proxy/gateway/models.py b/src/dstack/_internal/proxy/gateway/models.py index 80ce0b8abe..c1254fd97b 100644 --- a/src/dstack/_internal/proxy/gateway/models.py +++ b/src/dstack/_internal/proxy/gateway/models.py @@ -1,8 +1,8 @@ """Things stored in GatewayProxyRepo in addition to those from BaseProxyRepo.""" -from typing import Optional +from typing import Literal, Optional -from pydantic import AnyHttpUrl +from pydantic import AnyHttpUrl, Field from dstack._internal.proxy.lib.const import DEFAULT_SERVICE_READ_TIMEOUT from dstack._internal.proxy.lib.models import ImmutableModel @@ -23,3 +23,6 @@ class ACMESettings(ImmutableModel): class GlobalProxyConfig(ImmutableModel): acme_settings: ACMESettings = ACMESettings() + usage_metering_profiles: dict[str, Literal["vllm-0.19.1-prompt-details"]] = Field( + default_factory=dict + ) diff --git a/src/dstack/_internal/proxy/gateway/routers/config.py b/src/dstack/_internal/proxy/gateway/routers/config.py index 24dac6a52f..2827e47960 100644 --- a/src/dstack/_internal/proxy/gateway/routers/config.py +++ b/src/dstack/_internal/proxy/gateway/routers/config.py @@ -2,11 +2,18 @@ from fastapi import APIRouter, Depends -from dstack._internal.proxy.gateway.deps import get_gateway_proxy_repo -from dstack._internal.proxy.gateway.models import ACMESettings, GlobalProxyConfig +from dstack._internal.proxy.gateway.deps import ( + GatewayDependencyInjector, + get_gateway_injector, + get_gateway_proxy_repo, + get_metering, +) from dstack._internal.proxy.gateway.repo.repo import GatewayProxyRepo from dstack._internal.proxy.gateway.schemas.common import OkResponse from dstack._internal.proxy.gateway.schemas.config import ConfigRequest +from dstack._internal.proxy.gateway.services.metering import MeteringCollector +from dstack._internal.proxy.lib.errors import ProxyError +from dstack._internal.proxy.lib.models import OpenAIChatModelFormat router = APIRouter() @@ -15,14 +22,39 @@ async def update_global_config( body: ConfigRequest, repo: Annotated[GatewayProxyRepo, Depends(get_gateway_proxy_repo)], + metering: Annotated[MeteringCollector, Depends(get_metering)], + injector: Annotated[GatewayDependencyInjector, Depends(get_gateway_injector)], ) -> OkResponse: - await repo.set_config( - GlobalProxyConfig( - acme_settings=ACMESettings( - server=body.acme_server, - eab_kid=body.acme_eab_kid, - eab_hmac_key=body.acme_eab_hmac_key, - ), - ), - ) - return OkResponse() + async with injector.config_lock: + config = await repo.get_config() + acme_changes = { + name.removeprefix("acme_"): getattr(body, name) + for name in body.model_fields_set + if name.startswith("acme_") + } + profiles = config.usage_metering_profiles + if "usage_metering_profiles" in body.model_fields_set: + if body.usage_metering_profiles is None: + raise ProxyError("Metering profiles must be an object; omit to preserve") + profiles = body.usage_metering_profiles + eligible = set() + for service in await repo.list_services(): + for model in await repo.list_models(service.project_name): + if model.run_name == service.run_name and isinstance( + model.format_spec, OpenAIChatModelFormat + ): + eligible.add(service.id) + if not profiles.keys() <= eligible: + raise ProxyError("Metering requires a registered OpenAI service with a stable ID") + updated = config.model_copy( + update={ + "acme_settings": config.acme_settings.model_copy(update=acme_changes), + "usage_metering_profiles": profiles, + } + ) + + async def persist() -> None: + await repo.set_config(updated) + + await metering.configure_profiles(profiles, persist=persist) + return OkResponse() diff --git a/src/dstack/_internal/proxy/gateway/routers/usage.py b/src/dstack/_internal/proxy/gateway/routers/usage.py new file mode 100644 index 0000000000..63f486c106 --- /dev/null +++ b/src/dstack/_internal/proxy/gateway/routers/usage.py @@ -0,0 +1,31 @@ +"""Private management API: exposed only through the server's SSH connection.""" + +from typing import Annotated + +from fastapi import APIRouter, Depends, Query + +from dstack._internal.proxy.gateway.deps import get_metering +from dstack._internal.proxy.gateway.services.metering import MeteringCollector +from dstack._internal.proxy.lib.schemas.usage import ( + UsageAckRequest, + UsageAckResponse, + UsageBatchPage, +) + +router = APIRouter() + + +@router.get("/batches", response_model=UsageBatchPage) +async def get_batches( + metering: Annotated[MeteringCollector, Depends(get_metering)], + limit: Annotated[int, Query(ge=1, le=100)] = 100, +) -> UsageBatchPage: + return await metering.get_batches(limit) + + +@router.post("/batches/ack", response_model=UsageAckResponse) +async def acknowledge_batches( + body: UsageAckRequest, + metering: Annotated[MeteringCollector, Depends(get_metering)], +) -> UsageAckResponse: + return await metering.acknowledge(body.batch_ids) diff --git a/src/dstack/_internal/proxy/gateway/schemas/config.py b/src/dstack/_internal/proxy/gateway/schemas/config.py index 09cfc2101f..da21202ef3 100644 --- a/src/dstack/_internal/proxy/gateway/schemas/config.py +++ b/src/dstack/_internal/proxy/gateway/schemas/config.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Literal, Optional from pydantic import AnyHttpUrl, BaseModel @@ -7,3 +7,4 @@ class ConfigRequest(BaseModel): acme_server: Optional[AnyHttpUrl] = None acme_eab_kid: Optional[str] = None acme_eab_hmac_key: Optional[str] = None + usage_metering_profiles: Optional[dict[str, Literal["vllm-0.19.1-prompt-details"]]] = None diff --git a/src/dstack/_internal/proxy/gateway/services/metering.py b/src/dstack/_internal/proxy/gateway/services/metering.py new file mode 100644 index 0000000000..8ed56f2d35 --- /dev/null +++ b/src/dstack/_internal/proxy/gateway/services/metering.py @@ -0,0 +1,310 @@ +"""Gateway minute accumulator. Closed data is published only after durable storage.""" + +import asyncio +import uuid +from collections.abc import Awaitable, Callable, Mapping +from datetime import datetime, timedelta, timezone +from typing import Any + +from dstack._internal.proxy.gateway.services.metering_store import MeteringStore +from dstack._internal.proxy.lib.cancellation import await_completion +from dstack._internal.proxy.lib.errors import ProxyError +from dstack._internal.proxy.lib.schemas.usage import ( + TokenUsage, + UsageAckResponse, + UsageBatch, + UsageBatchPage, + UsageCheckpoint, + UsageEntry, + UsageKey, +) +from dstack._internal.proxy.lib.services.usage import ( + VLLM_PROFILE, + UsageAttempt, + UsageObserver, + normalize_usage, +) +from dstack._internal.utils.logging import get_logger + +logger = get_logger(__name__) + + +class Clock: + def utc_now(self) -> datetime: + return datetime.now(timezone.utc) + + +class MeteringCollector(UsageObserver): + def __init__( + self, + store: MeteringStore, + clock: Clock | None = None, + profiles: Mapping[str, str] | None = None, + max_pending: int = 1440, + max_entries: int = 10000, + ): + self.store = store + self.clock = clock or Clock() + self.profiles = dict(profiles or {}) + self.max_pending = max_pending + self.max_entries = max_entries + self._lock = asyncio.Lock() + self._state: UsageCheckpoint | None = None + self._entries: dict[UsageKey, UsageEntry] = {} + self._published: set[str] = set() + self._attempts: set[MeteringAttempt] = set() + self._storage_error: Exception | None = None + self._clock_error = False + self._last_time: datetime | None = None + self._closed = False + self._pending_bytes = 0 + self._reconfiguring = False + + async def start(self) -> None: + async with self._lock: + if self._state is not None: + return + if not self.profiles and not self.store.exists(): + return + saved = await asyncio.to_thread(self.store.load) + now = self.clock.utc_now() + self._state = saved or UsageCheckpoint( + collector_id=uuid.uuid4().hex, active_batch=self._new_batch(now) + ) + self._entries = {entry.key: entry for entry in self._state.active_batch.entries} + self._published = {batch.batch_id for batch in self._state.pending_batches} + self._pending_bytes = sum( + len(b.model_dump_json().encode()) for b in self._state.pending_batches + ) + self._last_time = self._state.active_batch.interval_start + await self._rotate(now) + await self._save(self._snapshot()) + + async def configure_profiles( + self, profiles: Mapping[str, str], persist: Callable[[], Awaitable[None]] | None = None + ) -> None: + async with self._lock: + self._reconfiguring = True + try: + if any(profile != VLLM_PROFILE for profile in profiles.values()): + raise ProxyError("Unsupported metering profile") + changed = { + key + for key in self.profiles.keys() | profiles.keys() + if self.profiles.get(key) != profiles.get(key) + } + if any(attempt.key.service_id in changed for attempt in self._attempts): + raise ProxyError("Drain in-flight requests before changing metering", 409) + if self._state is not None: + if await self._rotate(self.clock.utc_now()): + await self._save(self._snapshot()) + if any(key.service_id in changed for key in self._entries): + raise ProxyError("Change metering at a drained minute boundary", 409) + if persist is not None: + await persist() + self.profiles = dict(profiles) + finally: + self._reconfiguring = False + await self.start() + + def profile_for(self, service_id: str | None) -> str | None: + return self.profiles.get(service_id) if service_id is not None else None + + def start_attempt(self, key: UsageKey, profile: str) -> UsageAttempt: + if ( + self._closed + or self._reconfiguring + or self._state is None + or self._storage_error + or self._clock_error + or self.profile_for(key.service_id) != profile + or profile != VLLM_PROFILE + ): + raise ProxyError("Usage metering is unavailable", 503) + keys = set(self._entries) | {attempt.key for attempt in self._attempts} | {key} + # Headroom covers pending records and already admitted requests, including late finishers. + estimated_bytes = ( + self._pending_bytes + (len(self._entries) + len(self._attempts) + 1) * 1024 + 512 + ) + if ( + len(keys) > self.max_entries + or len(self._state.pending_batches) + len(self._attempts) + 1 >= self.max_pending + or estimated_bytes > self.store.max_bytes + ): + raise ProxyError("Usage storage is full; collection is required", 503) + attempt = MeteringAttempt(self, key, profile) + self._attempts.add(attempt) + return attempt + + async def rotate_if_due(self) -> None: + async with self._lock: + if self._state is None: + return + changed = await self._rotate(self.clock.utc_now()) + if changed or self._storage_error: + await self._save(self._snapshot()) + + async def get_batches(self, limit: int = 100) -> UsageBatchPage: + if not 1 <= limit <= 100: + raise ProxyError("Batch limit must be between 1 and 100") + async with self._lock: + if self._state is None: + raise ProxyError("Usage metering is not initialized", 404) + batches = [b for b in self._state.pending_batches if b.batch_id in self._published] + return UsageBatchPage( + collector_id=self._state.collector_id, + batches=batches[:limit], + has_more=len(batches) > limit, + ).model_copy(deep=True) + + async def acknowledge(self, batch_ids: list[str]) -> UsageAckResponse: + async with self._lock: + if self._state is None: + raise ProxyError("Usage metering is not initialized", 404) + ids = set(batch_ids) + if self._state.active_batch.batch_id in ids: + raise ProxyError("Cannot acknowledge the active interval") + if any( + b.batch_id in ids and b.batch_id not in self._published + for b in self._state.pending_batches + ): + raise ProxyError("Cannot acknowledge an unpublished batch") + state = self._snapshot() + candidate = state.model_copy( + update={ + "pending_batches": [b for b in state.pending_batches if b.batch_id not in ids] + } + ) + await self._save(candidate) + self._state = candidate + self._pending_bytes = sum( + len(b.model_dump_json().encode()) for b in candidate.pending_batches + ) + return UsageAckResponse(acknowledged_batch_ids=list(dict.fromkeys(batch_ids))) + + async def checkpoint(self) -> None: + async with self._lock: + if self._state is not None: + await self._save(self._snapshot()) + + async def close(self) -> None: + self._closed = True + try: + for attempt in list(self._attempts): + await attempt.finish() + await self.checkpoint() + finally: + self.store.close() + + async def _finish(self, attempt: "MeteringAttempt") -> None: + async with self._lock: + if attempt.finished: + return + if not attempt.dispatched: + attempt.finished = True + self._attempts.discard(attempt) + return + try: + rotated = await self._rotate(self.clock.utc_now()) + except ProxyError: + # Cannot classify a backward-clock observation into a closed interval. + # Keep the attempt for reconciliation; do not silently discard it. + logger.error("Usage finalization paused after a backward clock jump") + raise + previous = self._entries.get(attempt.key) or UsageEntry(**attempt.key.model_dump()) + usage = attempt.usage or TokenUsage() + values = { + name: getattr(previous, name) + getattr(usage, name) + for name in TokenUsage.model_fields + } + self._entries[attempt.key] = UsageEntry( + **attempt.key.model_dump(), + **values, + unknown_usage_attempts=previous.unknown_usage_attempts + + int(attempt.usage is None), + ) + attempt.finished = True + self._attempts.discard(attempt) + if rotated: + try: + await self._save(self._snapshot()) + except (OSError, ValueError): + logger.exception("Usage retained in memory after checkpoint failure") + + async def _rotate(self, now: datetime) -> bool: + assert self._state is not None + if self._last_time is not None and now < self._last_time: + self._clock_error = True + raise ProxyError("Usage clock moved backwards; reconciliation is required", 503) + self._last_time = now + if now < self._state.active_batch.interval_end: + return False + previous = self._state.active_batch.model_copy( + update={"entries": list(self._entries.values())} + ) + pending = [*self._state.pending_batches] + if previous.entries: + pending.append(previous) + self._pending_bytes += len(previous.model_dump_json().encode()) + self._state = self._state.model_copy( + update={"active_batch": self._new_batch(now), "pending_batches": pending} + ) + self._entries = {} + return True + + def _snapshot(self) -> UsageCheckpoint: + assert self._state is not None + return self._state.model_copy( + update={ + "active_batch": self._state.active_batch.model_copy( + update={"entries": list(self._entries.values())} + ) + }, + deep=True, + ) + + async def _save(self, state: UsageCheckpoint) -> None: + try: + await self.store.save(state) + except (OSError, ValueError) as exc: + self._storage_error = exc + raise + self._published = {batch.batch_id for batch in state.pending_batches} + self._storage_error = None + + @staticmethod + def _new_batch(now: datetime) -> UsageBatch: + start = now.astimezone(timezone.utc).replace(second=0, microsecond=0) + return UsageBatch( + batch_id=uuid.uuid4().hex, + interval_start=start, + interval_end=start + timedelta(seconds=60), + ) + + +class MeteringAttempt(UsageAttempt): + def __init__(self, collector: MeteringCollector, key: UsageKey, profile: str): + self.collector = collector + self.key = key + self.profile = profile + self.dispatched = False + self.upstream_done = False + self.finished = False + self.usage: TokenUsage | None = None + self._finish_task: asyncio.Task[None] | None = None + + def observe_usage(self, usage: Any) -> None: + confirmed = normalize_usage(usage, self.profile) + if confirmed is not None: + self.usage = confirmed + + def mark_dispatched(self) -> None: + self.dispatched = True + + def mark_upstream_done(self) -> None: + self.upstream_done = True + + async def finish(self) -> None: + if self._finish_task is None: + self._finish_task = asyncio.create_task(self.collector._finish(self)) + await await_completion(self._finish_task) diff --git a/src/dstack/_internal/proxy/gateway/services/metering_store.py b/src/dstack/_internal/proxy/gateway/services/metering_store.py new file mode 100644 index 0000000000..612834da1d --- /dev/null +++ b/src/dstack/_internal/proxy/gateway/services/metering_store.py @@ -0,0 +1,105 @@ +"""Single-owner, atomic local checkpoint storage for minute usage batches.""" + +import asyncio +import fcntl +import json +import os +import tempfile +from pathlib import Path +from typing import Any + +from dstack._internal.proxy.lib.cancellation import await_completion +from dstack._internal.proxy.lib.schemas.usage import UsageCheckpoint + + +class MeteringStore: + def __init__(self, path: Path, max_bytes: int = 64 * 1024 * 1024): + self.path = path + self.max_bytes = max_bytes + self._marker = path.with_suffix(path.suffix + ".initialized") + self._owner_fd: int | None = None + self._write_lock = asyncio.Lock() + + def exists(self) -> bool: + return self.path.exists() or self._marker.exists() + + def load(self) -> UsageCheckpoint | None: + self._ensure_owner() + if not self.path.exists(): + if self._marker.exists(): + raise ValueError( + "Initialized usage checkpoint is missing; reconcile before restart" + ) + return None + with self.path.open("rb") as source: + raw = source.read(self.max_bytes + 1) + if len(raw) > self.max_bytes: + raise ValueError("Usage checkpoint exceeds size limit") + state = UsageCheckpoint.model_validate(json.loads(raw, object_pairs_hook=_unique_object)) + if self._marker.exists() and self._marker.read_text() != state.collector_id: + raise ValueError("Usage collector identity mismatch") + return state + + async def save(self, state: UsageCheckpoint) -> None: + # Deep copy before crossing the thread boundary; the writer owns a consistent snapshot. + snapshot = state.model_copy(deep=True) + async with self._write_lock: + writer = asyncio.create_task(asyncio.to_thread(self._save, snapshot)) + # The thread survives Task.cancel(); keep ownership until it actually finishes, + # even if shutdown or an HTTP disconnect cancels this coroutine repeatedly. + await await_completion(writer) + + def close(self) -> None: + if self._owner_fd is not None: + os.close(self._owner_fd) + self._owner_fd = None + + def _ensure_owner(self) -> None: + if self._owner_fd is not None: + return + self.path.parent.mkdir(parents=True, exist_ok=True) + fd = os.open(str(self.path) + ".lock", os.O_CREAT | os.O_RDWR, 0o600) + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BaseException: + os.close(fd) + raise + self._owner_fd = fd + + def _save(self, state: UsageCheckpoint) -> None: + self._ensure_owner() + raw = state.model_dump_json().encode() + if len(raw) > self.max_bytes: + raise OSError("Usage checkpoint exceeds storage limit") + if self._marker.exists() and self._marker.read_text() != state.collector_id: + raise ValueError("Refusing to replace collector identity") + self._atomic_write(self.path, raw) + if not self._marker.exists(): + self._atomic_write(self._marker, state.collector_id.encode()) + + @staticmethod + def _atomic_write(path: Path, raw: bytes) -> None: + fd, name = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=path.parent) + try: + with os.fdopen(fd, "wb") as target: + target.write(raw) + target.flush() + os.fsync(target.fileno()) + os.replace(name, path) + directory = os.open(path.parent, os.O_RDONLY) + try: + os.fsync(directory) + finally: + os.close(directory) + finally: + if os.path.exists(name): + os.unlink(name) + + +def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result = {} + for key, value in pairs: + if key in result: + raise ValueError(f"Duplicate checkpoint field: {key}") + result[key] = value + return result diff --git a/src/dstack/_internal/proxy/lib/auth.py b/src/dstack/_internal/proxy/lib/auth.py index 382df2c468..5401e0cd70 100644 --- a/src/dstack/_internal/proxy/lib/auth.py +++ b/src/dstack/_internal/proxy/lib/auth.py @@ -1,7 +1,12 @@ from abc import ABC, abstractmethod +from dstack._internal.proxy.lib.schemas.usage import AuthorizedSubject + class BaseProxyAuthProvider(ABC): @abstractmethod async def is_project_member(self, project_name: str, token: str) -> bool: pass + + async def resolve_subject(self, project_name: str, token: str) -> AuthorizedSubject | None: + return None diff --git a/src/dstack/_internal/proxy/lib/cancellation.py b/src/dstack/_internal/proxy/lib/cancellation.py new file mode 100644 index 0000000000..eeafe2958e --- /dev/null +++ b/src/dstack/_internal/proxy/lib/cancellation.py @@ -0,0 +1,23 @@ +"""Complete owned cleanup before propagating cancellation to the caller.""" + +import asyncio +from typing import TypeVar + +import anyio + +T = TypeVar("T") + + +async def await_completion(task: asyncio.Task[T]) -> T: + cancelled: asyncio.CancelledError | None = None + # AnyIO's level cancellation and repeated direct Task.cancel() both occur in HTTP shutdown. + with anyio.CancelScope(shield=True): + while not task.done(): + try: + await asyncio.shield(task) + except asyncio.CancelledError as exc: + cancelled = exc + result = task.result() + if cancelled is not None: + raise cancelled + return result diff --git a/src/dstack/_internal/proxy/lib/deps.py b/src/dstack/_internal/proxy/lib/deps.py index c080ca3e4e..6d3773e6f0 100644 --- a/src/dstack/_internal/proxy/lib/deps.py +++ b/src/dstack/_internal/proxy/lib/deps.py @@ -7,7 +7,9 @@ from dstack._internal.proxy.lib.auth import BaseProxyAuthProvider from dstack._internal.proxy.lib.errors import ProxyError, UnexpectedProxyError from dstack._internal.proxy.lib.repo import BaseProxyRepo +from dstack._internal.proxy.lib.schemas.usage import AuthorizedSubject from dstack._internal.proxy.lib.services.service_connection import ServiceConnectionPool +from dstack._internal.proxy.lib.services.usage import UsageObserver class ProxyDependencyInjector(ABC): @@ -32,6 +34,9 @@ def get_repo(self) -> AsyncGenerator[BaseProxyRepo, None]: def get_auth_provider(self) -> AsyncGenerator[BaseProxyAuthProvider, None]: pass + def get_usage_observer(self) -> UsageObserver: + return UsageObserver() + async def get_service_connection_pool(self) -> ServiceConnectionPool: return self._service_conn_pool @@ -72,6 +77,14 @@ def __init__(self, project_name: str, token: Optional[str], provider: BaseProxyA self._project_name = project_name self._token = token self._provider = provider + self._subject: AuthorizedSubject | None = None + + async def require_subject(self) -> AuthorizedSubject: + if self._subject is None and self._token is not None: + self._subject = await self._provider.resolve_subject(self._project_name, self._token) + if self._subject is None: + raise ProxyError("Verified identity is required for metered inference", 403) + return self._subject async def enforce(self) -> None: if self._token is None or not await self._provider.is_project_member( diff --git a/src/dstack/_internal/proxy/lib/routers/model_proxy.py b/src/dstack/_internal/proxy/lib/routers/model_proxy.py index f348957f4a..f53f65fcbb 100644 --- a/src/dstack/_internal/proxy/lib/routers/model_proxy.py +++ b/src/dstack/_internal/proxy/lib/routers/model_proxy.py @@ -1,9 +1,20 @@ +import asyncio from typing import Annotated, AsyncIterator, Optional +import anyio from fastapi import APIRouter, Depends, status from fastapi.responses import StreamingResponse +from starlette.types import Receive, Scope, Send -from dstack._internal.proxy.lib.deps import ProxyAuth, get_proxy_repo, get_service_connection_pool +from dstack._internal.proxy.lib.cancellation import await_completion +from dstack._internal.proxy.lib.deps import ( + ProxyAuth, + ProxyAuthContext, + ProxyDependencyInjector, + get_injector, + get_proxy_repo, + get_service_connection_pool, +) from dstack._internal.proxy.lib.errors import ProxyError, UnexpectedProxyError from dstack._internal.proxy.lib.repo import BaseProxyRepo from dstack._internal.proxy.lib.schemas.model_proxy import ( @@ -13,13 +24,16 @@ Model, ModelsResponse, ) +from dstack._internal.proxy.lib.schemas.usage import UsageKey from dstack._internal.proxy.lib.services.model_proxy.model_proxy import get_chat_client from dstack._internal.proxy.lib.services.service_connection import ( ServiceConnectionPool, get_service_replica_client, ) +from dstack._internal.proxy.lib.services.usage import UsageAttempt -router = APIRouter(dependencies=[Depends(ProxyAuth(auto_enforce=True))]) +_model_auth = ProxyAuth(auto_enforce=True) +router = APIRouter(dependencies=[Depends(_model_auth)]) @router.get("/{project_name}/models") @@ -40,6 +54,8 @@ async def post_chat_completions( body: ChatCompletionsRequest, repo: Annotated[BaseProxyRepo, Depends(get_proxy_repo)], service_conn_pool: Annotated[ServiceConnectionPool, Depends(get_service_connection_pool)], + auth: Annotated[ProxyAuthContext, Depends(_model_auth)], + injector: Annotated[ProxyDependencyInjector, Depends(get_injector)], ): model = await repo.get_model(project_name, body.model) if model is None: @@ -52,16 +68,40 @@ async def post_chat_completions( f"Model {model.name} in project {project_name} references run {model.run_name}" " that does not exist or has no replicas" ) - http_client = await get_service_replica_client(service, repo, service_conn_pool) - client = get_chat_client(model, http_client) - if not body.stream: - return await client.generate(body) - else: - return StreamingResponse( - await StreamingAdaptor(client.stream(body)).get_stream(), + observer = injector.get_usage_observer() + profile = observer.profile_for(service.id) + attempt = None + if profile is not None: + if service.id is None or model.format_spec.format != "openai": + raise ProxyError("Metering requires a registered OpenAI service", 503) + subject = await auth.require_subject() + attempt = observer.start_attempt( + UsageKey(consumer_subject_id=subject.consumer_subject_id, service_id=service.id), + profile, + ) + transferred = False + try: + http_client = await get_service_replica_client(service, repo, service_conn_pool) + client = get_chat_client(model, http_client) + if not body.stream: + if attempt is None: + return await client.generate(body) + return await client.generate(body, attempt=attempt) + source = client.stream(body) if attempt is None else client.stream(body, attempt=attempt) + adaptor = StreamingAdaptor(source, attempt=attempt) + stream = await adaptor.get_stream() + response = MeteredStreamingResponse( + stream, + adaptor=adaptor, media_type="text/event-stream", headers={"X-Accel-Buffering": "no"}, ) + transferred = True + return response + finally: + if attempt is not None and not transferred: + with anyio.CancelScope(shield=True): + await attempt.finish() class StreamingAdaptor: @@ -71,8 +111,12 @@ class StreamingAdaptor: so that upstream request errors can propagate to the downstream client. """ - def __init__(self, stream: AsyncIterator[ChatCompletionsChunk]) -> None: + def __init__( + self, stream: AsyncIterator[ChatCompletionsChunk], attempt: UsageAttempt | None = None + ) -> None: self._stream = stream + self._attempt = attempt + self._close_task: asyncio.Task | None = None async def get_stream(self) -> AsyncIterator[bytes]: try: @@ -82,20 +126,46 @@ async def get_stream(self) -> AsyncIterator[bytes]: return self._adaptor(first_chunk) async def _adaptor(self, first_chunk: Optional[ChatCompletionsChunk]) -> AsyncIterator[bytes]: - if first_chunk is not None: - yield self._encode_chunk(first_chunk) + try: + if first_chunk is not None: + yield self._encode_chunk(first_chunk) + try: + async for chunk in self._stream: + yield self._encode_chunk(chunk) + except ProxyError as exc: + yield f": {exc.detail!r}\n\n".encode() + return + yield b"data: [DONE]\n\n" + finally: + await self.aclose() - try: - async for chunk in self._stream: - yield self._encode_chunk(chunk) - except ProxyError as e: - # No standard way to report errors while streaming, - # but we'll at least send them as comments - yield f": {e.detail!r}\n\n".encode() # !r to avoid line breaks - return + async def aclose(self) -> None: + if self._close_task is None: + self._close_task = asyncio.create_task(self._close()) + await await_completion(self._close_task) - yield "data: [DONE]\n\n".encode() + async def _close(self) -> None: + try: + close = getattr(self._stream, "aclose", None) + if close is not None: + await close() + finally: + if self._attempt is not None: + await self._attempt.finish() @staticmethod def _encode_chunk(chunk: ChatCompletionsChunk) -> bytes: - return f"data:{chunk.model_dump_json()}\n\n".encode() + encoded = chunk.model_dump_json(exclude={"usage"} if chunk.usage is None else None) + return f"data:{encoded}\n\n".encode() + + +class MeteredStreamingResponse(StreamingResponse): + def __init__(self, content, *, adaptor: StreamingAdaptor, **kwargs): + super().__init__(content, **kwargs) + self._adaptor = adaptor + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + try: + await super().__call__(scope, receive, send) + finally: + await self._adaptor.aclose() diff --git a/src/dstack/_internal/proxy/lib/schemas/model_proxy.py b/src/dstack/_internal/proxy/lib/schemas/model_proxy.py index 632a490dc4..04d54aa0c7 100644 --- a/src/dstack/_internal/proxy/lib/schemas/model_proxy.py +++ b/src/dstack/_internal/proxy/lib/schemas/model_proxy.py @@ -8,6 +8,14 @@ class ChatMessage(CoreModel): content: str +class StreamOptions(CoreModel): + include_usage: bool = False + + +class PromptTokensDetails(CoreModel): + cached_tokens: Optional[int] = None + + class ChatCompletionsRequest(CoreModel): messages: List[ChatMessage] model: str @@ -20,6 +28,7 @@ class ChatCompletionsRequest(CoreModel): seed: Optional[int] = None stop: Optional[Union[str, List[str]]] = None stream: bool = False + stream_options: Optional[StreamOptions] = None temperature: Optional[float] = 1.0 top_p: Optional[float] = 1.0 tools: List[Any] = [] @@ -44,6 +53,7 @@ class ChatCompletionsUsage(CoreModel): completion_tokens: int prompt_tokens: int total_tokens: int + prompt_tokens_details: Optional[PromptTokensDetails] = None class ChatCompletionsResponse(CoreModel): @@ -63,6 +73,7 @@ class ChatCompletionsChunk(CoreModel): model: str system_fingerprint: Optional[str] = "" object: Literal["chat.completion.chunk"] = "chat.completion.chunk" + usage: Optional[ChatCompletionsUsage] = None class Model(CoreModel): diff --git a/src/dstack/_internal/proxy/lib/schemas/usage.py b/src/dstack/_internal/proxy/lib/schemas/usage.py new file mode 100644 index 0000000000..ba576b802d --- /dev/null +++ b/src/dstack/_internal/proxy/lib/schemas/usage.py @@ -0,0 +1,106 @@ +"""Versioned minute aggregates shared by Gateway and its receivers.""" + +from datetime import datetime, timedelta +from typing import Annotated, Literal, Self + +from pydantic import BaseModel, ConfigDict, Field, model_validator + +Counter = Annotated[int, Field(strict=True, ge=0)] +Identifier = Annotated[str, Field(strict=True, min_length=1, max_length=128)] + + +class UsageModel(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + +class AuthorizedSubject(UsageModel): + consumer_subject_id: Identifier + + +class UsageKey(AuthorizedSubject): + service_id: Identifier + + def __hash__(self) -> int: + return hash((self.consumer_subject_id, self.service_id)) + + +class TokenUsage(UsageModel): + prompt_tokens: Counter = 0 + cached_prompt_tokens: Counter = 0 + completion_tokens: Counter = 0 + total_tokens: Counter = 0 + + @model_validator(mode="after") + def check_totals(self) -> Self: + if self.cached_prompt_tokens > self.prompt_tokens: + raise ValueError("Cached tokens exceed prompt tokens") + if self.total_tokens != self.prompt_tokens + self.completion_tokens: + raise ValueError("Total tokens must equal prompt plus completion") + return self + + +class UsageEntry(TokenUsage, UsageKey): + unknown_usage_attempts: Counter = 0 + + @property + def key(self) -> UsageKey: + return UsageKey(consumer_subject_id=self.consumer_subject_id, service_id=self.service_id) + + +class UsageBatch(UsageModel): + batch_id: Identifier + interval_start: datetime + interval_end: datetime + entries: list[UsageEntry] = Field(default_factory=list) + + @model_validator(mode="after") + def check_interval_and_keys(self) -> Self: + for value in (self.interval_start, self.interval_end): + if value.utcoffset() != timedelta(0) or value.second or value.microsecond: + raise ValueError("Intervals must use UTC minute boundaries") + if self.interval_end - self.interval_start != timedelta(seconds=60): + raise ValueError("Interval must be exactly sixty seconds") + keys = [entry.key for entry in self.entries] + if len(keys) != len(set(keys)): + raise ValueError("Duplicate usage key") + return self + + +class UsageCheckpoint(UsageModel): + schema_version: Literal[1] = 1 + collector_id: Identifier + active_batch: UsageBatch + pending_batches: list[UsageBatch] = Field(default_factory=list) + + @model_validator(mode="after") + def check_batch_ids(self) -> Self: + batches = [*self.pending_batches, self.active_batch] + if len({batch.batch_id for batch in batches}) != len(batches): + raise ValueError("Duplicate batch ID") + previous_end = None + for batch in batches: + if previous_end is not None and batch.interval_start < previous_end: + raise ValueError("Overlapping or unordered batch intervals") + previous_end = batch.interval_end + return self + + +class UsageBatchPage(UsageModel): + schema_version: Literal[1] = 1 + collector_id: Identifier + batches: list[UsageBatch] = Field(default_factory=list, max_length=100) + has_more: bool = False + + @model_validator(mode="after") + def check_ids(self) -> Self: + if len({batch.batch_id for batch in self.batches}) != len(self.batches): + raise ValueError("Duplicate batch ID") + return self + + +class UsageAckRequest(UsageModel): + batch_ids: list[Identifier] = Field(min_length=1, max_length=100) + + +class UsageAckResponse(UsageModel): + acknowledged_batch_ids: list[Identifier] diff --git a/src/dstack/_internal/proxy/lib/services/model_proxy/clients/base.py b/src/dstack/_internal/proxy/lib/services/model_proxy/clients/base.py index cf31cb462f..2aef5f1c7b 100644 --- a/src/dstack/_internal/proxy/lib/services/model_proxy/clients/base.py +++ b/src/dstack/_internal/proxy/lib/services/model_proxy/clients/base.py @@ -6,13 +6,18 @@ ChatCompletionsRequest, ChatCompletionsResponse, ) +from dstack._internal.proxy.lib.services.usage import UsageAttempt class ChatCompletionsClient(ABC): @abstractmethod - async def generate(self, request: ChatCompletionsRequest) -> ChatCompletionsResponse: + async def generate( + self, request: ChatCompletionsRequest, *, attempt: UsageAttempt | None = None + ) -> ChatCompletionsResponse: pass @abstractmethod - async def stream(self, request: ChatCompletionsRequest) -> AsyncIterator[ChatCompletionsChunk]: + async def stream( + self, request: ChatCompletionsRequest, *, attempt: UsageAttempt | None = None + ) -> AsyncIterator[ChatCompletionsChunk]: yield diff --git a/src/dstack/_internal/proxy/lib/services/model_proxy/clients/openai.py b/src/dstack/_internal/proxy/lib/services/model_proxy/clients/openai.py index dfd0e526f1..796fac8eb4 100644 --- a/src/dstack/_internal/proxy/lib/services/model_proxy/clients/openai.py +++ b/src/dstack/_internal/proxy/lib/services/model_proxy/clients/openai.py @@ -1,3 +1,4 @@ +import json from typing import AsyncIterator import httpx @@ -12,6 +13,8 @@ ChatCompletionsResponse, ) from dstack._internal.proxy.lib.services.model_proxy.clients.base import ChatCompletionsClient +from dstack._internal.proxy.lib.services.model_proxy.sse import SSEDecoder +from dstack._internal.proxy.lib.services.usage import MAX_JSON_RESPONSE_BYTES, UsageAttempt class OpenAIChatCompletions(ChatCompletionsClient): @@ -19,52 +22,103 @@ def __init__(self, http_client: httpx.AsyncClient, prefix: str): self._http = http_client self._prefix = prefix - async def generate(self, request: ChatCompletionsRequest) -> ChatCompletionsResponse: - try: - resp = await self._http.post( - f"{self._prefix}/chat/completions", json=request.model_dump(exclude_unset=True) - ) - await self._propagate_error(resp) - except httpx.RequestError as e: - raise ProxyError(f"Error requesting model: {e!r}", status.HTTP_502_BAD_GATEWAY) - - try: - return validate_json_extra_ignore(ChatCompletionsResponse, resp.content) - except ValidationError as e: - raise ProxyError(f"Invalid response from model: {e}", status.HTTP_502_BAD_GATEWAY) - - async def stream(self, request: ChatCompletionsRequest) -> AsyncIterator[ChatCompletionsChunk]: + async def generate( + self, request: ChatCompletionsRequest, *, attempt: UsageAttempt | None = None + ) -> ChatCompletionsResponse: try: + if attempt is not None: + attempt.mark_dispatched() async with self._http.stream( "POST", f"{self._prefix}/chat/completions", json=request.model_dump(exclude_unset=True), ) as resp: await self._propagate_error(resp) + raw = await self._read_body(resp) + data = json.loads(raw) + if not isinstance(data, dict): + raise ValueError("Expected a response object") + if attempt is not None: + attempt.observe_usage(data.get("usage")) + attempt.mark_upstream_done() + return validate_json_extra_ignore(ChatCompletionsResponse, raw) + except httpx.RequestError as exc: + raise ProxyError( + f"Error requesting model: {exc!r}", status.HTTP_502_BAD_GATEWAY + ) from exc + except (ValueError, ValidationError) as exc: + raise ProxyError("Invalid response from model", status.HTTP_502_BAD_GATEWAY) from exc - async for line in resp.aiter_lines(): - if not line.startswith("data:"): - continue - data = line[len("data:") :].strip() - if data == "[DONE]": - break - yield self._parse_chunk_data(data) - except httpx.RequestError as e: - raise ProxyError(f"Error requesting model: {e!r}", status.HTTP_502_BAD_GATEWAY) + async def stream( + self, request: ChatCompletionsRequest, *, attempt: UsageAttempt | None = None + ) -> AsyncIterator[ChatCompletionsChunk]: + payload = request.model_dump(exclude_unset=True) + include_usage = request.stream_options is not None and request.stream_options.include_usage + if attempt is not None: + payload["stream_options"] = { + **(payload.get("stream_options") or {}), + "include_usage": True, + } + try: + if attempt is not None: + attempt.mark_dispatched() + async with self._http.stream( + "POST", f"{self._prefix}/chat/completions", json=payload + ) as resp: + await self._propagate_error(resp) + decoder = SSEDecoder() + async for fragment in resp.aiter_bytes(): + for data in decoder.feed(fragment): + if data.strip() == "[DONE]": + if attempt is not None: + attempt.mark_upstream_done() + return + raw = json.loads(data) + if not isinstance(raw, dict): + raise ValueError("Expected an SSE response object") + # The supported vLLM profile emits final usage in a usage-only event. + # Cumulative values on content/finish chunks are not final observations. + if ( + attempt is not None + and raw.get("choices") == [] + and raw.get("usage") is not None + ): + attempt.observe_usage(raw["usage"]) + chunk = self._parse_chunk_data(data) + if attempt is not None and not include_usage and chunk.usage is not None: + if not chunk.choices: + continue + chunk = chunk.model_copy(update={"usage": None}) + yield chunk + decoder.finish() + raise ProxyError( + "Model stream ended before upstream [DONE]", status.HTTP_502_BAD_GATEWAY + ) + except httpx.RequestError as exc: + raise ProxyError( + f"Error requesting model: {exc!r}", status.HTTP_502_BAD_GATEWAY + ) from exc + except (ValueError, ValidationError) as exc: + raise ProxyError("Invalid event in model stream", status.HTTP_502_BAD_GATEWAY) from exc @staticmethod def _parse_chunk_data(data: str) -> ChatCompletionsChunk: try: return validate_json_extra_ignore(ChatCompletionsChunk, data) - except ValidationError as e: - raise ProxyError(f"Invalid chunk in model stream: {e}", status.HTTP_502_BAD_GATEWAY) + except ValidationError as exc: + raise ProxyError("Invalid chunk in model stream", status.HTTP_502_BAD_GATEWAY) from exc @staticmethod - async def _propagate_error(resp: httpx.Response) -> None: - """ - Propagates HTTP error by raising ProxyError if status is not 200. - May also raise httpx.RequestError if there are issues reading the response. - """ + async def _read_body(resp: httpx.Response) -> bytes: + body = bytearray() + async for fragment in resp.aiter_bytes(): + if len(body) + len(fragment) > MAX_JSON_RESPONSE_BYTES: + raise ProxyError("Model response exceeds size limit", status.HTTP_502_BAD_GATEWAY) + body.extend(fragment) + return bytes(body) + + @classmethod + async def _propagate_error(cls, resp: httpx.Response) -> None: if resp.status_code != 200: - resp_body = await resp.aread() - raise ProxyError(resp_body.decode(errors="replace"), code=resp.status_code) + body = await cls._read_body(resp) + raise ProxyError(body.decode(errors="replace"), code=resp.status_code) diff --git a/src/dstack/_internal/proxy/lib/services/model_proxy/clients/tgi.py b/src/dstack/_internal/proxy/lib/services/model_proxy/clients/tgi.py index 2b1742acdc..2135bb6d41 100644 --- a/src/dstack/_internal/proxy/lib/services/model_proxy/clients/tgi.py +++ b/src/dstack/_internal/proxy/lib/services/model_proxy/clients/tgi.py @@ -19,6 +19,7 @@ ChatMessage, ) from dstack._internal.proxy.lib.services.model_proxy.clients.base import ChatCompletionsClient +from dstack._internal.proxy.lib.services.usage import UsageAttempt class TGIChatCompletions(ChatCompletionsClient): @@ -36,7 +37,9 @@ def __init__(self, http_client: httpx.AsyncClient, chat_template: str, eos_token except jinja2.TemplateError as e: raise ProxyError(f"Failed to compile chat template: {e}") - async def generate(self, request: ChatCompletionsRequest) -> ChatCompletionsResponse: + async def generate( + self, request: ChatCompletionsRequest, *, attempt: UsageAttempt | None = None + ) -> ChatCompletionsResponse: payload = self.get_payload(request) try: resp = await self.client.post("/generate", json=payload) @@ -89,7 +92,9 @@ async def generate(self, request: ChatCompletionsRequest) -> ChatCompletionsResp ), ) - async def stream(self, request: ChatCompletionsRequest) -> AsyncIterator[ChatCompletionsChunk]: + async def stream( + self, request: ChatCompletionsRequest, *, attempt: UsageAttempt | None = None + ) -> AsyncIterator[ChatCompletionsChunk]: completion_id = uuid.uuid4().hex created = int(datetime.datetime.now(datetime.timezone.utc).timestamp()) diff --git a/src/dstack/_internal/proxy/lib/services/model_proxy/sse.py b/src/dstack/_internal/proxy/lib/services/model_proxy/sse.py new file mode 100644 index 0000000000..ddf890c084 --- /dev/null +++ b/src/dstack/_internal/proxy/lib/services/model_proxy/sse.py @@ -0,0 +1,47 @@ +"""Incremental SSE event framing, independent of HTTP read/chunk boundaries.""" + +import codecs + +from dstack._internal.proxy.lib.services.usage import MAX_SSE_EVENT_BYTES + + +class SSEDecoder: + def __init__(self, max_event_bytes: int = MAX_SSE_EVENT_BYTES): + self.max_event_bytes = max_event_bytes + self._utf8 = codecs.getincrementaldecoder("utf-8")() + self._line: list[str] = [] + self._data: list[str] = [] + self._size = 0 + self._after_cr = False + + def feed(self, data: bytes) -> list[str]: + events = [] + for char in self._utf8.decode(data): + if self._after_cr: + self._after_cr = False + if char == "\n": + continue + self._size += len(char.encode("utf-8")) + if self._size > self.max_event_bytes: + raise ValueError("SSE event exceeds size limit") + if char in ("\r", "\n"): + line = "".join(self._line) + self._line.clear() + self._after_cr = char == "\r" + if not line: + if self._data: + events.append("\n".join(self._data)) + self._data.clear() + self._size = 0 + elif line == "data": + self._data.append("") + elif line.startswith("data:"): + self._data.append(line[5:].removeprefix(" ")) + else: + self._line.append(char) + return events + + def finish(self) -> None: + self._utf8.decode(b"", final=True) + if self._line or self._data: + raise ValueError("Truncated SSE event") diff --git a/src/dstack/_internal/proxy/lib/services/usage.py b/src/dstack/_internal/proxy/lib/services/usage.py new file mode 100644 index 0000000000..6d7dc2d7db --- /dev/null +++ b/src/dstack/_internal/proxy/lib/services/usage.py @@ -0,0 +1,63 @@ +"""Usage observation is optional for shared proxy consumers.""" + +from collections.abc import Mapping +from typing import Any + +from pydantic import BaseModel, ValidationError + +from dstack._internal.proxy.lib.schemas.usage import TokenUsage, UsageKey + +VLLM_PROFILE = "vllm-0.19.1-prompt-details" +MAX_JSON_RESPONSE_BYTES = 16 * 1024 * 1024 +MAX_SSE_EVENT_BYTES = 1024 * 1024 + + +def normalize_usage(usage: Any, profile: str) -> TokenUsage | None: + if profile != VLLM_PROFILE: + return None + if isinstance(usage, BaseModel): + usage = usage.model_dump() + if not isinstance(usage, Mapping): + return None + details = usage.get("prompt_tokens_details") + if details is None: + cached = 0 + elif isinstance(details, Mapping): + cached = details.get("cached_tokens") + else: + return None + try: + return TokenUsage.model_validate( + { + "prompt_tokens": usage.get("prompt_tokens"), + "cached_prompt_tokens": cached, + "completion_tokens": usage.get("completion_tokens"), + "total_tokens": usage.get("total_tokens"), + } + ) + except ValidationError: + return None + + +class UsageAttempt: + """No-op default; Gateway supplies a concrete per-attempt observer.""" + + def observe_usage(self, usage: Any) -> None: + pass + + def mark_dispatched(self) -> None: + pass + + def mark_upstream_done(self) -> None: + pass + + async def finish(self) -> None: + pass + + +class UsageObserver: + def profile_for(self, service_id: str | None) -> str | None: + return None + + def start_attempt(self, key: UsageKey, profile: str) -> UsageAttempt: + return UsageAttempt() diff --git a/src/dstack/_internal/server/background/scheduled_tasks/__init__.py b/src/dstack/_internal/server/background/scheduled_tasks/__init__.py index 697133a1c8..1d2f20dca1 100644 --- a/src/dstack/_internal/server/background/scheduled_tasks/__init__.py +++ b/src/dstack/_internal/server/background/scheduled_tasks/__init__.py @@ -30,6 +30,7 @@ collect_prometheus_metrics, delete_prometheus_metrics, ) +from dstack._internal.server.background.scheduled_tasks.usage import collect_gateway_usage from dstack._internal.server.services.backends.cache import close_unused_backends _scheduler = AsyncIOScheduler() @@ -54,6 +55,7 @@ def start_scheduled_tasks() -> AsyncIOScheduler: _scheduler.add_job(delete_metrics, IntervalTrigger(minutes=5), max_instances=1) _scheduler.add_job(delete_events, IntervalTrigger(minutes=7), max_instances=1) _scheduler.add_job(process_gateways_connections, IntervalTrigger(seconds=15)) + _scheduler.add_job(collect_gateway_usage, IntervalTrigger(seconds=15), max_instances=1) _scheduler.add_job(close_unused_backends, IntervalTrigger(minutes=1), max_instances=1) _scheduler.add_job( process_idle_volumes, IntervalTrigger(seconds=60, jitter=10), max_instances=1 diff --git a/src/dstack/_internal/server/background/scheduled_tasks/usage.py b/src/dstack/_internal/server/background/scheduled_tasks/usage.py new file mode 100644 index 0000000000..65bcbd90c8 --- /dev/null +++ b/src/dstack/_internal/server/background/scheduled_tasks/usage.py @@ -0,0 +1,90 @@ +"""Fetch durable minute batches, commit receipts, then ACK over existing SSH connections.""" + +import asyncio +import uuid +from collections import defaultdict +from contextlib import asynccontextmanager + +import httpx +from sqlalchemy import select + +from dstack._internal.server.db import get_db, get_session_ctx +from dstack._internal.server.models import GatewayReplicaModel +from dstack._internal.server.services.gateways.connection import GatewayConnection +from dstack._internal.server.services.gateways.pool import gateway_connections_pool +from dstack._internal.server.services.usage import ingest_usage_batch +from dstack._internal.utils.logging import get_logger + +logger = get_logger(__name__) +PAGE_SIZE = 100 +MAX_PAGES = 10 +COLLECTION_TIMEOUT = 12 +_sqlite_ingestion_lock = asyncio.Lock() + + +async def collect_gateway_usage() -> None: + async with get_session_ctx() as session: + rows = ( + await session.execute( + select(GatewayReplicaModel.id, GatewayReplicaModel.ip_address).where( + GatewayReplicaModel.active == True + ) + ) + ).all() + identities: dict[str, list[uuid.UUID]] = defaultdict(list) + for replica_id, address in rows: + if address is not None: + identities[address].append(replica_id) + semaphore = asyncio.Semaphore(8) + + async def collect(connection: GatewayConnection) -> None: + candidates = identities.get(connection.ip_address, []) + if len(candidates) != 1: + # Ambiguous/recycled addresses cannot establish a verified billing source. + return + async with semaphore: + try: + async with asyncio.timeout(COLLECTION_TIMEOUT): + await _collect_connection(connection, candidates[0]) + except httpx.HTTPStatusError as exc: + if exc.response.status_code not in (404, 405): + logger.warning( + "Usage collection HTTP failure from %s: %s", connection.ip_address, exc + ) + except Exception: + logger.exception( + "Usage collection failed from %s; unacknowledged batches retained", + connection.ip_address, + ) + + await asyncio.gather( + *(collect(connection) for connection in await gateway_connections_pool.all()) + ) + + +async def _collect_connection(connection: GatewayConnection, replica_id: uuid.UUID) -> None: + for _ in range(MAX_PAGES): + async with connection.client() as client: + page = await client.fetch_usage_batches(PAGE_SIZE) + if not page.batches: + return + # SQLite is single-server; lock before opening a session. PG relies on DB constraints. + async with _ingestion_lock(): + async with get_session_ctx() as session: + for batch in page.batches: + await ingest_usage_batch(session, replica_id, page.collector_id, batch) + # get_session_ctx commits and closes before leaving this block. + ids = [batch.batch_id for batch in page.batches] + async with connection.client() as client: + await client.acknowledge_usage(ids) + if not page.has_more: + return + + +@asynccontextmanager +async def _ingestion_lock(): + if get_db().dialect_name == "sqlite": + async with _sqlite_ingestion_lock: + yield + else: + yield diff --git a/src/dstack/_internal/server/migrations/versions/2026/11_16_1201_9a2e8f1f3c37_add_gateway_usage_batches.py b/src/dstack/_internal/server/migrations/versions/2026/11_16_1201_9a2e8f1f3c37_add_gateway_usage_batches.py new file mode 100644 index 0000000000..4ef875c908 --- /dev/null +++ b/src/dstack/_internal/server/migrations/versions/2026/11_16_1201_9a2e8f1f3c37_add_gateway_usage_batches.py @@ -0,0 +1,88 @@ +"""add gateway usage batches + +Revision ID: 9a2e8f1f3c37 +Revises: 6b5610ff36c1 +Create Date: 2026-11-16 12:01:47.939623+00:00 + +""" + +import sqlalchemy as sa +import sqlalchemy_utils +from alembic import op + +import dstack._internal.server.models + +# revision identifiers, used by Alembic. +revision = "9a2e8f1f3c37" +down_revision = "6b5610ff36c1" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.create_table( + "usage_collectors", + sa.Column("collector_id", sa.String(length=128), nullable=False), + sa.Column( + "gateway_replica_id", + sqlalchemy_utils.types.uuid.UUIDType(binary=False), + nullable=False, + ), + sa.PrimaryKeyConstraint("collector_id", name=op.f("pk_usage_collectors")), + sa.UniqueConstraint( + "gateway_replica_id", name=op.f("uq_usage_collectors_gateway_replica_id") + ), + ) + op.create_table( + "usage_batches", + sa.Column("id", sqlalchemy_utils.types.uuid.UUIDType(binary=False), nullable=False), + sa.Column("collector_id", sa.String(length=128), nullable=False), + sa.Column("batch_id", sa.String(length=128), nullable=False), + sa.Column( + "interval_start", dstack._internal.server.models.NaiveDateTime(), nullable=False + ), + sa.Column("interval_end", dstack._internal.server.models.NaiveDateTime(), nullable=False), + sa.Column("received_at", dstack._internal.server.models.NaiveDateTime(), nullable=False), + sa.Column("content", sa.Text(), nullable=False), + sa.ForeignKeyConstraint( + ["collector_id"], + ["usage_collectors.collector_id"], + name=op.f("fk_usage_batches_collector_id_usage_collectors"), + ), + sa.PrimaryKeyConstraint("id", name=op.f("pk_usage_batches")), + sa.UniqueConstraint("collector_id", "batch_id", name="uq_usage_batches_collector_batch"), + sa.UniqueConstraint( + "collector_id", "interval_start", name="uq_usage_batches_collector_minute" + ), + ) + op.create_table( + "usage_counters", + sa.Column( + "receipt_id", sqlalchemy_utils.types.uuid.UUIDType(binary=False), nullable=False + ), + sa.Column("consumer_subject_id", sa.String(length=128), nullable=False), + sa.Column("service_id", sa.String(length=128), nullable=False), + sa.Column("prompt_tokens", sa.BigInteger(), nullable=False), + sa.Column("cached_prompt_tokens", sa.BigInteger(), nullable=False), + sa.Column("completion_tokens", sa.BigInteger(), nullable=False), + sa.Column("total_tokens", sa.BigInteger(), nullable=False), + sa.Column("unknown_usage_attempts", sa.BigInteger(), nullable=False), + sa.ForeignKeyConstraint( + ["receipt_id"], + ["usage_batches.id"], + name=op.f("fk_usage_counters_receipt_id_usage_batches"), + ), + sa.PrimaryKeyConstraint( + "receipt_id", "consumer_subject_id", "service_id", name=op.f("pk_usage_counters") + ), + ) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table("usage_counters") + op.drop_table("usage_batches") + op.drop_table("usage_collectors") + # ### end Alembic commands ### diff --git a/src/dstack/_internal/server/models.py b/src/dstack/_internal/server/models.py index 8801768087..ce2f8d12c7 100644 --- a/src/dstack/_internal/server/models.py +++ b/src/dstack/_internal/server/models.py @@ -1508,3 +1508,46 @@ class ProviderRefModel(BaseModel): created_at: Mapped[datetime] = mapped_column(NaiveDateTime, default=get_current_datetime) __table_args__ = (Index("ix_provider_refs_project_id_created_at", project_id, created_at),) + + +class UsageCollectorModel(BaseModel): + """Durable identity binding; intentionally independent of live resource deletion.""" + + __tablename__ = "usage_collectors" + collector_id: Mapped[str] = mapped_column(String(128), primary_key=True) + gateway_replica_id: Mapped[uuid.UUID] = mapped_column(UUIDType(binary=False), unique=True) + + +class UsageBatchModel(BaseModel): + __tablename__ = "usage_batches" + __table_args__ = ( + UniqueConstraint("collector_id", "batch_id", name="uq_usage_batches_collector_batch"), + UniqueConstraint( + "collector_id", "interval_start", name="uq_usage_batches_collector_minute" + ), + ) + + id: Mapped[uuid.UUID] = mapped_column( + UUIDType(binary=False), primary_key=True, default=uuid.uuid4 + ) + collector_id: Mapped[str] = mapped_column(ForeignKey("usage_collectors.collector_id")) + batch_id: Mapped[str] = mapped_column(String(128)) + interval_start: Mapped[datetime] = mapped_column(NaiveDateTime) + interval_end: Mapped[datetime] = mapped_column(NaiveDateTime) + received_at: Mapped[datetime] = mapped_column(NaiveDateTime, default=get_current_datetime) + content: Mapped[str] = mapped_column(Text) + """Canonical normalized counters, never prompts, responses, or bearer tokens.""" + + +class UsageCounterModel(BaseModel): + __tablename__ = "usage_counters" + + receipt_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("usage_batches.id"), primary_key=True) + consumer_subject_id: Mapped[str] = mapped_column(String(128), primary_key=True) + service_id: Mapped[str] = mapped_column(String(128), primary_key=True) + # Historical source IDs deliberately have no cascading foreign keys to users/runs. + prompt_tokens: Mapped[int] = mapped_column(BigInteger) + cached_prompt_tokens: Mapped[int] = mapped_column(BigInteger) + completion_tokens: Mapped[int] = mapped_column(BigInteger) + total_tokens: Mapped[int] = mapped_column(BigInteger) + unknown_usage_attempts: Mapped[int] = mapped_column(BigInteger) diff --git a/src/dstack/_internal/server/routers/projects.py b/src/dstack/_internal/server/routers/projects.py index 8d166ebe41..ca69af3b46 100644 --- a/src/dstack/_internal/server/routers/projects.py +++ b/src/dstack/_internal/server/routers/projects.py @@ -4,6 +4,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from dstack._internal.core.models.projects import Project, ProjectsInfoListOrProjectsList +from dstack._internal.proxy.lib.schemas.usage import AuthorizedSubject from dstack._internal.server.db import get_session from dstack._internal.server.models import ProjectModel, UserModel from dstack._internal.server.schemas.projects import ( @@ -220,3 +221,11 @@ async def update_project( ) await session.refresh(project) return CustomJSONResponse(projects.project_model_to_project(project)) + + +@router.post("/{project_name}/authorize_proxy", response_model=AuthorizedSubject) +async def authorize_proxy( + user_project: Tuple[UserModel, ProjectModel] = Depends(ProjectMemberOrPublicAccess()), +): + user, _ = user_project + return AuthorizedSubject(consumer_subject_id=user.id.hex) diff --git a/src/dstack/_internal/server/services/gateways/client.py b/src/dstack/_internal/server/services/gateways/client.py index bf92b7687d..55b3ed9f13 100644 --- a/src/dstack/_internal/server/services/gateways/client.py +++ b/src/dstack/_internal/server/services/gateways/client.py @@ -17,6 +17,11 @@ ) from dstack._internal.proxy.gateway.schemas.services import ServiceListItem, ServiceListResponse from dstack._internal.proxy.gateway.schemas.stats import ServiceStats +from dstack._internal.proxy.lib.schemas.usage import ( + UsageAckRequest, + UsageAckResponse, + UsageBatchPage, +) from dstack._internal.server import settings @@ -242,6 +247,26 @@ async def collect_stats(self) -> list[ServiceStats]: return [] return TypeAdapter(list[ServiceStats]).validate_python(resp_data) + async def fetch_usage_batches(self, limit: int = 100) -> UsageBatchPage: + if not 1 <= limit <= 100: + raise ValueError("Usage page limit must be between 1 and 100") + response = await self._client.get( + self._url("/api/usage/batches"), params={"limit": limit}, timeout=10 + ) + response.raise_for_status() + return UsageBatchPage.model_validate(response.json()) + + async def acknowledge_usage(self, batch_ids: list[str]) -> UsageAckResponse: + payload = UsageAckRequest(batch_ids=batch_ids) + response = await self._client.post( + self._url("/api/usage/batches/ack"), json=payload.model_dump(), timeout=10 + ) + response.raise_for_status() + result = UsageAckResponse.model_validate(response.json()) + if set(result.acknowledged_batch_ids) != set(batch_ids): + raise ValueError("Gateway acknowledged unexpected usage batch IDs") + return result + def _url(self, path: str) -> str: return f"{self.base_url}/{path.lstrip('/')}" diff --git a/src/dstack/_internal/server/services/usage.py b/src/dstack/_internal/server/services/usage.py new file mode 100644 index 0000000000..5cdc996ab7 --- /dev/null +++ b/src/dstack/_internal/server/services/usage.py @@ -0,0 +1,94 @@ +"""Transactional receipt of Gateway minute counters; no pricing or quota decisions.""" + +import json +import uuid +from dataclasses import dataclass + +from sqlalchemy import insert, select +from sqlalchemy.dialects.postgresql import insert as pg_insert +from sqlalchemy.dialects.sqlite import insert as sqlite_insert +from sqlalchemy.ext.asyncio import AsyncSession + +from dstack._internal.proxy.lib.schemas.usage import UsageBatch +from dstack._internal.server.models import UsageBatchModel, UsageCollectorModel, UsageCounterModel + + +class UsageConflict(ValueError): + """Identity or immutable content changed: preserve the source for reconciliation.""" + + +@dataclass(frozen=True) +class ReceiptResult: + batch_id: str + inserted: bool + """Caller must commit before using this result to ACK.""" + + +async def ingest_usage_batch( + session: AsyncSession, gateway_replica_id: uuid.UUID, collector_id: str, batch: UsageBatch +) -> ReceiptResult: + # Validate even callers that constructed an unchecked model_copy(). + batch = UsageBatch.model_validate(batch.model_dump()) + if not collector_id or len(collector_id) > 128: + raise ValueError("Invalid collector identity") + content = batch.model_dump(mode="json") + content["entries"].sort(key=lambda entry: (entry["consumer_subject_id"], entry["service_id"])) + canonical = json.dumps(content, sort_keys=True, separators=(",", ":")) + for entry in batch.entries: + for name in ( + "prompt_tokens", + "cached_prompt_tokens", + "completion_tokens", + "total_tokens", + "unknown_usage_attempts", + ): + if getattr(entry, name) > 2**63 - 1: + raise ValueError("Usage counter exceeds signed 64-bit storage") + + dialect_insert = ( + pg_insert if session.get_bind().dialect.name == "postgresql" else sqlite_insert + ) + # INSERT first avoids a read-to-write upgrade and handles cross-process races in Postgres. + await session.execute( + dialect_insert(UsageCollectorModel) + .values(collector_id=collector_id, gateway_replica_id=gateway_replica_id) + .on_conflict_do_nothing() + ) + owner = await session.scalar( + select(UsageCollectorModel.gateway_replica_id).where( + UsageCollectorModel.collector_id == collector_id + ) + ) + if owner != gateway_replica_id: + raise UsageConflict("Collector identity reset or moved to another Gateway") + + receipt_id = uuid.uuid4() + created = await session.scalar( + dialect_insert(UsageBatchModel) + .values( + id=receipt_id, + collector_id=collector_id, + batch_id=batch.batch_id, + interval_start=batch.interval_start, + interval_end=batch.interval_end, + content=canonical, + ) + .on_conflict_do_nothing() + .returning(UsageBatchModel.id) + ) + if created is None: + existing = await session.scalar( + select(UsageBatchModel.content).where( + UsageBatchModel.collector_id == collector_id, + UsageBatchModel.batch_id == batch.batch_id, + ) + ) + if existing != canonical: + raise UsageConflict("Conflicting batch content or duplicate minute under a new ID") + return ReceiptResult(batch.batch_id, inserted=False) + if batch.entries: + await session.execute( + insert(UsageCounterModel), + [{"receipt_id": receipt_id, **entry.model_dump()} for entry in batch.entries], + ) + return ReceiptResult(batch.batch_id, inserted=True) diff --git a/src/tests/_internal/proxy/gateway/metering/__init__.py b/src/tests/_internal/proxy/gateway/metering/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/tests/_internal/proxy/gateway/metering/backend.py b/src/tests/_internal/proxy/gateway/metering/backend.py new file mode 100644 index 0000000000..51c1d97f4c --- /dev/null +++ b/src/tests/_internal/proxy/gateway/metering/backend.py @@ -0,0 +1,102 @@ +"""Local deterministic inference + server authorization fixture; never shipped as an API.""" + +import asyncio +import json + +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import StreamingResponse + +from tests._internal.proxy.gateway.metering.traffic import FIXTURES + +SUBJECTS = {"token-a": "1" * 32, "token-b": "2" * 32} + + +def make_backend() -> FastAPI: + app = FastAPI() + holds: dict[str, asyncio.Event] = {} + after_usage: set[str] = set() + started: set[str] = set() + + @app.get("/") + async def ready(): + return {"ready": True} + + @app.post("/api/projects/{project}/get") + @app.post("/api/projects/{project}/authorize_proxy") + async def authorize(project: str, request: Request): + token = request.headers.get("authorization", "").removeprefix("Bearer ") + if project != "p" or token not in SUBJECTS: + raise HTTPException(403) + return {"consumer_subject_id": SUBJECTS[token]} + + @app.post("/test/control") + async def control(request: Request): + body = await request.json() + for request_id in body.get("hold", []): + holds[request_id] = asyncio.Event() + if body.get("after_usage"): + after_usage.add(request_id) + for request_id in body.get("release", []): + if request_id in holds: + holds[request_id].set() + return {"started": sorted(started)} + + @app.post("/v1/chat/completions") + async def completions(request: Request): + body = await request.json() + request_id = body["user"] + started.add(request_id) + case = body["messages"][0]["content"] + expected = FIXTURES[case] + usage = { + "prompt_tokens": expected["prompt_tokens"], + "completion_tokens": expected["completion_tokens"], + "total_tokens": expected["total_tokens"], + "prompt_tokens_details": ( + {"cached_tokens": expected["cached_prompt_tokens"]} + if expected["cached_prompt_tokens"] + else None + ), + } + response = { + "id": request_id, + "created": 1, + "model": body["model"], + "choices": [], + "usage": usage, + } + gate = holds.get(request_id) + if not body.get("stream"): + if gate: + await gate.wait() + return response + + async def events(): + content = { + "id": request_id, + "model": body["model"], + "choices": [ + { + "index": 0, + "delta": {"role": "assistant", "content": "Hello 世界"}, + "finish_reason": None, + } + ], + } + raw = ("data: " + json.dumps(content, ensure_ascii=False) + "\r\n\r\n").encode() + for offset in range(0, len(raw), 3): + yield raw[offset : offset + 3] + if gate and request_id not in after_usage: + await gate.wait() + if case == "cut": + return + # Repeated cumulative usage deliberately must not double-account. + yield ("data: " + json.dumps(response) + "\n\n").encode() + yield ("data: " + json.dumps(response) + "\n\n").encode() + if gate and request_id in after_usage: + await gate.wait() + yield b"data: [DONE]\n\n" + + return StreamingResponse(events(), media_type="text/event-stream") + + return app diff --git a/src/tests/_internal/proxy/gateway/metering/benchmark.py b/src/tests/_internal/proxy/gateway/metering/benchmark.py new file mode 100644 index 0000000000..d359a7d6d1 --- /dev/null +++ b/src/tests/_internal/proxy/gateway/metering/benchmark.py @@ -0,0 +1,114 @@ +"""Explicit local microbenchmark; not a production load/capacity guarantee.""" + +import argparse +import asyncio +import json +import time +from pathlib import Path + +import httpx + +from tests._internal.proxy.gateway.metering.harness import Harness + + +def distribution(samples): + ordered = sorted(samples) + return ( + { + "count": len(ordered), + "p50_ms": ordered[len(ordered) // 2] * 1000, + "p95_ms": ordered[min(len(ordered) - 1, int(len(ordered) * 0.95))] * 1000, + "max_ms": max(ordered) * 1000, + } + if ordered + else {} + ) + + +async def run(root): + h = Harness(root) + await h.start() + try: + semaphore = asyncio.Semaphore(20) + first = [] + durations = [] + payload_sizes = [] + async with httpx.AsyncClient(base_url=h.gateway_url, timeout=30) as client: + + async def request(i): + async with semaphore: + request_id = f"perf-{i}" + started = time.perf_counter() + size = 0 + first_seen = False + async with client.stream( + "POST", + "/api/models/p/chat/completions", + headers={ + "Authorization": "Bearer token-a", + "X-Test-Request-ID": request_id, + }, + json={ + "model": "model-a", + "user": request_id, + "messages": [{"role": "user", "content": "A"}], + "stream": True, + "stream_options": {"include_usage": True}, + }, + ) as response: + response.raise_for_status() + async for chunk in response.aiter_bytes(): + if not first_seen: + first.append(time.perf_counter() - started) + first_seen = True + size += len(chunk) + durations.append(time.perf_counter() - started) + payload_sizes.append(size) + await h.wait_finalized(request_id) + + # Grow a persisted backlog, then measure forwarding while that backlog is checkpointed. + for i in range(20): + await request(i) + await h.advance_clock() + first.clear() + durations.clear() + payload_sizes.clear() + started = time.perf_counter() + await asyncio.gather( + *(request(i) for i in range(20, 220)), h.ipc_command("checkpoint") + ) + elapsed = time.perf_counter() - started + await h.advance_clock() + metrics = await h.ipc_command("metrics") + page = await h.batches() + counted = sum(e["completion_tokens"] for b in page["batches"] for e in b["entries"]) + assert counted == 220 * 3 + result = { + "requests": 200, + "concurrency": 20, + "mode": "burst, fragmented SSE, Python Gateway path", + "elapsed_seconds": elapsed, + "achieved_rps": 200 / elapsed, + "response_bytes_min": min(payload_sizes), + "response_bytes_max": max(payload_sizes), + "first_byte": distribution(first), + "forwarding": distribution(durations), + "gateway_loop_lag": distribution(metrics["loop_lag_seconds"]), + "checkpoint": distribution(metrics["checkpoint_seconds"]), + "gateway_peak_rss_bytes": metrics["peak_rss_bytes"], + "pending_batches": len(page["batches"]), + } + (root / "benchmark.json").write_text(json.dumps(result, indent=2)) + print(json.dumps(result, indent=2)) + finally: + await h.stop() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--artifacts", required=True) + asyncio.run(run(Path(parser.parse_args().artifacts))) + + +if __name__ == "__main__": + main() diff --git a/src/tests/_internal/proxy/gateway/metering/conftest.py b/src/tests/_internal/proxy/gateway/metering/conftest.py new file mode 100644 index 0000000000..6e7f918fe4 --- /dev/null +++ b/src/tests/_internal/proxy/gateway/metering/conftest.py @@ -0,0 +1,26 @@ +import pytest +import pytest_asyncio + +from tests._internal.proxy.gateway.metering.harness import Harness + + +@pytest_asyncio.fixture +async def harness(tmp_path): + # A real process covers HTTP cancellation, shutdown, and durable restart boundaries. + instance = Harness(tmp_path) + await instance.start() + try: + yield instance + finally: + await instance.stop() + + +def pytest_addoption(parser): + parser.addoption("--run-metering-realtime", action="store_true", default=False) + + +def pytest_collection_modifyitems(config, items): + if not config.getoption("--run-metering-realtime", default=False): + for item in items: + if "metering_realtime" in item.keywords: + item.add_marker(pytest.mark.skip(reason="requires --run-metering-realtime")) diff --git a/src/tests/_internal/proxy/gateway/metering/fixtures.json b/src/tests/_internal/proxy/gateway/metering/fixtures.json new file mode 100644 index 0000000000..819911bb2d --- /dev/null +++ b/src/tests/_internal/proxy/gateway/metering/fixtures.json @@ -0,0 +1,7 @@ +{ + "A": {"prompt_tokens":20,"cached_prompt_tokens":5,"completion_tokens":3,"total_tokens":23,"unknown_usage_attempts":0}, + "B": {"prompt_tokens":20,"cached_prompt_tokens":0,"completion_tokens":4,"total_tokens":24,"unknown_usage_attempts":0}, + "C": {"prompt_tokens":11,"cached_prompt_tokens":2,"completion_tokens":7,"total_tokens":18,"unknown_usage_attempts":0}, + "D": {"prompt_tokens":30,"cached_prompt_tokens":9,"completion_tokens":2,"total_tokens":32,"unknown_usage_attempts":0}, + "cut": {"prompt_tokens":0,"cached_prompt_tokens":0,"completion_tokens":0,"total_tokens":0,"unknown_usage_attempts":1} +} diff --git a/src/tests/_internal/proxy/gateway/metering/harness.py b/src/tests/_internal/proxy/gateway/metering/harness.py new file mode 100644 index 0000000000..c24c3b45fe --- /dev/null +++ b/src/tests/_internal/proxy/gateway/metering/harness.py @@ -0,0 +1,378 @@ +"""Separate Gateway process and deterministic backend; test control uses private Unix IPC.""" + +import argparse +import asyncio +import contextvars +import json +import os +import resource +import socket +import subprocess +import sys +import tempfile +import time +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import httpx +import httpx2 +import uvicorn + +from dstack._internal.proxy.gateway import app as gateway_app +from dstack._internal.proxy.gateway.auth import GatewayProxyAuthProvider +from dstack._internal.proxy.gateway.deps import GatewayDependencyInjector +from dstack._internal.proxy.gateway.models import GlobalProxyConfig +from dstack._internal.proxy.gateway.repo.repo import GatewayProxyRepo +from dstack._internal.proxy.gateway.services.metering import Clock, MeteringCollector +from dstack._internal.proxy.gateway.services.metering_store import MeteringStore +from dstack._internal.proxy.gateway.services.nginx import Nginx +from dstack._internal.proxy.gateway.services.stats import StatsCollector +from dstack._internal.proxy.lib.models import ChatModel, OpenAIChatModelFormat +from dstack._internal.proxy.lib.routers import model_proxy +from dstack._internal.proxy.lib.services.usage import VLLM_PROFILE +from dstack._internal.proxy.lib.testing.common import make_service +from tests._internal.proxy.gateway.metering.backend import make_backend + +REQUEST_ID = contextvars.ContextVar("test_request_id", default="") + + +class TestClock(Clock): + def __init__(self, value: str): + self.now = datetime.fromisoformat(value) + + def utc_now(self): + return self.now + + +class TracingCollector(MeteringCollector): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.completed: dict[str, asyncio.Event] = {} + self.request_ids = {} + self.checkpoint_seconds = [] + + def start_attempt(self, key, profile): + attempt = super().start_attempt(key, profile) + self.request_ids[attempt] = REQUEST_ID.get() + return attempt + + async def _finish(self, attempt): + await super()._finish(attempt) + if attempt.finished: + self.completed.setdefault(self.request_ids.pop(attempt, ""), asyncio.Event()).set() + + async def _save(self, state): + started = time.perf_counter() + await super()._save(state) + self.checkpoint_seconds.append(time.perf_counter() - started) + + +class TestNginx(Nginx): + def write_global_conf(self): + pass + + +async def _noop(*args, **kwargs): + pass + + +async def _worker(args) -> None: + http_clients = [] + collector = None + if args.kind == "backend": + app = make_backend() + else: + repo = GatewayProxyRepo() + for name, service_id in [("a", "a" * 32), ("b", "b" * 32)]: + await repo.set_service(make_service("p", f"run-{name}", run_id=service_id)) + await repo.set_model( + ChatModel( + project_name="p", + name=f"model-{name}", + run_name=f"run-{name}", + created_at=datetime.now(timezone.utc), + format_spec=OpenAIChatModelFormat(format="openai", prefix="/v1"), + ) + ) + await repo.set_config( + GlobalProxyConfig( + usage_metering_profiles={"a" * 32: VLLM_PROFILE, "b" * 32: VLLM_PROFILE} + ) + ) + clock = Clock() if args.realtime else TestClock(args.clock) + store = MeteringStore(Path(args.state) / "usage-counters.json") + collector = TracingCollector(store, clock=clock) + app = gateway_app.make_app(repo=repo, nginx=TestNginx(), metering_store=store, clock=clock) + auth_client = httpx2.AsyncClient(base_url=args.backend, timeout=10) + backend_client = httpx.AsyncClient( + base_url=args.nginx_url or args.backend, + headers={"Host": "service.test"} if args.nginx_url else {}, + timeout=30, + ) + http_clients = [auth_client, backend_client] + app.state.proxy_dependency_injector = GatewayDependencyInjector( + repo=repo, + auth=GatewayProxyAuthProvider(auth_client), + nginx=TestNginx(), + stats_collector=StatsCollector(Path(args.state) / "unused-access.log"), + metering=collector, + ) + gateway_app.apply_all = _noop + + async def connection(*args, **kwargs): + return backend_client + + model_proxy.get_service_replica_client = connection + + @app.middleware("http") + async def trace(request, call_next): + token = REQUEST_ID.set(request.headers.get("X-Test-Request-ID", "")) + try: + return await call_next(request) + finally: + REQUEST_ID.reset(token) + + server = uvicorn.Server( + uvicorn.Config( + app, + host="127.0.0.1", + port=0, + log_level="warning", + access_log=False, + timeout_graceful_shutdown=2, + ) + ) + ipc_server = None + loop_lag = [] + + async def sample_lag(): + while True: + before = time.perf_counter() + await asyncio.sleep(0.01) + loop_lag.append(max(0, time.perf_counter() - before - 0.01)) + + lag_task = asyncio.create_task(sample_lag()) + if collector is not None: + + async def control(reader, writer): + try: + request = json.loads(await reader.readline()) + if request["op"] == "advance": + if args.realtime: + raise ValueError("Real clock cannot be advanced") + assert isinstance(collector.clock, TestClock) + collector.clock.now += timedelta(seconds=request.get("seconds", 60)) + await collector.rotate_if_due() + elif request["op"] == "wait": + await asyncio.wait_for( + collector.completed.setdefault(request["id"], asyncio.Event()).wait(), 10 + ) + elif request["op"] == "checkpoint": + await collector.checkpoint() + result: dict = {"now": collector.clock.utc_now().isoformat()} + if request["op"] == "metrics": + result.update( + loop_lag_seconds=loop_lag[-10000:], + checkpoint_seconds=collector.checkpoint_seconds[-10000:], + peak_rss_bytes=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + * (1 if sys.platform == "darwin" else 1024), + ) + except Exception as exc: + result = {"error": repr(exc)} + writer.write(json.dumps(result).encode() + b"\n") + await writer.drain() + writer.close() + await writer.wait_closed() + + ipc_server = await asyncio.start_unix_server(control, path=args.ipc) + sockets = None + if args.kind == "backend": + tcp = socket.socket() + tcp.bind(("127.0.0.1", 0)) + tcp.setblocking(False) + unix = socket.socket(socket.AF_UNIX) + unix.bind(args.backend_socket) + unix.setblocking(False) + sockets = [tcp, unix] + serving = asyncio.create_task(server.serve(sockets=sockets)) + try: + while not server.started: + if serving.done(): + await serving + raise RuntimeError("Server stopped before readiness") + await asyncio.sleep(0.01) + port = server.servers[0].sockets[0].getsockname()[1] + Path(args.ready).write_text(json.dumps({"port": port})) + await serving + finally: + lag_task.cancel() + await asyncio.gather(lag_task, return_exceptions=True) + if ipc_server: + ipc_server.close() + await ipc_server.wait_closed() + for client in http_clients: + await client.aclose() + + +class Harness: + def __init__(self, state: Path, realtime: bool = False, nginx_url: str = ""): + self.nginx_url = nginx_url + self.audit = [] + self.state = state + self.realtime = realtime + self.now = datetime(2026, 11, 16, 10, tzinfo=timezone.utc) + self._ipc_dir = tempfile.TemporaryDirectory(prefix="ds2-", dir=tempfile.gettempdir()) + self.ipc = Path(self._ipc_dir.name) / "control.sock" + self.backend_socket = Path(self._ipc_dir.name) / "backend.sock" + self.workers = {} + self.gateway_url = "" + self.backend_url = "" + + async def start(self) -> None: + self.state.mkdir(parents=True, exist_ok=True) + try: + self.backend_url = await self._launch("backend") + self.gateway_url = await self._launch("gateway") + except BaseException: + await self.stop() + raise + + async def _launch(self, kind: str) -> str: + ready = self.state / f"{kind}.ready.json" + ready.unlink(missing_ok=True) + if kind == "gateway": + self.ipc.unlink(missing_ok=True) + command = [ + sys.executable, + "-m", + __name__ + if __name__ != "__main__" + else "tests._internal.proxy.gateway.metering.harness", + "--kind", + kind, + "--state", + str(self.state), + "--ready", + str(ready), + "--ipc", + str(self.ipc), + "--clock", + self.now.isoformat(), + ] + command += ["--backend-socket", str(self.backend_socket), "--nginx-url", self.nginx_url] + if self.backend_url: + command += ["--backend", self.backend_url] + if self.realtime: + command += ["--realtime"] + log = (self.state / f"{kind}.log").open("ab") + env = dict(os.environ) + env["PYTHONPATH"] = ( + str(Path(__file__).resolve().parents[5]) + os.pathsep + env.get("PYTHONPATH", "") + ) + proc = subprocess.Popen( + command, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, env=env + ) + self.workers[kind] = (proc, log) + deadline = time.monotonic() + 25 + async with httpx.AsyncClient(timeout=1) as client: + while time.monotonic() < deadline: + if proc.poll() is not None: + raise RuntimeError( + f"{kind} exited: " + (self.state / f"{kind}.log").read_text()[-4000:] + ) + try: + url = f"http://127.0.0.1:{json.loads(ready.read_text())['port']}" + response = await client.get(url + "/") + if response.status_code == 200: + return url + except (OSError, ValueError, httpx.HTTPError): + pass + await asyncio.sleep(0.02) + raise TimeoutError(f"{kind} readiness timed out") + + async def ipc_command(self, op: str, **kwargs) -> dict: + reader, writer = await asyncio.open_unix_connection(self.ipc) + try: + writer.write(json.dumps({"op": op, **kwargs}).encode() + b"\n") + await writer.drain() + result = json.loads(await asyncio.wait_for(reader.readline(), 15)) + if "error" in result: + raise RuntimeError(result["error"]) + self.audit.append({"control": {"op": op, **kwargs}, "result": result}) + return result + finally: + writer.close() + await writer.wait_closed() + + async def advance_clock(self, seconds: int = 60) -> None: + result = await self.ipc_command("advance", seconds=seconds) + self.now = datetime.fromisoformat(result["now"]) + + async def wait_finalized(self, request_id: str) -> None: + await self.ipc_command("wait", id=request_id) + + async def batches(self, limit: int = 100) -> dict: + async with httpx.AsyncClient(base_url=self.gateway_url, timeout=10) as client: + response = await client.get("/api/usage/batches", params={"limit": limit}) + response.raise_for_status() + result = response.json() + self.audit.append({"batches": result}) + return result + + async def backend_control(self, **body) -> dict: + async with httpx.AsyncClient(base_url=self.backend_url, timeout=10) as client: + response = await client.post("/test/control", json=body) + response.raise_for_status() + return response.json() + + async def wait_backend_started(self, request_id: str) -> None: + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + if request_id in (await self.backend_control())["started"]: + return + await asyncio.sleep(0.01) + raise TimeoutError(f"{request_id} did not start") + + async def restart(self, kill: bool = False) -> None: + await self._stop_worker("gateway", kill=kill) + self.gateway_url = await self._launch("gateway") + + async def _stop_worker(self, kind: str, kill: bool = False) -> None: + if kind not in self.workers: + return + proc, log = self.workers.pop(kind) + try: + if proc.poll() is None: + proc.kill() if kill else proc.terminate() + try: + await asyncio.to_thread(proc.wait, 8) + except subprocess.TimeoutExpired: + proc.kill() + await asyncio.to_thread(proc.wait, 5) + finally: + log.close() + + async def stop(self) -> None: + if self.state.exists(): + (self.state / "audit.json").write_text(json.dumps(self.audit, indent=2)) + for kind in list(self.workers): + await self._stop_worker(kind) + self._ipc_dir.cleanup() + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--kind", choices=["gateway", "backend"], required=True) + parser.add_argument("--state", required=True) + parser.add_argument("--ready", required=True) + parser.add_argument("--ipc", required=True) + parser.add_argument("--clock", required=True) + parser.add_argument("--backend", default="") + parser.add_argument("--backend-socket", required=True) + parser.add_argument("--nginx-url", default="") + parser.add_argument("--realtime", action="store_true") + asyncio.run(_worker(parser.parse_args())) + + +if __name__ == "__main__": + main() diff --git a/src/tests/_internal/proxy/gateway/metering/receiver.py b/src/tests/_internal/proxy/gateway/metering/receiver.py new file mode 100644 index 0000000000..0dbe251d8d --- /dev/null +++ b/src/tests/_internal/proxy/gateway/metering/receiver.py @@ -0,0 +1,152 @@ +"""Test receiver/CLI: SQLite commit precedes any Gateway ACK.""" + +import argparse +import asyncio +import json +import sqlite3 +from dataclasses import asdict, dataclass, field +from pathlib import Path + +import httpx + +from dstack._internal.proxy.lib.schemas.usage import UsageAckResponse, UsageBatchPage + +COUNTERS = ( + "prompt_tokens", + "cached_prompt_tokens", + "completion_tokens", + "total_tokens", + "unknown_usage_attempts", +) + + +@dataclass +class ReceiptReport: + fetched_ids: list[str] + committed_ids: list[str] + replayed_ids: list[str] + acked_ids: list[str] = field(default_factory=list) + has_more: bool = False + + +class MockReceiver: + def __init__(self, url: str, ledger: Path, client: httpx.AsyncClient | None = None): + self.client = client or httpx.AsyncClient(base_url=url, timeout=10) + self._owns_client = client is None + self.db = sqlite3.connect(ledger) + self.db.executescript(""" + CREATE TABLE IF NOT EXISTS metadata (collector_id TEXT PRIMARY KEY); + CREATE TABLE IF NOT EXISTS receipts ( + collector_id TEXT, batch_id TEXT, content TEXT NOT NULL, + PRIMARY KEY (collector_id,batch_id)); + CREATE TABLE IF NOT EXISTS entries ( + collector_id TEXT, batch_id TEXT, subject TEXT, service TEXT, + prompt_tokens INTEGER, cached_prompt_tokens INTEGER, + completion_tokens INTEGER, total_tokens INTEGER, unknown_usage_attempts INTEGER, + PRIMARY KEY (collector_id,batch_id,subject,service)); + """) + + async def collect_once(self, limit: int = 100, acknowledge: bool = True) -> ReceiptReport: + response = await self.client.get("/api/usage/batches", params={"limit": limit}) + response.raise_for_status() + page = UsageBatchPage.model_validate(response.json()) + new, replay = self.commit_page(page) + ids = [batch.batch_id for batch in page.batches] + report = ReceiptReport(ids, new, replay, has_more=page.has_more) + if ids and acknowledge: + report.acked_ids = (await self.acknowledge_committed(ids)).acknowledged_batch_ids + return report + + def commit_page(self, page: UsageBatchPage) -> tuple[list[str], list[str]]: + new, replay = [], [] + with self.db: + bound = self.db.execute("SELECT collector_id FROM metadata").fetchone() + if bound and bound[0] != page.collector_id: + raise ValueError("Collector identity changed; reconcile") + self.db.execute("INSERT OR IGNORE INTO metadata VALUES (?)", (page.collector_id,)) + for batch in page.batches: + content = json.dumps( + batch.model_dump(mode="json"), sort_keys=True, separators=(",", ":") + ) + existing = self.db.execute( + "SELECT content FROM receipts WHERE collector_id=? AND batch_id=?", + (page.collector_id, batch.batch_id), + ).fetchone() + if existing: + if existing[0] != content: + raise ValueError("Same batch ID has conflicting content") + replay.append(batch.batch_id) + continue + self.db.execute( + "INSERT INTO receipts VALUES (?,?,?)", + (page.collector_id, batch.batch_id, content), + ) + for entry in batch.entries: + self.db.execute( + "INSERT INTO entries VALUES (?,?,?,?,?,?,?,?,?)", + ( + page.collector_id, + batch.batch_id, + entry.consumer_subject_id, + entry.service_id, + *(getattr(entry, name) for name in COUNTERS), + ), + ) + new.append(batch.batch_id) + return new, replay + + async def acknowledge_committed(self, batch_ids: list[str]) -> UsageAckResponse: + committed = set(self.receipt_ids()) + if not set(batch_ids) <= committed: + raise ValueError("Cannot ACK a batch that has not committed") + response = await self.client.post("/api/usage/batches/ack", json={"batch_ids": batch_ids}) + response.raise_for_status() + return UsageAckResponse.model_validate(response.json()) + + def receipt_ids(self) -> list[str]: + return [ + row[0] for row in self.db.execute("SELECT batch_id FROM receipts ORDER BY batch_id") + ] + + def totals(self) -> dict[tuple[str, str], dict[str, int]]: + rows = self.db.execute( + "SELECT subject,service," + + ",".join(f"SUM({name})" for name in COUNTERS) + + " FROM entries GROUP BY subject,service" + ).fetchall() + return {(row[0], row[1]): dict(zip(COUNTERS, row[2:])) for row in rows} + + async def close(self) -> None: + self.db.close() + if self._owns_client: + await self.client.aclose() + + +async def _run(args) -> None: + receiver = MockReceiver(args.url, Path(args.ledger)) + try: + while True: + report = await receiver.collect_once(args.limit, acknowledge=not args.no_ack) + print(json.dumps(asdict(report)), flush=True) + if not args.watch: + break + await asyncio.sleep(args.interval) + finally: + await receiver.close() + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--url", required=True, help="Private Gateway management URL / local SSH forward" + ) + parser.add_argument("--ledger", required=True) + parser.add_argument("--limit", type=int, default=100) + parser.add_argument("--no-ack", action="store_true") + parser.add_argument("--watch", action="store_true") + parser.add_argument("--interval", type=float, default=15) + asyncio.run(_run(parser.parse_args())) + + +if __name__ == "__main__": + main() diff --git a/src/tests/_internal/proxy/gateway/metering/test_helpers.py b/src/tests/_internal/proxy/gateway/metering/test_helpers.py new file mode 100644 index 0000000000..e826a59f94 --- /dev/null +++ b/src/tests/_internal/proxy/gateway/metering/test_helpers.py @@ -0,0 +1,111 @@ +import httpx +import pytest + +from dstack._internal.proxy.lib.schemas.usage import UsageBatchPage +from tests._internal.proxy.gateway.metering.harness import Harness +from tests._internal.proxy.gateway.metering.receiver import MockReceiver +from tests._internal.proxy.gateway.metering.traffic import TrafficDriver + + +def page(batch_id="a", completion=3): + return UsageBatchPage.model_validate( + { + "collector_id": "collector", + "batches": [ + { + "batch_id": batch_id, + "interval_start": "2026-11-16T10:00:00Z", + "interval_end": "2026-11-16T10:01:00Z", + "entries": [ + { + "consumer_subject_id": "u", + "service_id": "s", + "prompt_tokens": 20, + "cached_prompt_tokens": 5, + "completion_tokens": completion, + "total_tokens": 20 + completion, + "unknown_usage_attempts": 0, + } + ], + } + ], + } + ) + + +@pytest.mark.asyncio +async def test_receiver_commits_once_reopens_and_rejects_conflicting_content(tmp_path): + ledger = tmp_path / "receiver.sqlite" + receiver = MockReceiver("http://unused", ledger) + assert receiver.commit_page(page()) == (["a"], []) + assert receiver.commit_page(page()) == ([], ["a"]) + with pytest.raises(ValueError, match="content"): + receiver.commit_page(page(completion=4)) + assert receiver.totals()[("u", "s")] == dict( + prompt_tokens=20, + cached_prompt_tokens=5, + completion_tokens=3, + total_tokens=23, + unknown_usage_attempts=0, + ) + await receiver.close() + receiver = MockReceiver("http://unused", ledger) + assert receiver.commit_page(page()) == ([], ["a"]) + assert receiver.totals()[("u", "s")]["total_tokens"] == 23 + with pytest.raises(ValueError, match="committed"): + await receiver.acknowledge_committed(["unseen"]) + await receiver.close() + + +@pytest.mark.asyncio +async def test_receiver_page_conflict_rolls_back_other_new_batches(tmp_path): + receiver = MockReceiver("http://unused", tmp_path / "receiver.sqlite") + receiver.commit_page(page()) + mixed = UsageBatchPage( + collector_id="collector", batches=[page("new").batches[0], page(completion=4).batches[0]] + ) + with pytest.raises(ValueError): + receiver.commit_page(mixed) + assert receiver.receipt_ids() == ["a"] + await receiver.close() + + +@pytest.mark.asyncio +async def test_traffic_checks_independent_expected_usage(): + wrong = { + "id": "answer", + "model": "model-a", + "choices": [], + "created": 1, + "usage": { + "prompt_tokens": 20, + "completion_tokens": 3, + "total_tokens": 23, + "prompt_tokens_details": {"cached_tokens": 0}, + }, + } + async with httpx.AsyncClient( + transport=httpx.MockTransport(lambda request: httpx.Response(200, json=wrong)), + base_url="http://gateway", + ) as client: + driver = TrafficDriver("http://gateway", client=client) + with pytest.raises(AssertionError, match="usage"): + await driver.send("request-1", case="A") + + +@pytest.mark.asyncio +async def test_separate_gateway_uses_real_model_and_management_routes(tmp_path): + harness = Harness(tmp_path) + await harness.start() + driver = TrafficDriver(harness.gateway_url) + try: + await driver.send("first", case="A", stream=True) + await harness.wait_finalized("first") + assert not (await harness.batches())["batches"] + await harness.advance_clock() + batch = (await harness.batches())["batches"][0] + assert batch["entries"][0]["cached_prompt_tokens"] == 5 + assert batch["entries"][0]["consumer_subject_id"] == "1" * 32 + finally: + await driver.close() + await harness.stop() diff --git a/src/tests/_internal/proxy/gateway/metering/test_scenarios.py b/src/tests/_internal/proxy/gateway/metering/test_scenarios.py new file mode 100644 index 0000000000..78ea090724 --- /dev/null +++ b/src/tests/_internal/proxy/gateway/metering/test_scenarios.py @@ -0,0 +1,337 @@ +"""DS-002 acceptance: real local HTTP/processes, deterministic inference and isolated state.""" + +import asyncio +import json +import time +from datetime import datetime, timezone + +import httpx +import pytest + +from dstack._internal.proxy.lib.schemas.usage import UsageBatchPage +from tests._internal.proxy.gateway.metering.harness import Harness +from tests._internal.proxy.gateway.metering.receiver import COUNTERS, MockReceiver +from tests._internal.proxy.gateway.metering.traffic import FIXTURES, TrafficDriver + +PAIR = ("1" * 32, "a" * 32) + + +def totals(batch): + return {name: sum(e[name] for e in batch["entries"]) for name in COUNTERS} + + +def expected(case, count=1): + return {k: v * count for k, v in FIXTURES[case].items()} + + +async def send(h, driver, request_id, **kwargs): + result = await driver.send(request_id, **kwargs) + await h.wait_finalized(request_id) + return result + + +async def close_minute(h): + if not h.realtime: + await h.advance_clock() + return + start = datetime.now(timezone.utc).replace(second=0, microsecond=0) + deadline = time.monotonic() + 70 + while time.monotonic() < deadline: + page = await h.batches() + if any(datetime.fromisoformat(b["interval_start"]) >= start for b in page["batches"]): + return + await asyncio.sleep(0.2) + raise TimeoutError("Minute did not durably close") + + +async def two_intervals(h): + driver = TrafficDriver(h.gateway_url, artifact_dir=h.state) + receiver = MockReceiver(h.gateway_url, h.state / "receiver.sqlite") + evidence: dict = {"started_at": datetime.now(timezone.utc).isoformat()} + try: + for i in range(10): + await send(h, driver, f"A-{i}", stream=i % 2 == 0) + await close_minute(h) + page = await h.batches() + a = page["batches"][-1] + evidence["A"] = a + assert totals(a) == expected("A", 10) + assert a in (await h.batches())["batches"] + receiver.commit_page(UsageBatchPage.model_validate({**page, "batches": [a]})) + await send(h, driver, "B-0", case="B") + await h.backend_control(hold=["B-1"]) + inflight = asyncio.create_task(send(h, driver, "B-1", case="B", stream=True)) + await h.wait_backend_started("B-1") + evidence["ack_A"] = (await receiver.acknowledge_committed([a["batch_id"]])).model_dump() + assert a["batch_id"] not in [b["batch_id"] for b in (await h.batches())["batches"]] + await h.backend_control(release=["B-1"]) + await inflight + for i in range(2, 7): + await send(h, driver, f"B-{i}", case="B", stream=i % 2 == 0) + await close_minute(h) + b = (await h.batches())["batches"][-1] + evidence["B"] = b + assert totals(b) == expected("B", 7) + await receiver.acknowledge_committed([a["batch_id"]]) + assert b in (await h.batches())["batches"] + await receiver.collect_once() + assert receiver.totals()[PAIR] == dict(zip(COUNTERS, [340, 50, 58, 398, 0])) + assert not (await h.batches())["batches"] + evidence["ledger_totals"] = [ + {"subject": k[0], "service": k[1], **v} for k, v in receiver.totals().items() + ] + finally: + evidence["traffic"] = driver.report.attempts + evidence["finished_at"] = datetime.now(timezone.utc).isoformat() + (h.state / "evidence.json").write_text(json.dumps(evidence, indent=2)) + await driver.close() + await receiver.close() + + +@pytest.mark.asyncio +async def test_two_intervals_and_ack(harness): + await two_intervals(harness) + + +@pytest.mark.asyncio +async def test_selective_ack_during_traffic(harness): + h = harness + d = TrafficDriver(h.gateway_url, artifact_dir=h.state) + r = MockReceiver(h.gateway_url, h.state / "receiver.sqlite") + try: + await send(h, d, "P") + await close_minute(h) + p = (await h.batches())["batches"][0] + await send(h, d, "Q", case="C") + await close_minute(h) + page = await h.batches() + q = page["batches"][1] + r.commit_page(UsageBatchPage.model_validate({**page, "batches": [p]})) + await send(h, d, "R0", case="D") + await h.backend_control(hold=["R1"]) + task = asyncio.create_task(send(h, d, "R1", case="D")) + await h.wait_backend_started("R1") + await r.acknowledge_committed([p["batch_id"]]) + assert (await h.batches())["batches"] == [q] + await h.backend_control(release=["R1"]) + await task + await close_minute(h) + batches = (await h.batches())["batches"] + assert batches[0] == q and totals(batches[1]) == expected("D", 2) + finally: + await d.close() + await r.close() + + +@pytest.mark.asyncio +async def test_subject_service_isolation(harness): + h = harness + d = TrafficDriver(h.gateway_url, artifact_dir=h.state) + try: + cases = [ + ("token-a", "model-a", "A"), + ("token-a", "model-b", "B"), + ("token-b", "model-a", "C"), + ("token-b", "model-b", "D"), + ] + await asyncio.gather( + *( + send(h, d, f"spoofed-user-{i}", case=c, token=t, model=m, stream=True) + for i, (t, m, c) in enumerate(cases) + ) + ) + await close_minute(h) + entries = (await h.batches())["batches"][0]["entries"] + actual = { + (e["consumer_subject_id"], e["service_id"]): {k: e[k] for k in COUNTERS} + for e in entries + } + assert actual == { + (str(1 + i // 2) * 32, ("a" if i % 2 == 0 else "b") * 32): expected(c) + for i, (_, _, c) in enumerate(cases) + } + finally: + await d.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize("case", ["A", "B"]) +async def test_json_and_streaming_usage(harness, stream, case): + h = harness + d = TrafficDriver(h.gateway_url, artifact_dir=h.state) + try: + await send(h, d, "request", case=case, stream=stream) + await close_minute(h) + assert totals((await h.batches())["batches"][0]) == expected(case) + finally: + await d.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("after_usage", [False, True]) +async def test_stream_disconnect(harness, after_usage): + h = harness + await h.backend_control(hold=["disconnect"], after_usage=after_usage) + body = { + "model": "model-a", + "user": "disconnect", + "messages": [{"role": "user", "content": "A"}], + "stream": True, + "stream_options": {"include_usage": True}, + } + async with httpx.AsyncClient(base_url=h.gateway_url, timeout=10) as client: + async with client.stream( + "POST", + "/api/models/p/chat/completions", + json=body, + headers={"Authorization": "Bearer token-a", "X-Test-Request-ID": "disconnect"}, + ) as response: + response.raise_for_status() + saw_content = False + async for line in response.aiter_lines(): + if not line.startswith("data:"): + continue + event = json.loads(line[5:]) + saw_content |= bool(event.get("choices")) + if (not after_usage and saw_content) or (after_usage and event.get("usage")): + break + assert saw_content # Content arrives while final usage / DONE is still held. + await h.wait_finalized("disconnect") + await close_minute(h) + assert totals((await h.batches())["batches"][0]) == expected("A" if after_usage else "cut") + await h.backend_control(release=["disconnect"]) + + +@pytest.mark.asyncio +async def test_truncated_stream_unknown(harness): + h = harness + d = TrafficDriver(h.gateway_url, artifact_dir=h.state) + try: + await send(h, d, "cut", case="cut", stream=True) + await close_minute(h) + assert totals((await h.batches())["batches"][0]) == expected("cut") + finally: + await d.close() + + +class LostReply(httpx.AsyncBaseTransport): + def __init__(self, method): + self.inner = httpx.AsyncHTTPTransport() + self.method = method + self.lost = False + + async def handle_async_request(self, request): + response = await self.inner.handle_async_request(request) + if request.method == self.method and not self.lost: + self.lost = True + await response.aread() + await response.aclose() + raise httpx.ReadError("Injected lost response", request=request) + return response + + async def aclose(self): + await self.inner.aclose() + + +@pytest.mark.asyncio +async def test_receiver_outage_and_retry(harness): + h = harness + d = TrafficDriver(h.gateway_url, artifact_dir=h.state) + ledger = h.state / "receiver.sqlite" + try: + for i in range(2): + await send(h, d, f"offline-{i}") + await close_minute(h) + pending = (await h.batches())["batches"] + assert len(pending) == 2 + async with httpx.AsyncClient(base_url=h.gateway_url, transport=LostReply("GET")) as client: + r = MockReceiver(h.gateway_url, ledger, client) + with pytest.raises(httpx.ReadError): + await r.collect_once(1) + assert r.receipt_ids() == [] and (await h.batches())["batches"] == pending + first = await r.collect_once(1, acknowledge=False) + await r.close() + r = MockReceiver(h.gateway_url, ledger) + replay = await r.collect_once(1, acknowledge=False) + assert replay.replayed_ids == first.committed_ids + await r.close() + async with httpx.AsyncClient( + base_url=h.gateway_url, transport=LostReply("POST") + ) as client: + r = MockReceiver(h.gateway_url, ledger, client) + with pytest.raises(httpx.ReadError): + await r.acknowledge_committed(first.committed_ids) + assert len((await h.batches())["batches"]) == 1 + await r.acknowledge_committed(first.committed_ids) + await r.collect_once(1) + assert len(r.receipt_ids()) == 2 and r.totals()[PAIR] == expected("A", 2) + assert (await h.batches())["batches"] == [] + await r.close() + finally: + await d.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kill", [False, True]) +async def test_gateway_restart_persistence(harness, kill): + h = harness + d = TrafficDriver(h.gateway_url, artifact_dir=h.state) + r = MockReceiver(h.gateway_url, h.state / "receiver.sqlite") + try: + await send(h, d, "P") + await close_minute(h) + await r.collect_once() + await send(h, d, "Q", case="B") + await close_minute(h) + page = await h.batches() + q = page["batches"][0] + await d.close() + await r.close() + await h.restart(kill) + assert (await h.batches()) == page + d = TrafficDriver(h.gateway_url, artifact_dir=h.state) + r = MockReceiver(h.gateway_url, h.state / "receiver.sqlite") + await r.collect_once() + await send(h, d, "R", case="C") + await close_minute(h) + new = (await h.batches())["batches"][0] + assert new["batch_id"] != q["batch_id"] and totals(new) == expected("C") + await r.collect_once() + assert len(r.receipt_ids()) == 3 + finally: + await d.close() + await r.close() + + +@pytest.mark.asyncio +async def test_unsaved_active_loss_is_bounded(harness): + h = harness + d = TrafficDriver(h.gateway_url, artifact_dir=h.state) + try: + await send(h, d, "durable") + await h.ipc_command("checkpoint") + await send(h, d, "unsaved", case="B") + await d.close() + await h.restart(kill=True) + await close_minute(h) + assert totals((await h.batches())["batches"][0]) == expected("A") + finally: + await d.close() + + +@pytest.mark.metering_realtime +@pytest.mark.asyncio +async def test_two_intervals_real_minutes(tmp_path): + h = Harness(tmp_path, realtime=True) + await h.start() + try: + # Align without wall-clock sleeps in the default suite; this explicit opt-in is acceptance evidence. + deadline = time.monotonic() + 65 + while datetime.now(timezone.utc).second > 2: + if time.monotonic() > deadline: + raise TimeoutError("Could not align minute") + await asyncio.sleep(0.2) + await two_intervals(h) + finally: + await h.stop() diff --git a/src/tests/_internal/proxy/gateway/metering/traffic.py b/src/tests/_internal/proxy/gateway/metering/traffic.py new file mode 100644 index 0000000000..de9be12a90 --- /dev/null +++ b/src/tests/_internal/proxy/gateway/metering/traffic.py @@ -0,0 +1,138 @@ +"""Deterministic traffic with expectations independent of Gateway counters.""" + +import argparse +import asyncio +import json +import uuid +from dataclasses import dataclass, field +from pathlib import Path + +import httpx + +FIXTURES = json.loads(Path(__file__).with_name("fixtures.json").read_text()) + + +@dataclass +class TrafficReport: + attempts: list[dict] = field(default_factory=list) + + +class TrafficDriver: + def __init__( + self, url: str, client: httpx.AsyncClient | None = None, artifact_dir: Path | None = None + ): + self.artifact_path = ( + artifact_dir / f"traffic-{uuid.uuid4().hex}.json" if artifact_dir else None + ) + self.client = client or httpx.AsyncClient(base_url=url, timeout=30) + self._owns_client = client is None + self.report = TrafficReport() + + async def send( + self, + request_id: str, + case: str = "A", + token: str = "token-a", + model: str = "model-a", + stream: bool = False, + ) -> dict: + request = { + "model": model, + "messages": [{"role": "user", "content": case}], + "user": request_id, + "stream": stream, + } + if stream: + request["stream_options"] = {"include_usage": True} + headers = {"Authorization": f"Bearer {token}", "X-Test-Request-ID": request_id} + async with self.client.stream( + "POST", "/api/models/p/chat/completions", json=request, headers=headers + ) as response: + response.raise_for_status() + if stream: + events = [] + observed = None + saw_done = False + async for line in response.aiter_lines(): + if not line.startswith("data:"): + continue + payload = line[5:].strip() + if payload == "[DONE]": + saw_done = True + continue + data = json.loads(payload) + events.append(data) + if data.get("usage") is not None: + observed = data["usage"] + raw = events + if case != "cut": + assert saw_done, "stream missing completion marker" + else: + raw = json.loads(await response.aread()) + observed = raw.get("usage") + expected = FIXTURES[case] + if case == "cut": + assert observed is None, "unexpected confirmed usage in interrupted stream" + normalized = dict(expected) + else: + assert observed is not None, "missing usage" + normalized = { + "prompt_tokens": observed["prompt_tokens"], + "cached_prompt_tokens": (observed.get("prompt_tokens_details") or {}).get( + "cached_tokens", 0 + ), + "completion_tokens": observed["completion_tokens"], + "total_tokens": observed["total_tokens"], + "unknown_usage_attempts": 0, + } + assert normalized == expected, ( + f"usage mismatch for {request_id}: {normalized} != {expected}" + ) + item = { + "request_id": request_id, + "case": case, + "subject": {"token-a": "1" * 32, "token-b": "2" * 32}.get(token, "unknown"), + "service": {"model-a": "a" * 32, "model-b": "b" * 32}[model], + "expected": dict(expected), + "observed": normalized, + "response": raw, + } + self.report.attempts.append(item) + return item + + async def run(self, manifest: list[dict]) -> TrafficReport: + await asyncio.gather(*(self.send(**item) for item in manifest)) + return self.report + + async def close(self) -> None: + if self.artifact_path is not None: + self.artifact_path.write_text(json.dumps(self.report.attempts, indent=2)) + if self._owns_client: + await self.client.aclose() + + +async def _run(args) -> None: + driver = TrafficDriver(args.url) + try: + await driver.run( + [ + dict(request_id=f"{args.case}-{i}", case=args.case, stream=args.stream) + for i in range(args.count) + ] + ) + print(json.dumps(driver.report.attempts, indent=2)) + finally: + await driver.close() + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--url", required=True) + parser.add_argument("--case", choices=list(FIXTURES), default="A") + parser.add_argument("--count", type=int, default=10) + parser.add_argument("--stream", action="store_true") + asyncio.run(_run(parser.parse_args())) + + +if __name__ == "__main__": + main() diff --git a/src/tests/_internal/proxy/gateway/routers/test_config.py b/src/tests/_internal/proxy/gateway/routers/test_config.py new file mode 100644 index 0000000000..7fc10be241 --- /dev/null +++ b/src/tests/_internal/proxy/gateway/routers/test_config.py @@ -0,0 +1,92 @@ +import asyncio +from datetime import datetime, timezone + +import httpx +import pytest + +from dstack._internal.proxy.gateway.app import make_app +from dstack._internal.proxy.gateway.repo.repo import GatewayProxyRepo +from dstack._internal.proxy.gateway.services.metering_store import MeteringStore +from dstack._internal.proxy.lib.models import ChatModel, OpenAIChatModelFormat +from dstack._internal.proxy.lib.services.usage import VLLM_PROFILE +from dstack._internal.proxy.lib.testing.common import make_service + + +@pytest.mark.asyncio +async def test_old_config_update_preserves_metering_and_disabled_creates_no_file(tmp_path): + repo = GatewayProxyRepo() + path = tmp_path / "usage.json" + app = make_app(repo=repo, metering_store=MeteringStore(path)) + await repo.set_service(make_service("p", "run", run_id="service")) + await repo.set_model( + ChatModel( + project_name="p", + name="model", + run_name="run", + created_at=datetime.now(timezone.utc), + format_spec=OpenAIChatModelFormat(format="openai", prefix="/v1"), + ) + ) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://control" + ) as client: + assert (await client.get("/api/usage/batches")).status_code == 404 + assert not path.exists() + assert ( + await client.post( + "/api/config", json={"usage_metering_profiles": {"service": VLLM_PROFILE}} + ) + ).status_code == 200 + assert path.exists() + assert (await client.post("/api/config", json={"acme_eab_kid": "kid"})).status_code == 200 + config = await repo.get_config() + assert config.usage_metering_profiles == {"service": VLLM_PROFILE} + assert config.acme_settings.eab_kid == "kid" + assert ( + await client.post( + "/api/config", json={"usage_metering_profiles": {"missing": VLLM_PROFILE}} + ) + ).status_code == 400 + await app.state.proxy_dependency_injector.get_usage_observer().close() + + +@pytest.mark.asyncio +async def test_concurrent_legacy_config_cannot_erase_enabled_profiles(tmp_path, monkeypatch): + repo = GatewayProxyRepo() + app = make_app(repo=repo, metering_store=MeteringStore(tmp_path / "usage.json")) + await repo.set_service(make_service("p", "run", run_id="service")) + await repo.set_model( + ChatModel( + project_name="p", + name="model", + run_name="run", + created_at=datetime.now(timezone.utc), + format_spec=OpenAIChatModelFormat(format="openai", prefix="/v1"), + ) + ) + entered = asyncio.Event() + release = asyncio.Event() + original = repo.set_config + + async def delayed(config): + if config.usage_metering_profiles and not entered.is_set(): + entered.set() + await release.wait() + await original(config) + + monkeypatch.setattr(repo, "set_config", delayed) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://control" + ) as client: + enabling = asyncio.create_task( + client.post("/api/config", json={"usage_metering_profiles": {"service": VLLM_PROFILE}}) + ) + await entered.wait() + legacy = asyncio.create_task(client.post("/api/config", json={"acme_eab_kid": "new-kid"})) + await asyncio.sleep(0) + await asyncio.sleep(0) + release.set() + assert (await enabling).status_code == 200 + assert (await legacy).status_code == 200 + assert (await repo.get_config()).usage_metering_profiles == {"service": VLLM_PROFILE} + await app.state.proxy_dependency_injector.get_usage_observer().close() diff --git a/src/tests/_internal/proxy/gateway/routers/test_usage.py b/src/tests/_internal/proxy/gateway/routers/test_usage.py new file mode 100644 index 0000000000..60b836cda1 --- /dev/null +++ b/src/tests/_internal/proxy/gateway/routers/test_usage.py @@ -0,0 +1,51 @@ +import httpx +import pytest + +from dstack._internal.proxy.gateway.app import make_app +from dstack._internal.proxy.gateway.repo.repo import GatewayProxyRepo +from dstack._internal.proxy.gateway.services.metering_store import MeteringStore +from dstack._internal.proxy.lib.services.usage import VLLM_PROFILE +from tests._internal.proxy.gateway.services.test_metering import FakeClock, record + + +@pytest.mark.asyncio +async def test_fetch_and_ack_preserve_active_and_reject_active_ids(tmp_path): + clock = FakeClock() + store = MeteringStore(tmp_path / "usage.json") + app = make_app(repo=GatewayProxyRepo(), metering_store=store, clock=clock) + collector = app.state.proxy_dependency_injector.get_usage_observer() + collector.profiles = {"s": VLLM_PROFILE} + await collector.start() + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://control" + ) as client: + await record(collector) + clock.advance() + await collector.rotate_if_due() + response = await client.get("/api/usage/batches?limit=1") + assert response.status_code == 200 + a = response.json()["batches"][0] + assert (await client.get("/api/usage/batches")).json()["batches"] == [a] + await record(collector) + saved = store.load() + assert saved is not None + bad = await client.post( + "/api/usage/batches/ack", + json={"batch_ids": [a["batch_id"], saved.active_batch.batch_id]}, + ) + assert bad.status_code == 400 + assert (await client.get("/api/usage/batches")).json()["batches"] == [a] + assert ( + await client.post("/api/usage/batches/ack", json={"batch_ids": [a["batch_id"]]}) + ).status_code == 200 + clock.advance() + await collector.rotate_if_due() + b = (await client.get("/api/usage/batches")).json()["batches"][0] + await client.post("/api/usage/batches/ack", json={"batch_ids": [a["batch_id"]]}) + assert (await client.get("/api/usage/batches")).json()["batches"] == [b] + assert b["entries"][0]["total_tokens"] == 23 + assert (await client.get("/api/usage/batches?limit=0")).status_code == 422 + assert ( + await client.post("/api/usage/batches/ack", json={"batch_ids": []}) + ).status_code == 422 + await collector.close() diff --git a/src/tests/_internal/proxy/gateway/services/test_metering.py b/src/tests/_internal/proxy/gateway/services/test_metering.py new file mode 100644 index 0000000000..f1cdf112fc --- /dev/null +++ b/src/tests/_internal/proxy/gateway/services/test_metering.py @@ -0,0 +1,276 @@ +import asyncio +from datetime import datetime, timedelta, timezone + +import pytest + +from dstack._internal.proxy.gateway.services.metering import Clock, MeteringCollector +from dstack._internal.proxy.gateway.services.metering_store import MeteringStore +from dstack._internal.proxy.lib.errors import ProxyError +from dstack._internal.proxy.lib.schemas.usage import UsageKey +from dstack._internal.proxy.lib.services.usage import VLLM_PROFILE + + +class FakeClock(Clock): + def __init__(self): + self.now = datetime(2026, 11, 16, 10, tzinfo=timezone.utc) + + def utc_now(self): + return self.now + + def advance(self, seconds=60): + self.now += timedelta(seconds=seconds) + + +class FailingStore(MeteringStore): + fail = False + + async def save(self, state): + if self.fail: + raise OSError("injected disk failure") + await super().save(state) + + +async def record(collector, user="u", service="s", usage=None): + attempt = collector.start_attempt( + UsageKey(consumer_subject_id=user, service_id=service), VLLM_PROFILE + ) + attempt.mark_dispatched() + attempt.observe_usage( + usage + or dict( + prompt_tokens=20, + completion_tokens=3, + total_tokens=23, + prompt_tokens_details={"cached_tokens": 5}, + ) + ) + await attempt.finish() + return attempt + + +@pytest.mark.asyncio +class TestMeteringCollector: + async def test_ack_does_not_clear_active(self, tmp_path): + clock = FakeClock() + collector = MeteringCollector( + MeteringStore(tmp_path / "usage.json"), clock=clock, profiles={"s": VLLM_PROFILE} + ) + await collector.start() + await record(collector) + assert not (await collector.get_batches()).batches + clock.advance() + await collector.rotate_if_due() + a = (await collector.get_batches()).batches[0] + await record(collector) + await collector.acknowledge([a.batch_id]) + clock.advance() + await collector.rotate_if_due() + b = (await collector.get_batches()).batches[0] + await collector.acknowledge([a.batch_id]) + assert (await collector.get_batches()).batches == [b] + assert b.entries[0].total_tokens == 23 + assert b.batch_id != a.batch_id + await collector.close() + + async def test_ack_preserves_other_pending(self, tmp_path): + clock = FakeClock() + c = MeteringCollector( + MeteringStore(tmp_path / "usage.json"), clock=clock, profiles={"s": VLLM_PROFILE} + ) + await c.start() + for _ in range(2): + await record(c) + clock.advance() + await c.rotate_if_due() + p, q = (await c.get_batches()).batches + await record(c) + await c.acknowledge([p.batch_id]) + assert (await c.get_batches()).batches == [q] + clock.advance() + await c.rotate_if_due() + assert [b.entries[0].total_tokens for b in (await c.get_batches()).batches] == [23, 23] + await c.close() + + async def test_rotation_not_published_before_save(self, tmp_path): + clock = FakeClock() + store = FailingStore(tmp_path / "usage.json") + c = MeteringCollector(store, clock=clock, profiles={"s": VLLM_PROFILE}) + await c.start() + late = await record(c) + store.fail = True + clock.advance() + with pytest.raises(OSError): + await c.rotate_if_due() + assert not (await c.get_batches()).batches + with pytest.raises(ProxyError): + c.start_attempt(UsageKey(consumer_subject_id="u", service_id="s"), VLLM_PROFILE) + store.fail = False + await c.checkpoint() + assert (await c.get_batches()).batches[0].entries[0].total_tokens == 23 + await late.finish() + await c.close() + + async def test_failed_ack_is_not_success(self, tmp_path): + clock = FakeClock() + store = FailingStore(tmp_path / "usage.json") + c = MeteringCollector(store, clock=clock, profiles={"s": VLLM_PROFILE}) + await c.start() + await record(c) + clock.advance() + await c.rotate_if_due() + before = await c.get_batches() + store.fail = True + with pytest.raises(OSError): + await c.acknowledge([before.batches[0].batch_id]) + assert await c.get_batches() == before + store.fail = False + await c.acknowledge([before.batches[0].batch_id]) + await c.checkpoint() + await c.close() + restored = MeteringCollector(MeteringStore(tmp_path / "usage.json"), clock=clock) + await restored.start() + assert not (await restored.get_batches()).batches + await restored.close() + + async def test_late_finish_and_repeated_cleanup_count_once(self, tmp_path): + clock = FakeClock() + c = MeteringCollector( + MeteringStore(tmp_path / "usage.json"), clock=clock, profiles={"s": VLLM_PROFILE} + ) + await c.start() + a = c.start_attempt(UsageKey(consumer_subject_id="u", service_id="s"), VLLM_PROFILE) + a.mark_dispatched() + a.observe_usage(dict(prompt_tokens=20, completion_tokens=3, total_tokens=23)) + clock.advance(130) + await asyncio.gather(a.finish(), a.finish()) + clock.advance(60) + await c.rotate_if_due() + batches = (await c.get_batches()).batches + assert len(batches) == 1 + assert batches[0].interval_start.minute == 2 + assert batches[0].entries[0].total_tokens == 23 + assert batches[0].interval_end - batches[0].interval_start == timedelta(seconds=60) + await c.close() + + async def test_unknown_only_after_dispatch(self, tmp_path): + clock = FakeClock() + c = MeteringCollector( + MeteringStore(tmp_path / "usage.json"), clock=clock, profiles={"s": VLLM_PROFILE} + ) + await c.start() + key = UsageKey(consumer_subject_id="u", service_id="s") + a = c.start_attempt(key, VLLM_PROFILE) + await a.finish() + b = c.start_attempt(key, VLLM_PROFILE) + b.mark_dispatched() + await b.finish() + await b.finish() + clock.advance() + await c.rotate_if_due() + entry = (await c.get_batches()).batches[0].entries[0] + assert entry.unknown_usage_attempts == 1 + assert entry.total_tokens == 0 + await c.close() + + async def test_backward_clock_pauses_admission(self, tmp_path): + clock = FakeClock() + c = MeteringCollector( + MeteringStore(tmp_path / "usage.json"), clock=clock, profiles={"s": VLLM_PROFILE} + ) + await c.start() + await record(c) + clock.advance(-1) + with pytest.raises(ProxyError): + await c.rotate_if_due() + with pytest.raises(ProxyError): + c.start_attempt(UsageKey(consumer_subject_id="u", service_id="s"), VLLM_PROFILE) + await c.close() + + async def test_active_ack_rejected_atomically(self, tmp_path): + clock = FakeClock() + store = MeteringStore(tmp_path / "usage.json") + c = MeteringCollector(store, clock=clock, profiles={"s": VLLM_PROFILE}) + await c.start() + await record(c) + clock.advance() + await c.rotate_if_due() + before = await c.get_batches() + state = store.load() + assert state is not None + with pytest.raises(ProxyError): + await c.acknowledge([before.batches[0].batch_id, state.active_batch.batch_id]) + assert await c.get_batches() == before + await c.close() + + async def test_concurrent_finalizers_and_storage_backpressure(self, tmp_path): + clock = FakeClock() + c = MeteringCollector( + MeteringStore(tmp_path / "usage.json"), + clock=clock, + profiles={"s": VLLM_PROFILE}, + max_pending=32, + max_entries=1, + ) + await c.start() + await asyncio.gather(*(record(c) for _ in range(20))) + with pytest.raises(ProxyError): + c.start_attempt( + UsageKey(consumer_subject_id="different", service_id="s"), VLLM_PROFILE + ) + clock.advance() + await c.rotate_if_due() + entry = (await c.get_batches()).batches[0].entries[0] + assert ( + entry.prompt_tokens, + entry.cached_prompt_tokens, + entry.completion_tokens, + entry.total_tokens, + ) == (400, 100, 60, 460) + await c.close() + + async def test_old_checkpoint_cannot_resurrect_acked_batch(self, tmp_path): + clock = FakeClock() + path = tmp_path / "usage.json" + c = MeteringCollector(MeteringStore(path), clock=clock, profiles={"s": VLLM_PROFILE}) + await c.start() + await record(c) + clock.advance() + await c.rotate_if_due() + batch = (await c.get_batches()).batches[0] + await asyncio.gather(c.checkpoint(), c.acknowledge([batch.batch_id]), c.checkpoint()) + await c.close() + c = MeteringCollector(MeteringStore(path), clock=clock) + await c.start() + assert not (await c.get_batches()).batches + await c.close() + + +@pytest.mark.asyncio +async def test_repeated_cancellation_does_not_abandon_finalization(tmp_path): + clock = FakeClock() + collector = MeteringCollector( + MeteringStore(tmp_path / "usage.json"), clock=clock, profiles={"s": VLLM_PROFILE} + ) + await collector.start() + attempt = collector.start_attempt( + UsageKey(consumer_subject_id="u", service_id="s"), VLLM_PROFILE + ) + attempt.mark_dispatched() + attempt.observe_usage(dict(prompt_tokens=20, completion_tokens=3, total_tokens=23)) + await collector._lock.acquire() + task = asyncio.create_task(attempt.finish()) + try: + for _ in range(3): + await asyncio.sleep(0) + task.cancel() + await asyncio.sleep(0) + finally: + collector._lock.release() + with pytest.raises(asyncio.CancelledError): + await task + # Finalized before cleanup returns, not postponed until process shutdown. + clock.advance() + await collector.rotate_if_due() + page = await collector.get_batches() + await collector.close() + assert len(page.batches) == 1 and page.batches[0].entries[0].completion_tokens == 3 diff --git a/src/tests/_internal/proxy/gateway/services/test_metering_store.py b/src/tests/_internal/proxy/gateway/services/test_metering_store.py new file mode 100644 index 0000000000..edab714ae2 --- /dev/null +++ b/src/tests/_internal/proxy/gateway/services/test_metering_store.py @@ -0,0 +1,101 @@ +import asyncio +import threading +from datetime import datetime, timedelta, timezone + +import pytest + +from dstack._internal.proxy.gateway.services.metering_store import MeteringStore +from dstack._internal.proxy.lib.schemas.usage import UsageBatch, UsageCheckpoint + + +def checkpoint(): + start = datetime(2026, 11, 16, 10, tzinfo=timezone.utc) + return UsageCheckpoint( + collector_id="collector", + active_batch=UsageBatch( + batch_id="a", interval_start=start, interval_end=start + timedelta(seconds=60) + ), + ) + + +@pytest.mark.asyncio +class TestMeteringStore: + async def test_roundtrip_and_missing_initialized_state(self, tmp_path): + path = tmp_path / "usage.json" + store = MeteringStore(path) + assert store.load() is None + await store.save(checkpoint()) + assert store.load() == checkpoint() + path.unlink() + with pytest.raises(ValueError, match="missing"): + store.load() + store.close() + + async def test_corruption_is_not_a_fresh_collector(self, tmp_path): + path = tmp_path / "usage.json" + path.write_text('{"broken":') + store = MeteringStore(path) + with pytest.raises(ValueError): + store.load() + store.close() + + async def test_failed_replace_preserves_previous_checkpoint(self, tmp_path, monkeypatch): + path = tmp_path / "usage.json" + store = MeteringStore(path) + await store.save(checkpoint()) + original = path.read_bytes() + + def fail(*args): + raise OSError("replace failed") + + monkeypatch.setattr( + "dstack._internal.proxy.gateway.services.metering_store.os.replace", fail + ) + with pytest.raises(OSError): + await store.save(checkpoint()) + assert path.read_bytes() == original + assert not list(tmp_path.glob("*.tmp")) + store.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("cancel_count", [1, 2, 3]) +async def test_cancelled_save_finishes_before_next_writer(tmp_path, monkeypatch, cancel_count): + store = MeteringStore(tmp_path / "usage.json") + entered = threading.Event() + release = threading.Event() + original = store._save + order = [] + + def delayed(state): + if state.active_batch.batch_id == "a": + entered.set() + release.wait(timeout=5) + original(state) + order.append(state.active_batch.batch_id) + + monkeypatch.setattr(store, "_save", delayed) + first = asyncio.create_task(store.save(checkpoint())) + await asyncio.to_thread(entered.wait, 5) + for _ in range(cancel_count): + first.cancel() + await asyncio.sleep(0) + await asyncio.sleep(0) + other = checkpoint().model_copy( + update={"active_batch": checkpoint().active_batch.model_copy(update={"batch_id": "b"})} + ) + second = asyncio.create_task(store.save(other)) + # Task scheduling barriers, not timing assumptions about disk latency. + await asyncio.sleep(0) + await asyncio.sleep(0) + retained_ownership = not first.done() + release.set() + with pytest.raises(asyncio.CancelledError): + await first + await second + assert retained_ownership, "cancelled writer must retain ownership until its thread completes" + assert order == ["a", "b"] + saved = store.load() + assert saved is not None + assert saved.active_batch.batch_id == "b" + store.close() diff --git a/src/tests/_internal/proxy/gateway/test_auth.py b/src/tests/_internal/proxy/gateway/test_auth.py index 3b96306aa4..eff2ce48b1 100644 --- a/src/tests/_internal/proxy/gateway/test_auth.py +++ b/src/tests/_internal/proxy/gateway/test_auth.py @@ -83,3 +83,42 @@ async def test_no_servers_reaches_auth_error_boundary(self, tmp_path): def _get_auth_cache() -> BaseCache: # `aiocache.cached` sets `cache` on the wrapper at runtime, but its type doesn't declare it return GatewayProxyAuthProvider.is_project_member.cache # pyright: ignore[reportAttributeAccessIssue] + + +@pytest.mark.asyncio +async def test_verified_identity_cache_is_scoped_to_provider(): + calls = [] + + def handler(subject): + def respond(request): + calls.append(request.url.path) + return httpx.Response(200, json={"consumer_subject_id": subject}) + + return respond + + async with ( + httpx.AsyncClient( + transport=httpx.MockTransport(handler("user-a")), base_url="http://one" + ) as one, + httpx.AsyncClient( + transport=httpx.MockTransport(handler("user-b")), base_url="http://two" + ) as two, + ): + a, b = GatewayProxyAuthProvider(one), GatewayProxyAuthProvider(two) + subject_a = await a.resolve_subject("project", "same-token") + assert subject_a is not None and subject_a.consumer_subject_id == "user-a" + subject_b = await b.resolve_subject("project", "same-token") + assert subject_b is not None and subject_b.consumer_subject_id == "user-b" + subject_a = await a.resolve_subject("project", "same-token") + assert subject_a is not None and subject_a.consumer_subject_id == "user-a" + assert calls == ["/api/projects/project/authorize_proxy"] * 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("status", [401, 403, 404]) +async def test_missing_or_denied_identity_never_returns_a_subject(status): + async with httpx.AsyncClient( + transport=httpx.MockTransport(lambda request: httpx.Response(status)), + base_url="http://server", + ) as client: + assert await GatewayProxyAuthProvider(client).resolve_subject("p", "t") is None diff --git a/src/tests/_internal/proxy/gateway/test_metering_ingress.py b/src/tests/_internal/proxy/gateway/test_metering_ingress.py new file mode 100644 index 0000000000..f1731299a7 --- /dev/null +++ b/src/tests/_internal/proxy/gateway/test_metering_ingress.py @@ -0,0 +1,206 @@ +"""Opt-in real Nginx topology, with Unix fixture sockets replacing SSH tunnels.""" + +import asyncio +import json +import os +import shutil +import socket +import subprocess +import time + +import httpx +import pytest + +from dstack._internal.proxy.gateway.const import PROXY_PORT_ON_GATEWAY +from dstack._internal.proxy.gateway.services.nginx import ( + LimitReqConfig, + LimitReqZoneConfig, + LocationConfig, + ModelEntrypointConfig, + ReplicaConfig, + ServiceConfig, +) +from tests._internal.proxy.gateway.metering.harness import Harness + + +def configs(root, backend_socket): + model = ModelEntrypointConfig( + domain="model.test", project_name="p", https=False, read_timeout=10 + ) + service = ServiceConfig( + domain="service.test", + project_name="p", + https=False, + auth=True, + client_max_body_size=1024 * 1024, + access_log_path=root / "access.log", + limit_req_zones=[LimitReqZoneConfig(name="test_limit", key="$binary_remote_addr", rpm=1)], + locations=[ + LocationConfig( + prefix="/limited", limit_req=LimitReqConfig(zone="test_limit", burst=0) + ), + LocationConfig(prefix="/"), + ], + replicas=[ReplicaConfig(id="test-replica", socket=backend_socket, port=8000)], + cors_enabled=True, + proxy_buffering=False, + read_timeout=10, + ) + return model, service + + +def test_rendered_routes_keep_management_private(tmp_path): + model, service = configs(tmp_path, tmp_path / "backend.sock") + public = model.render() + direct = service.render() + assert "/api/models/p/" in public + assert "proxy_pass http://service.test.upstream" in direct + assert "/api/usage" not in public + direct + assert "internal;" in direct and "limit_req_status 429;" in direct + assert "proxy_buffering off;" in direct and "set $dstack_replica_hit 1;" in direct + + +@pytest.mark.asyncio +@pytest.mark.skipif( + not os.environ.get("DS002_NGINX"), reason="set DS002_NGINX to a local nginx binary" +) +async def test_real_nginx_ingress(tmp_path): + # Real Nginx earns its process cost: buffering, URI normalization, CORS and auth subrequests. + executable = os.environ["DS002_NGINX"] + assert shutil.which(executable), "DS002_NGINX must point to a working binary" + with socket.socket() as reservation: + reservation.bind(("127.0.0.1", 0)) + port = reservation.getsockname()[1] + url = f"http://127.0.0.1:{port}" + h = Harness(tmp_path, nginx_url=url) + proc = None + await h.start() + try: + model, service = configs(tmp_path, h.backend_socket) + proxy_port = httpx.URL(h.gateway_url).port + rendered = "\n".join(c.render() for c in (model, service)) + rendered = rendered.replace("listen 80;", f"listen 127.0.0.1:{port};") + rendered = rendered.replace("localhost:8000", f"127.0.0.1:{proxy_port}") + # Production default is 8000; assert every upstream points to the isolated listener. + rendered = rendered.replace( + f"localhost:{PROXY_PORT_ON_GATEWAY}", f"127.0.0.1:{proxy_port}" + ) + conf = f"""daemon off; +master_process off; +pid {tmp_path}/nginx.pid; +error_log {tmp_path}/error.log info; +events {{ worker_connections 128; }} +http {{ + access_log off; + client_body_temp_path {tmp_path}/body; + proxy_temp_path {tmp_path}/proxy; + log_format dstack_stat '$time_iso8601 $host $status $request_time $dstack_replica_hit'; + {rendered} +}} +""" + config_path = tmp_path / "nginx.conf" + config_path.write_text(conf) + proc = subprocess.Popen( + [executable, "-p", str(tmp_path), "-c", str(config_path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + async with httpx.AsyncClient(base_url=url, timeout=10) as client: + deadline = time.monotonic() + 10 + while True: + if proc.poll() is not None: + raise RuntimeError((tmp_path / "error.log").read_text()) + try: + await client.get("/", headers={"Host": "model.test"}) + break + except httpx.ConnectError: + if time.monotonic() > deadline: + raise + await asyncio.sleep(0.02) + body = { + "model": "model-a", + "user": "ingress", + "messages": [{"role": "user", "content": "A"}], + "stream": True, + "stream_options": {"include_usage": True}, + } + await h.backend_control(hold=["ingress"]) + async with client.stream( + "POST", + "/chat/completions", + json=body, + headers={ + "Host": "model.test", + "Authorization": "Bearer token-a", + "X-Test-Request-ID": "ingress", + }, + ) as response: + response.raise_for_status() + seen = [] + async for line in response.aiter_lines(): + if line.startswith("data:"): + if not seen: + assert "Hello" in line + await h.backend_control(release=["ingress"]) + seen.append(line) + assert seen[-1] == "data: [DONE]" + await h.wait_finalized("ingress") + await h.advance_clock() + page = await h.batches() + assert page["batches"][0]["entries"][0]["completion_tokens"] == 3 + # Service hostname bypasses Python; valid inference works but adds no counters. + body.update(stream=False, user="direct") + response = await client.post( + "/v1/chat/completions", json=body, headers={"Host": "service.test"} + ) + assert ( + response.status_code == 200 and response.json()["usage"]["completion_tokens"] == 3 + ) + await h.advance_clock() + assert (await h.batches()) == page + variants = [ + "/api/usage/batches", + "/api/usage/batches/ack", + "/../api/usage/batches", + "/%2e%2e/api/usage/batches", + "/%2e%2e%2f%2e%2e%2fusage/batches", + "//api/usage/batches", + "/chat/completions/../../usage/batches", + ] + for host in ["model.test", "service.test"]: + for path in variants: + for method in ["GET", "POST"]: + response = await client.request( + method, + path, + json={"batch_ids": [page["batches"][0]["batch_id"]]}, + headers={"Host": host, "Authorization": "Bearer token-a"}, + ) + assert response.status_code in (400, 403, 404, 405, 422), ( + host, + path, + method, + response.text, + ) + assert (await h.batches()) == page + cors = await client.options( + "/v1/chat/completions", + headers={"Host": "service.test", "Origin": "https://example.test"}, + ) + assert cors.status_code == 204 and cors.headers["access-control-allow-origin"] == "*" + statuses = [ + (await client.get("/limited", headers={"Host": "service.test"})).status_code + for _ in range(3) + ] + assert 429 in statuses + lines = (tmp_path / "access.log").read_text().splitlines() + assert any("service.test 200 " in line and line.endswith(" 1") for line in lines) + assert any("service.test 429 " in line and line.endswith(" 0") for line in lines) + (tmp_path / "ingress-evidence.json").write_text( + json.dumps({"page": page, "limited_statuses": statuses, "sse": seen}, indent=2) + ) + finally: + if proc is not None and proc.poll() is None: + proc.terminate() + await asyncio.to_thread(proc.wait, 5) + await h.stop() diff --git a/src/tests/_internal/proxy/lib/routers/test_model_proxy.py b/src/tests/_internal/proxy/lib/routers/test_model_proxy.py index a2dfa3257c..ecf1fd728b 100644 --- a/src/tests/_internal/proxy/lib/routers/test_model_proxy.py +++ b/src/tests/_internal/proxy/lib/routers/test_model_proxy.py @@ -33,7 +33,9 @@ class ChatClientStub(ChatCompletionsClient): - async def generate(self, request: ChatCompletionsRequest) -> ChatCompletionsResponse: + async def generate( + self, request: ChatCompletionsRequest, *, attempt=None + ) -> ChatCompletionsResponse: return ChatCompletionsResponse( id="chatcmpl-123", choices=[ @@ -55,7 +57,9 @@ async def generate(self, request: ChatCompletionsRequest) -> ChatCompletionsResp ), ) - async def stream(self, request: ChatCompletionsRequest) -> AsyncIterator[ChatCompletionsChunk]: + async def stream( + self, request: ChatCompletionsRequest, *, attempt=None + ) -> AsyncIterator[ChatCompletionsChunk]: for i, word in enumerate(SAMPLE_RESPONSE.split(" ")): if i > 0: word = " " + word diff --git a/src/tests/_internal/proxy/lib/services/test_openai_usage.py b/src/tests/_internal/proxy/lib/services/test_openai_usage.py new file mode 100644 index 0000000000..ce265c040b --- /dev/null +++ b/src/tests/_internal/proxy/lib/services/test_openai_usage.py @@ -0,0 +1,278 @@ +import json + +import httpx +import pytest +from fastapi import FastAPI + +from dstack._internal.proxy.gateway.repo.repo import GatewayProxyRepo +from dstack._internal.proxy.gateway.services.metering import MeteringCollector +from dstack._internal.proxy.gateway.services.metering_store import MeteringStore +from dstack._internal.proxy.lib.auth import BaseProxyAuthProvider +from dstack._internal.proxy.lib.errors import ProxyError +from dstack._internal.proxy.lib.models import ChatModel, OpenAIChatModelFormat +from dstack._internal.proxy.lib.routers.model_proxy import router as model_router +from dstack._internal.proxy.lib.schemas.model_proxy import ChatCompletionsRequest +from dstack._internal.proxy.lib.schemas.usage import AuthorizedSubject, UsageKey +from dstack._internal.proxy.lib.services.model_proxy.clients.openai import OpenAIChatCompletions +from dstack._internal.proxy.lib.services.usage import VLLM_PROFILE +from dstack._internal.proxy.lib.testing.common import ProxyTestDependencyInjector, make_service +from tests._internal.proxy.gateway.services.test_metering import FakeClock + +USAGE = { + "prompt_tokens": 20, + "completion_tokens": 3, + "total_tokens": 23, + "prompt_tokens_details": {"cached_tokens": 5}, +} + + +class FragmentedStream(httpx.AsyncByteStream): + def __init__(self, data): + self.data = data + self.closed = False + + async def __aiter__(self): + for offset in range(0, len(self.data), 3): + yield self.data[offset : offset + 3] + + async def aclose(self): + self.closed = True + + +@pytest.mark.asyncio +@pytest.mark.parametrize("stream,include_usage", [(False, False), (True, True), (True, False)]) +async def test_backend_usage_is_observed_and_forwarded(tmp_path, stream, include_usage): + clock = FakeClock() + c = MeteringCollector( + MeteringStore(tmp_path / "usage.json"), clock=clock, profiles={"s": VLLM_PROFILE} + ) + await c.start() + attempt = c.start_attempt(UsageKey(consumer_subject_id="u", service_id="s"), VLLM_PROFILE) + requests = [] + response = {"id": "answer", "created": 1, "model": "test", "choices": [], "usage": USAGE} + content = {"model": "test", "choices": [{"index": 0, "delta": {"content": "Hello"}}]} + wire = ( + "data: " + + json.dumps(content) + + "\n\n" + + "data: " + + json.dumps(response) + + "\n\n" + + "data: " + + json.dumps(response) + + "\n\ndata: [DONE]\n\n" + ).encode() + transport_stream = FragmentedStream(wire) + + def backend(request): + requests.append(json.loads(request.content)) + return ( + httpx.Response(200, stream=transport_stream) + if stream + else httpx.Response(200, json=response) + ) + + request = ChatCompletionsRequest.model_validate( + { + "model": "test", + "messages": [], + "stream": stream, + "stream_options": {"include_usage": include_usage}, + } + ) + async with httpx.AsyncClient( + transport=httpx.MockTransport(backend), base_url="http://backend" + ) as http: + client = OpenAIChatCompletions(http, "/v1") + if stream: + chunks = [chunk async for chunk in client.stream(request, attempt=attempt)] + assert requests[0]["stream_options"]["include_usage"] is True + assert request.stream_options is not None + assert request.stream_options.include_usage is include_usage + assert len(chunks) == (3 if include_usage else 1) + if include_usage: + usage = chunks[-1].usage + assert usage is not None and usage.prompt_tokens_details is not None + assert usage.prompt_tokens_details.cached_tokens == 5 + assert transport_stream.closed + else: + result = await client.generate(request, attempt=attempt) + assert result.usage.prompt_tokens_details is not None + assert result.usage.prompt_tokens_details.cached_tokens == 5 + await attempt.finish() + await attempt.finish() + clock.advance() + await c.rotate_if_due() + entry = (await c.get_batches()).batches[0].entries[0] + assert ( + entry.prompt_tokens, + entry.cached_prompt_tokens, + entry.completion_tokens, + entry.total_tokens, + ) == (20, 5, 3, 23) + assert entry.unknown_usage_attempts == 0 + await c.close() + + +@pytest.mark.asyncio +async def test_truncated_stream_is_unknown_not_synthetic_done(tmp_path): + clock = FakeClock() + c = MeteringCollector( + MeteringStore(tmp_path / "usage.json"), clock=clock, profiles={"s": VLLM_PROFILE} + ) + await c.start() + attempt = c.start_attempt(UsageKey(consumer_subject_id="u", service_id="s"), VLLM_PROFILE) + stream = FragmentedStream(b'data: {"model":"test","choices":[]}\n\n') + async with httpx.AsyncClient( + transport=httpx.MockTransport(lambda request: httpx.Response(200, stream=stream)), + base_url="http://backend", + ) as http: + client = OpenAIChatCompletions(http, "/v1") + with pytest.raises(ProxyError): + [ + chunk + async for chunk in client.stream( + ChatCompletionsRequest(model="test", messages=[], stream=True), attempt=attempt + ) + ] + await attempt.finish() + clock.advance() + await c.rotate_if_due() + entry = (await c.get_batches()).batches[0].entries[0] + assert entry.unknown_usage_attempts == 1 and entry.total_tokens == 0 + assert stream.closed + await c.close() + + +class IdentityProvider(BaseProxyAuthProvider): + async def is_project_member(self, project_name, token): + return token == "token" + + async def resolve_subject(self, project_name, token): + return AuthorizedSubject(consumer_subject_id="verified-user") if token == "token" else None + + +class MeteredInjector(ProxyTestDependencyInjector): + def __init__(self, repo, collector): + super().__init__(repo, IdentityProvider()) + self.collector = collector + + def get_usage_observer(self): + return self.collector + + +@pytest.mark.asyncio +@pytest.mark.parametrize("stream", [False, True]) +async def test_model_handler_finalizes_verified_usage(tmp_path, monkeypatch, stream): + clock = FakeClock() + collector = MeteringCollector( + MeteringStore(tmp_path / "usage.json"), clock=clock, profiles={"s": VLLM_PROFILE} + ) + await collector.start() + repo = GatewayProxyRepo() + await repo.set_service(make_service("p", "run", run_id="s")) + await repo.set_model( + ChatModel( + project_name="p", + name="test", + run_name="run", + created_at=clock.utc_now(), + format_spec=OpenAIChatModelFormat(format="openai", prefix="/v1"), + ) + ) + app = FastAPI() + app.state.proxy_dependency_injector = MeteredInjector(repo, collector) + app.include_router(model_router, prefix="/models") + response = {"id": "answer", "created": 1, "model": "test", "choices": [], "usage": USAGE} + wire = ("data: " + json.dumps(response) + "\n\ndata: [DONE]\n\n").encode() + async with httpx.AsyncClient( + transport=httpx.MockTransport( + lambda request: httpx.Response(200, stream=FragmentedStream(wire)) + if stream + else httpx.Response(200, json=response) + ), + base_url="http://backend", + ) as backend: + + async def connection(*args, **kwargs): + return backend + + monkeypatch.setattr( + "dstack._internal.proxy.lib.routers.model_proxy.get_service_replica_client", connection + ) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://gateway" + ) as client: + result = await client.post( + "/models/p/chat/completions", + headers={"Authorization": "Bearer token", "consumer_subject_id": "spoofed"}, + json={ + "model": "test", + "messages": [], + "stream": stream, + "stream_options": {"include_usage": True}, + "user": "spoofed", + }, + ) + assert result.status_code == 200 + if stream: + assert '"cached_tokens":5' in result.text + else: + assert result.json()["usage"]["prompt_tokens_details"]["cached_tokens"] == 5 + clock.advance() + await collector.rotate_if_due() + batches = (await collector.get_batches()).batches + assert len(batches) == 1 + assert batches[0].entries[0].consumer_subject_id == "verified-user" + assert batches[0].entries[0].cached_prompt_tokens == 5 + assert batches[0].entries[0].total_tokens == 23 + await collector.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("intermediate_only", [True, False]) +async def test_confirmed_final_usage_survives_invalid_duplicates(tmp_path, intermediate_only): + clock = FakeClock() + collector = MeteringCollector( + MeteringStore(tmp_path / "usage.json"), clock=clock, profiles={"s": VLLM_PROFILE} + ) + await collector.start() + attempt = collector.start_attempt( + UsageKey(consumer_subject_id="u", service_id="s"), VLLM_PROFILE + ) + final = {"model": "test", "choices": [], "usage": USAGE} + if intermediate_only: + events = [ + {**final, "choices": [{"index": 0, "delta": {"content": "Hi"}, "finish_reason": None}]} + ] + else: + events = [ + final, + {**final, "usage": {**USAGE, "completion_tokens": -1, "total_tokens": 19}}, + ] + wire = "".join("data: " + json.dumps(event) + "\n\n" for event in events) + if not intermediate_only: + wire += "data: [DONE]\n\n" + async with httpx.AsyncClient( + transport=httpx.MockTransport( + lambda request: httpx.Response(200, stream=FragmentedStream(wire.encode())) + ), + base_url="http://backend", + ) as http: + client = OpenAIChatCompletions(http, "/v1") + request = ChatCompletionsRequest(model="test", messages=[], stream=True) + if intermediate_only: + with pytest.raises(ProxyError): + [chunk async for chunk in client.stream(request, attempt=attempt)] + else: + [chunk async for chunk in client.stream(request, attempt=attempt)] + await attempt.finish() + clock.advance() + await collector.rotate_if_due() + entry = (await collector.get_batches()).batches[0].entries[0] + await collector.close() + if intermediate_only: + assert entry.unknown_usage_attempts == 1 and entry.total_tokens == 0 + else: + assert entry.unknown_usage_attempts == 0 and entry.total_tokens == 23 + assert entry.cached_prompt_tokens == 5 diff --git a/src/tests/_internal/proxy/lib/services/test_sse.py b/src/tests/_internal/proxy/lib/services/test_sse.py new file mode 100644 index 0000000000..5d451c30b0 --- /dev/null +++ b/src/tests/_internal/proxy/lib/services/test_sse.py @@ -0,0 +1,28 @@ +import pytest + +from dstack._internal.proxy.lib.services.model_proxy.sse import SSEDecoder + + +class TestSSEDecoder: + @pytest.mark.parametrize("step", [1, 2, 3, 17, 4096]) + def test_fragmentation_utf8_crlf_comments_and_multiple_events(self, step): + wire = ': keepalive\r\ndata: {"text":"привет"}\r\n\r\ndata: first\ndata: second\n\ndata: [DONE]\n\n'.encode() + parser = SSEDecoder() + events = [] + for start in range(0, len(wire), step): + events.extend(parser.feed(wire[start : start + step])) + parser.finish() + assert events == ['{"text":"привет"}', "first\nsecond", "[DONE]"] + + def test_bounds_unfinished_events_and_rejects_truncated_utf8(self): + parser = SSEDecoder(max_event_bytes=16) + with pytest.raises(ValueError): + parser.feed(b"data: " + b"x" * 17) + parser = SSEDecoder() + parser.feed(b"data: partial") + with pytest.raises(ValueError): + parser.finish() + parser = SSEDecoder() + parser.feed(b"data: \xd0") + with pytest.raises(ValueError): + parser.finish() diff --git a/src/tests/_internal/proxy/lib/test_usage.py b/src/tests/_internal/proxy/lib/test_usage.py new file mode 100644 index 0000000000..bce76a57f9 --- /dev/null +++ b/src/tests/_internal/proxy/lib/test_usage.py @@ -0,0 +1,110 @@ +from datetime import datetime, timedelta, timezone + +import pytest +from pydantic import ValidationError + +from dstack._internal.core.models.common import validate_json_extra_ignore +from dstack._internal.proxy.lib.schemas.model_proxy import ( + ChatCompletionsChunk, + ChatCompletionsRequest, + ChatCompletionsUsage, +) +from dstack._internal.proxy.lib.schemas.usage import UsageBatch, UsageCheckpoint, UsageEntry +from dstack._internal.proxy.lib.services.usage import normalize_usage + +PROFILE = "vllm-0.19.1-prompt-details" + + +class TestUsagePreservation: + def test_usage_round_trip(self): + usage = validate_json_extra_ignore( + ChatCompletionsUsage, + '{"prompt_tokens":20,"completion_tokens":3,"total_tokens":23,' + '"prompt_tokens_details":{"cached_tokens":5}}', + ) + assert usage.model_dump()["prompt_tokens_details"] == {"cached_tokens": 5} + + def test_stream_options_and_usage_only_event(self): + request = ChatCompletionsRequest.model_validate( + { + "model": "test", + "messages": [], + "stream": True, + "stream_options": {"include_usage": True}, + } + ) + assert request.model_dump(exclude_unset=True)["stream_options"] == {"include_usage": True} + chunk = validate_json_extra_ignore( + ChatCompletionsChunk, + '{"model":"test","choices":[],"usage":{"prompt_tokens":20,' + '"completion_tokens":3,"total_tokens":23}}', + ) + assert chunk.usage is not None + assert chunk.usage.prompt_tokens == 20 + assert "stream_options" not in ChatCompletionsRequest( + model="test", messages=[] + ).model_dump(exclude_unset=True) + + +class TestUsageNormalization: + @pytest.mark.parametrize("details", [None, {"cached_tokens": 5}]) + def test_cache_normalization_is_profile_specific(self, details): + raw = dict( + prompt_tokens=20, completion_tokens=3, total_tokens=23, prompt_tokens_details=details + ) + usage = normalize_usage(raw, PROFILE) + assert usage is not None + assert usage.cached_prompt_tokens == (0 if details is None else 5) + assert usage.prompt_tokens == 20 + assert normalize_usage(raw, "unverified") is None + + @pytest.mark.parametrize( + "patch", + [ + {"prompt_tokens": -1}, + {"completion_tokens": True}, + {"total_tokens": 2}, + {"prompt_tokens": 20.0}, + {"prompt_tokens": "20"}, + {"prompt_tokens_details": {"cached_tokens": 21}}, + {"prompt_tokens_details": {"cached_tokens": None}}, + ], + ) + def test_invalid_usage_is_unknown(self, patch): + raw = dict(prompt_tokens=20, completion_tokens=3, total_tokens=23) + assert normalize_usage(raw | patch, PROFILE) is None + assert normalize_usage(None, PROFILE) is None + + +class TestUsageContracts: + def test_checkpoint_rejects_duplicate_keys_and_ids(self): + entry = UsageEntry( + consumer_subject_id="u", + service_id="s", + prompt_tokens=20, + cached_prompt_tokens=5, + completion_tokens=3, + total_tokens=23, + ) + start = datetime(2026, 11, 16, 10, tzinfo=timezone.utc) + batch = UsageBatch( + batch_id="a", + interval_start=start, + interval_end=start + timedelta(seconds=60), + entries=[entry], + ) + with pytest.raises(ValidationError): + UsageBatch.model_validate(batch.model_dump() | {"entries": [entry, entry]}) + with pytest.raises(ValidationError): + UsageCheckpoint(collector_id="c", active_batch=batch, pending_batches=[batch]) + with pytest.raises(ValidationError): + UsageBatch.model_validate( + batch.model_dump() | {"interval_end": start + timedelta(seconds=30)} + ) + + @pytest.mark.parametrize("value", [-1, True, 1.0, "1"]) + def test_rejects_invalid_persisted_counter(self, value): + with pytest.raises(ValidationError): + UsageEntry( + consumer_subject_id="u", service_id="s", prompt_tokens=value, total_tokens=value + ) diff --git a/src/tests/_internal/server/background/scheduled_tasks/test_usage.py b/src/tests/_internal/server/background/scheduled_tasks/test_usage.py new file mode 100644 index 0000000000..788e9deb5e --- /dev/null +++ b/src/tests/_internal/server/background/scheduled_tasks/test_usage.py @@ -0,0 +1,167 @@ +import asyncio +import contextvars +import uuid +from contextlib import asynccontextmanager +from unittest.mock import AsyncMock + +import httpx +import pytest +from sqlalchemy import func, select + +from dstack._internal.proxy.lib.schemas.usage import UsageAckResponse, UsageBatchPage +from dstack._internal.server.background.scheduled_tasks import usage +from dstack._internal.server.models import UsageBatchModel, UsageCounterModel +from dstack._internal.server.testing.common import ( + create_backend, + create_gateway_replica, + create_project, + create_user, +) +from tests._internal.server.services.test_usage import batch + +DB_SESSION = contextvars.ContextVar("usage_test_db_session", default=False) + + +class Client: + def __init__(self, test_db, items): + self.db = test_db + self.items = items + self.acks = [] + self.fetches = 0 + self.lose_ack = False + + def assert_no_db_connection(self): + # Async sessions are tracked explicitly below, independent of pool implementation. + assert not DB_SESSION.get() + + async def fetch_usage_batches(self, limit=100): + self.assert_no_db_connection() + self.fetches += 1 + return UsageBatchPage( + collector_id="collector", batches=self.items[:limit], has_more=len(self.items) > limit + ) + + async def acknowledge_usage(self, ids): + self.assert_no_db_connection() + async with self.db.get_session() as session: + committed = set(await session.scalars(select(UsageBatchModel.batch_id))) + assert set(ids) <= committed + self.acks.append(ids) + self.items = [b for b in self.items if b.batch_id not in ids] + if self.lose_ack: + self.lose_ack = False + raise httpx.ReadError("ACK reply lost") + return UsageAckResponse(acknowledged_batch_ids=ids) + + +def setup(monkeypatch, db, client): + original = usage.get_session_ctx + + @asynccontextmanager + async def tracked(): + token = DB_SESSION.set(True) + try: + async with original() as session: + yield session + finally: + DB_SESSION.reset(token) + + monkeypatch.setattr(usage, "get_session_ctx", tracked) + + @asynccontextmanager + async def connection_client(): + yield client + + connection = type( + "Connection", (), {"ip_address": "1.1.1.1", "client": staticmethod(connection_client)} + )() + monkeypatch.setattr( + usage.gateway_connections_pool, "all", AsyncMock(return_value=[connection]) + ) + return connection + + +async def registered(session): + user = await create_user(session) + project = await create_project(session, owner=user) + backend = await create_backend(session, project.id) + return await create_gateway_replica(session, backend) + + +@pytest.mark.asyncio +async def test_commit_before_ack_and_lost_reply(session, test_db, monkeypatch): + await registered(session) + client = Client(test_db, [batch()]) + setup(monkeypatch, test_db, client) + client.lose_ack = True + await usage.collect_gateway_usage() + # Simulate a retry of the same already committed batch. + client.items = [batch()] + await usage.collect_gateway_usage() + async with test_db.get_session() as s: + assert await s.scalar(select(func.count()).select_from(UsageCounterModel)) == 1 + assert client.acks == [["batch-1"], ["batch-1"]] + + +@pytest.mark.asyncio +async def test_failed_transaction_sends_no_ack(session, test_db, monkeypatch): + await registered(session) + client = Client(test_db, [batch()]) + setup(monkeypatch, test_db, client) + original = usage.ingest_usage_batch + + async def fail(*args, **kwargs): + await original(*args, **kwargs) + raise RuntimeError("Injected transaction failure") + + monkeypatch.setattr(usage, "ingest_usage_batch", fail) + await usage.collect_gateway_usage() + assert not client.acks + async with test_db.get_session() as s: + assert await s.scalar(select(func.count()).select_from(UsageBatchModel)) == 0 + + +@pytest.mark.asyncio +async def test_conflict_never_acknowledged(session, test_db, monkeypatch): + await registered(session) + client = Client(test_db, [batch()]) + setup(monkeypatch, test_db, client) + async with test_db.get_session() as s: + await usage.ingest_usage_batch(s, uuid.uuid4(), "collector", batch()) + await s.commit() + await usage.collect_gateway_usage() + assert not client.acks and client.items + + +@pytest.mark.asyncio +async def test_page_budget_and_overlapping_collectors(session, test_db, monkeypatch): + await registered(session) + client = Client(test_db, [batch(f"b-{i}", i) for i in range(5)]) + setup(monkeypatch, test_db, client) + monkeypatch.setattr(usage, "PAGE_SIZE", 1) + monkeypatch.setattr(usage, "MAX_PAGES", 2) + await usage.collect_gateway_usage() + assert len(client.items) == 3 and client.fetches == 2 + await asyncio.gather(usage.collect_gateway_usage(), usage.collect_gateway_usage()) + await ( + usage.collect_gateway_usage() + ) # Overlapping pages may replay; a later tick drains the rest. + async with test_db.get_session() as s: + assert await s.scalar(select(func.count()).select_from(UsageBatchModel)) == 5 + + +@pytest.mark.asyncio +async def test_old_gateway_skipped_without_stats_calls(session, test_db, monkeypatch): + await registered(session) + client = Client(test_db, []) + setup(monkeypatch, test_db, client) + + async def unavailable(limit=100): + response = httpx.Response( + 404, request=httpx.Request("GET", "http://gateway/api/usage/batches") + ) + response.raise_for_status() + + monkeypatch.setattr(client, "fetch_usage_batches", unavailable) + await usage.collect_gateway_usage() + assert not client.acks diff --git a/src/tests/_internal/server/routers/test_projects.py b/src/tests/_internal/server/routers/test_projects.py index 37ec3ce835..70f7fef49a 100644 --- a/src/tests/_internal/server/routers/test_projects.py +++ b/src/tests/_internal/server/routers/test_projects.py @@ -2420,3 +2420,33 @@ async def test_rejects_unreachable_templates_repo( } ] } + + +class TestAuthorizeProxy: + @pytest.mark.asyncio + @pytest.mark.parametrize("kind", ["member", "admin", "public", "denied", "invalid"]) + async def test_returns_authenticated_actor_only_after_access_check( + self, session, client, kind + ): + owner = await create_user( + session=session, name="capacity-owner", global_role=GlobalRole.USER + ) + actor = await create_user( + session=session, + name="consumer", + global_role=(GlobalRole.ADMIN if kind == "admin" else GlobalRole.USER), + ) + project = await create_project(session=session, owner=owner, is_public=kind == "public") + if kind == "member": + await add_project_member( + session=session, project=project, user=actor, project_role=ProjectRole.USER + ) + response = await client.post( + f"/api/projects/{project.name}/authorize_proxy", + headers=get_auth_headers("bad-token" if kind == "invalid" else actor.token), + ) + if kind in ("denied", "invalid"): + assert response.status_code in (401, 403) + else: + assert response.status_code == 200 + assert response.json() == {"consumer_subject_id": actor.id.hex} diff --git a/src/tests/_internal/server/services/gateways/test_usage_client.py b/src/tests/_internal/server/services/gateways/test_usage_client.py new file mode 100644 index 0000000000..a9e96e8421 --- /dev/null +++ b/src/tests/_internal/server/services/gateways/test_usage_client.py @@ -0,0 +1,53 @@ +import httpx +import pytest +from pydantic import ValidationError + +from dstack._internal.server.services.gateways.client import AsyncClientWrapper, GatewayClient + + +@pytest.mark.asyncio +async def test_usage_client_contract(): + seen = [] + + def response(request): + seen.append(request) + if request.method == "GET": + assert request.url.path == "/api/usage/batches" and request.url.params["limit"] == "2" + return httpx.Response( + 200, json={"collector_id": "c", "batches": [], "has_more": False} + ) + assert request.url.path == "/api/usage/batches/ack" + return httpx.Response(200, json={"acknowledged_batch_ids": ["b"]}) + + client = GatewayClient(port=1) + await client._client.aclose() + async with AsyncClientWrapper(transport=httpx.MockTransport(response)) as http: + client._client = http + assert (await client.fetch_usage_batches(2)).collector_id == "c" + assert (await client.acknowledge_usage(["b"])).acknowledged_batch_ids == ["b"] + assert all(r.extensions["timeout"]["read"] == 10 for r in seen) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("code", [404, 405, 503]) +async def test_usage_client_http_errors(code): + client = GatewayClient(port=1) + await client._client.aclose() + async with AsyncClientWrapper( + transport=httpx.MockTransport(lambda r: httpx.Response(code)) + ) as http: + client._client = http + with pytest.raises(httpx.HTTPStatusError): + await client.fetch_usage_batches() + + +@pytest.mark.asyncio +async def test_usage_client_rejects_malformed_data(): + client = GatewayClient(port=1) + await client._client.aclose() + async with AsyncClientWrapper( + transport=httpx.MockTransport(lambda r: httpx.Response(200, json={})) + ) as http: + client._client = http + with pytest.raises(ValidationError): + await client.fetch_usage_batches() diff --git a/src/tests/_internal/server/services/test_usage.py b/src/tests/_internal/server/services/test_usage.py new file mode 100644 index 0000000000..1193963dd8 --- /dev/null +++ b/src/tests/_internal/server/services/test_usage.py @@ -0,0 +1,96 @@ +import asyncio +import uuid +from datetime import datetime, timedelta, timezone + +import pytest +from sqlalchemy import func, select + +from dstack._internal.proxy.lib.schemas.usage import UsageBatch, UsageEntry +from dstack._internal.server.models import UsageBatchModel, UsageCollectorModel, UsageCounterModel +from dstack._internal.server.services.usage import UsageConflict, ingest_usage_batch + + +def batch(batch_id="batch-1", offset=0, tokens=3): + start = datetime(2026, 11, 16, 10, tzinfo=timezone.utc) + timedelta(minutes=offset) + return UsageBatch( + batch_id=batch_id, + interval_start=start, + interval_end=start + timedelta(minutes=1), + entries=[ + UsageEntry( + consumer_subject_id="1" * 32, + service_id="a" * 32, + prompt_tokens=20, + cached_prompt_tokens=5, + completion_tokens=tokens, + total_tokens=20 + tokens, + ) + ], + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) +async def test_commit_replay_conflict_and_historical_ids(test_db): + gateway = uuid.uuid4() + item = batch(tokens=2**40) + async with test_db.get_session() as session: + assert (await ingest_usage_batch(session, gateway, "collector", item)).inserted + await session.commit() + async with test_db.get_session() as session: + assert not (await ingest_usage_batch(session, gateway, "collector", item)).inserted + await session.commit() + async with test_db.get_session() as session: + with pytest.raises(UsageConflict): + await ingest_usage_batch(session, gateway, "collector", batch(tokens=4)) + await session.rollback() + row = (await session.scalars(select(UsageCounterModel))).one() + assert row.completion_tokens == 2**40 + assert row.consumer_subject_id == "1" * 32 and row.service_id == "a" * 32 + assert await session.scalar(select(func.count()).select_from(UsageBatchModel)) == 1 + # Historical attribution is retained even without corresponding live user/run rows. + + +@pytest.mark.asyncio +@pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) +async def test_rollback_leaves_no_receipt_or_entries(test_db): + async with test_db.get_session() as session: + await ingest_usage_batch(session, uuid.uuid4(), "collector", batch()) + await session.rollback() + async with test_db.get_session() as session: + for model in [UsageCollectorModel, UsageBatchModel, UsageCounterModel]: + assert await session.scalar(select(func.count()).select_from(model)) == 0 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) +async def test_identity_and_interval_conflicts(test_db): + gateway = uuid.uuid4() + async with test_db.get_session() as session: + await ingest_usage_batch(session, gateway, "collector", batch()) + await session.commit() + for g, c, b in [ + (uuid.uuid4(), "collector", batch()), + (gateway, "reset", batch()), + (gateway, "collector", batch("duplicate-minute")), + ]: + async with test_db.get_session() as session: + with pytest.raises(UsageConflict): + await ingest_usage_batch(session, g, c, b) + await session.rollback() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("test_db", ["postgres"], indirect=True) +async def test_concurrent_pollers_commit_once(test_db): + gateway = uuid.uuid4() + + async def ingest(): + async with test_db.get_session() as session: + result = await ingest_usage_batch(session, gateway, "collector", batch()) + await session.commit() + return result.inserted + + assert sorted(await asyncio.gather(ingest(), ingest())) == [False, True] + async with test_db.get_session() as session: + assert await session.scalar(select(func.count()).select_from(UsageCounterModel)) == 1 From 072439989307fa8570bab2a6edc88547ae3e9f75 Mon Sep 17 00:00:00 2001 From: Igx22 Date: Tue, 17 Nov 2026 00:38:19 +0700 Subject: [PATCH 2/7] Simplify Gateway usage identity and extend setup retries Replace collector IDs with historical Gateway and replica identities. Consolidate the unapplied usage migration into two tables, preserve legacy checkpoint and API compatibility, and cover replay, persistence, multi-replica collection, and migration behavior. Include the local Gateway configuration retry increase from 50 to 300. Validation: 204 tests passed, 1 opt-in real-minute test skipped; local Nginx and PostgreSQL checks enabled. Ruff and formatting checks passed for all 18 changed files. --- .../proxy/gateway/services/metering.py | 5 +- .../proxy/gateway/services/metering_store.py | 44 +++++- .../_internal/proxy/lib/schemas/usage.py | 26 +++- .../background/scheduled_tasks/usage.py | 35 +++-- ..._9a2e8f1f3c37_add_gateway_usage_batches.py | 48 +++--- src/dstack/_internal/server/models.py | 22 ++- .../server/services/gateways/__init__.py | 3 +- .../server/services/gateways/client.py | 9 +- src/dstack/_internal/server/services/usage.py | 76 +++++---- .../proxy/gateway/metering/receiver.py | 72 ++++++--- .../proxy/gateway/metering/test_helpers.py | 56 ++++++- .../proxy/gateway/metering/test_scenarios.py | 98 +++++++++++- .../gateway/services/test_metering_store.py | 88 ++++++++++- src/tests/_internal/proxy/lib/test_usage.py | 2 +- .../background/scheduled_tasks/test_usage.py | 78 ++++++++-- .../services/gateways/test_usage_client.py | 22 ++- .../_internal/server/services/test_usage.py | 60 +++++-- .../_internal/server/test_usage_migration.py | 146 ++++++++++++++++++ 18 files changed, 715 insertions(+), 175 deletions(-) create mode 100644 src/tests/_internal/server/test_usage_migration.py diff --git a/src/dstack/_internal/proxy/gateway/services/metering.py b/src/dstack/_internal/proxy/gateway/services/metering.py index 8ed56f2d35..01126f89ee 100644 --- a/src/dstack/_internal/proxy/gateway/services/metering.py +++ b/src/dstack/_internal/proxy/gateway/services/metering.py @@ -68,9 +68,7 @@ async def start(self) -> None: return saved = await asyncio.to_thread(self.store.load) now = self.clock.utc_now() - self._state = saved or UsageCheckpoint( - collector_id=uuid.uuid4().hex, active_batch=self._new_batch(now) - ) + self._state = saved or UsageCheckpoint(active_batch=self._new_batch(now)) self._entries = {entry.key: entry for entry in self._state.active_batch.entries} self._published = {batch.batch_id for batch in self._state.pending_batches} self._pending_bytes = sum( @@ -152,7 +150,6 @@ async def get_batches(self, limit: int = 100) -> UsageBatchPage: raise ProxyError("Usage metering is not initialized", 404) batches = [b for b in self._state.pending_batches if b.batch_id in self._published] return UsageBatchPage( - collector_id=self._state.collector_id, batches=batches[:limit], has_more=len(batches) > limit, ).model_copy(deep=True) diff --git a/src/dstack/_internal/proxy/gateway/services/metering_store.py b/src/dstack/_internal/proxy/gateway/services/metering_store.py index 612834da1d..9db96f6c84 100644 --- a/src/dstack/_internal/proxy/gateway/services/metering_store.py +++ b/src/dstack/_internal/proxy/gateway/services/metering_store.py @@ -5,11 +5,14 @@ import json import os import tempfile +import uuid from pathlib import Path from typing import Any from dstack._internal.proxy.lib.cancellation import await_completion -from dstack._internal.proxy.lib.schemas.usage import UsageCheckpoint +from dstack._internal.proxy.lib.schemas.usage import LegacyUsageCheckpoint, UsageCheckpoint + +_INITIALIZED = "usage-state-v2" class MeteringStore: @@ -35,11 +38,37 @@ def load(self) -> UsageCheckpoint | None: raw = source.read(self.max_bytes + 1) if len(raw) > self.max_bytes: raise ValueError("Usage checkpoint exceeds size limit") - state = UsageCheckpoint.model_validate(json.loads(raw, object_pairs_hook=_unique_object)) - if self._marker.exists() and self._marker.read_text() != state.collector_id: - raise ValueError("Usage collector identity mismatch") + data = json.loads(raw, object_pairs_hook=_unique_object) + if not isinstance(data, dict): + raise ValueError("Usage checkpoint must be an object") + marker = self._read_marker() + if data.get("schema_version", 1) == 1: + legacy = LegacyUsageCheckpoint.model_validate(data) + if marker is not None and marker != legacy.collector_id: + raise ValueError("Legacy usage identity mismatch") + state = UsageCheckpoint.model_validate( + legacy.model_dump(exclude={"schema_version", "collector_id"}) + ) + self._save(state) + else: + state = UsageCheckpoint.model_validate(data) + if marker != _INITIALIZED: + # Recovery after checkpoint replacement but before marker replacement. + self._save(state) return state + def _read_marker(self) -> str | None: + if not self._marker.exists(): + return None + marker = self._marker.read_text() + if marker != _INITIALIZED: + try: + if uuid.UUID(marker).hex != marker: + raise ValueError("Non-canonical legacy marker") + except ValueError as exc: + raise ValueError("Invalid usage initialized marker") from exc + return marker + async def save(self, state: UsageCheckpoint) -> None: # Deep copy before crossing the thread boundary; the writer owns a consistent snapshot. snapshot = state.model_copy(deep=True) @@ -71,11 +100,10 @@ def _save(self, state: UsageCheckpoint) -> None: raw = state.model_dump_json().encode() if len(raw) > self.max_bytes: raise OSError("Usage checkpoint exceeds storage limit") - if self._marker.exists() and self._marker.read_text() != state.collector_id: - raise ValueError("Refusing to replace collector identity") + marker = self._read_marker() self._atomic_write(self.path, raw) - if not self._marker.exists(): - self._atomic_write(self._marker, state.collector_id.encode()) + if marker != _INITIALIZED: + self._atomic_write(self._marker, _INITIALIZED.encode()) @staticmethod def _atomic_write(path: Path, raw: bytes) -> None: diff --git a/src/dstack/_internal/proxy/lib/schemas/usage.py b/src/dstack/_internal/proxy/lib/schemas/usage.py index ba576b802d..fe10feb1af 100644 --- a/src/dstack/_internal/proxy/lib/schemas/usage.py +++ b/src/dstack/_internal/proxy/lib/schemas/usage.py @@ -66,9 +66,7 @@ def check_interval_and_keys(self) -> Self: return self -class UsageCheckpoint(UsageModel): - schema_version: Literal[1] = 1 - collector_id: Identifier +class _UsageCheckpoint(UsageModel): active_batch: UsageBatch pending_batches: list[UsageBatch] = Field(default_factory=list) @@ -85,9 +83,18 @@ def check_batch_ids(self) -> Self: return self -class UsageBatchPage(UsageModel): +class UsageCheckpoint(_UsageCheckpoint): + schema_version: Literal[2] = 2 + + +class LegacyUsageCheckpoint(_UsageCheckpoint): + """Read-only local format used before source identity moved to server.""" + schema_version: Literal[1] = 1 collector_id: Identifier + + +class _UsageBatchPage(UsageModel): batches: list[UsageBatch] = Field(default_factory=list, max_length=100) has_more: bool = False @@ -98,6 +105,17 @@ def check_ids(self) -> Self: return self +class UsageBatchPage(_UsageBatchPage): + schema_version: Literal[2] = 2 + + +class LegacyUsageBatchPage(_UsageBatchPage): + """Read-only compatibility for Gateways upgraded after the server.""" + + schema_version: Literal[1] = 1 + collector_id: Identifier + + class UsageAckRequest(UsageModel): batch_ids: list[Identifier] = Field(min_length=1, max_length=100) diff --git a/src/dstack/_internal/server/background/scheduled_tasks/usage.py b/src/dstack/_internal/server/background/scheduled_tasks/usage.py index 65bcbd90c8..9b26bc96ad 100644 --- a/src/dstack/_internal/server/background/scheduled_tasks/usage.py +++ b/src/dstack/_internal/server/background/scheduled_tasks/usage.py @@ -9,7 +9,7 @@ from sqlalchemy import select from dstack._internal.server.db import get_db, get_session_ctx -from dstack._internal.server.models import GatewayReplicaModel +from dstack._internal.server.models import GatewayModel, GatewayReplicaModel from dstack._internal.server.services.gateways.connection import GatewayConnection from dstack._internal.server.services.gateways.pool import gateway_connections_pool from dstack._internal.server.services.usage import ingest_usage_batch @@ -26,15 +26,30 @@ async def collect_gateway_usage() -> None: async with get_session_ctx() as session: rows = ( await session.execute( - select(GatewayReplicaModel.id, GatewayReplicaModel.ip_address).where( - GatewayReplicaModel.active == True + select( + GatewayReplicaModel.id, + GatewayReplicaModel.ip_address, + GatewayReplicaModel.gateway_id, + ).where(GatewayReplicaModel.active == True) + ) + ).all() + legacy_rows = ( + await session.execute( + select(GatewayModel.gateway_replica_id, GatewayModel.id).where( + GatewayModel.gateway_replica_id.is_not(None) ) ) ).all() - identities: dict[str, list[uuid.UUID]] = defaultdict(list) - for replica_id, address in rows: + legacy_parents: dict[uuid.UUID, set[uuid.UUID]] = defaultdict(set) + for replica_id, gateway_id in legacy_rows: + legacy_parents[replica_id].add(gateway_id) + identities: dict[str, list[tuple[uuid.UUID, uuid.UUID | None]]] = defaultdict(list) + for replica_id, address, gateway_id in rows: + parents = legacy_parents[replica_id] | ({gateway_id} if gateway_id else set()) if address is not None: - identities[address].append(replica_id) + # Retain ambiguous entries so no other replica at this address is selected. + for parent in parents or {None}: + identities[address].append((replica_id, parent)) semaphore = asyncio.Semaphore(8) async def collect(connection: GatewayConnection) -> None: @@ -45,7 +60,7 @@ async def collect(connection: GatewayConnection) -> None: async with semaphore: try: async with asyncio.timeout(COLLECTION_TIMEOUT): - await _collect_connection(connection, candidates[0]) + await _collect_connection(connection, *candidates[0]) except httpx.HTTPStatusError as exc: if exc.response.status_code not in (404, 405): logger.warning( @@ -62,7 +77,9 @@ async def collect(connection: GatewayConnection) -> None: ) -async def _collect_connection(connection: GatewayConnection, replica_id: uuid.UUID) -> None: +async def _collect_connection( + connection: GatewayConnection, replica_id: uuid.UUID, gateway_id: uuid.UUID | None +) -> None: for _ in range(MAX_PAGES): async with connection.client() as client: page = await client.fetch_usage_batches(PAGE_SIZE) @@ -72,7 +89,7 @@ async def _collect_connection(connection: GatewayConnection, replica_id: uuid.UU async with _ingestion_lock(): async with get_session_ctx() as session: for batch in page.batches: - await ingest_usage_batch(session, replica_id, page.collector_id, batch) + await ingest_usage_batch(session, replica_id, gateway_id, batch) # get_session_ctx commits and closes before leaving this block. ids = [batch.batch_id for batch in page.batches] async with connection.client() as client: diff --git a/src/dstack/_internal/server/migrations/versions/2026/11_16_1201_9a2e8f1f3c37_add_gateway_usage_batches.py b/src/dstack/_internal/server/migrations/versions/2026/11_16_1201_9a2e8f1f3c37_add_gateway_usage_batches.py index 4ef875c908..3d0afc8386 100644 --- a/src/dstack/_internal/server/migrations/versions/2026/11_16_1201_9a2e8f1f3c37_add_gateway_usage_batches.py +++ b/src/dstack/_internal/server/migrations/versions/2026/11_16_1201_9a2e8f1f3c37_add_gateway_usage_batches.py @@ -1,4 +1,4 @@ -"""add gateway usage batches +"""Add Gateway usage batches with historical replica/Gateway IDs Revision ID: 9a2e8f1f3c37 Revises: 6b5610ff36c1 @@ -20,24 +20,15 @@ def upgrade() -> None: - # ### commands auto generated by Alembic - please adjust! ### op.create_table( - "usage_collectors", - sa.Column("collector_id", sa.String(length=128), nullable=False), + "usage_batches", + sa.Column("id", sqlalchemy_utils.types.uuid.UUIDType(binary=False), nullable=False), sa.Column( "gateway_replica_id", sqlalchemy_utils.types.uuid.UUIDType(binary=False), nullable=False, ), - sa.PrimaryKeyConstraint("collector_id", name=op.f("pk_usage_collectors")), - sa.UniqueConstraint( - "gateway_replica_id", name=op.f("uq_usage_collectors_gateway_replica_id") - ), - ) - op.create_table( - "usage_batches", - sa.Column("id", sqlalchemy_utils.types.uuid.UUIDType(binary=False), nullable=False), - sa.Column("collector_id", sa.String(length=128), nullable=False), + sa.Column("gateway_id", sqlalchemy_utils.types.uuid.UUIDType(binary=False), nullable=True), sa.Column("batch_id", sa.String(length=128), nullable=False), sa.Column( "interval_start", dstack._internal.server.models.NaiveDateTime(), nullable=False @@ -45,21 +36,21 @@ def upgrade() -> None: sa.Column("interval_end", dstack._internal.server.models.NaiveDateTime(), nullable=False), sa.Column("received_at", dstack._internal.server.models.NaiveDateTime(), nullable=False), sa.Column("content", sa.Text(), nullable=False), - sa.ForeignKeyConstraint( - ["collector_id"], - ["usage_collectors.collector_id"], - name=op.f("fk_usage_batches_collector_id_usage_collectors"), - ), sa.PrimaryKeyConstraint("id", name=op.f("pk_usage_batches")), - sa.UniqueConstraint("collector_id", "batch_id", name="uq_usage_batches_collector_batch"), sa.UniqueConstraint( - "collector_id", "interval_start", name="uq_usage_batches_collector_minute" + "gateway_replica_id", "batch_id", name="uq_usage_batches_replica_batch" ), + sa.UniqueConstraint( + "gateway_replica_id", "interval_start", name="uq_usage_batches_replica_minute" + ), + ) + op.create_index( + "ix_usage_batches_gateway_interval", "usage_batches", ["gateway_id", "interval_start"] ) op.create_table( "usage_counters", sa.Column( - "receipt_id", sqlalchemy_utils.types.uuid.UUIDType(binary=False), nullable=False + "usage_baches_id", sqlalchemy_utils.types.uuid.UUIDType(binary=False), nullable=False ), sa.Column("consumer_subject_id", sa.String(length=128), nullable=False), sa.Column("service_id", sa.String(length=128), nullable=False), @@ -69,20 +60,21 @@ def upgrade() -> None: sa.Column("total_tokens", sa.BigInteger(), nullable=False), sa.Column("unknown_usage_attempts", sa.BigInteger(), nullable=False), sa.ForeignKeyConstraint( - ["receipt_id"], + ["usage_baches_id"], ["usage_batches.id"], - name=op.f("fk_usage_counters_receipt_id_usage_batches"), + name=op.f("fk_usage_counters_usage_baches_id_usage_batches"), ), sa.PrimaryKeyConstraint( - "receipt_id", "consumer_subject_id", "service_id", name=op.f("pk_usage_counters") + "usage_baches_id", "consumer_subject_id", "service_id", name=op.f("pk_usage_counters") ), ) - # ### end Alembic commands ### def downgrade() -> None: - # ### commands auto generated by Alembic - please adjust! ### + conn = op.get_bind() + if conn.scalar(sa.text("SELECT COUNT(*) FROM usage_batches")) or conn.scalar( + sa.text("SELECT COUNT(*) FROM usage_counters") + ): + raise ValueError("Populated usage downgrade requires a backup and reconciliation") op.drop_table("usage_counters") op.drop_table("usage_batches") - op.drop_table("usage_collectors") - # ### end Alembic commands ### diff --git a/src/dstack/_internal/server/models.py b/src/dstack/_internal/server/models.py index ce2f8d12c7..165270548b 100644 --- a/src/dstack/_internal/server/models.py +++ b/src/dstack/_internal/server/models.py @@ -1510,27 +1510,23 @@ class ProviderRefModel(BaseModel): __table_args__ = (Index("ix_provider_refs_project_id_created_at", project_id, created_at),) -class UsageCollectorModel(BaseModel): - """Durable identity binding; intentionally independent of live resource deletion.""" - - __tablename__ = "usage_collectors" - collector_id: Mapped[str] = mapped_column(String(128), primary_key=True) - gateway_replica_id: Mapped[uuid.UUID] = mapped_column(UUIDType(binary=False), unique=True) - - class UsageBatchModel(BaseModel): __tablename__ = "usage_batches" __table_args__ = ( - UniqueConstraint("collector_id", "batch_id", name="uq_usage_batches_collector_batch"), + UniqueConstraint("gateway_replica_id", "batch_id", name="uq_usage_batches_replica_batch"), UniqueConstraint( - "collector_id", "interval_start", name="uq_usage_batches_collector_minute" + "gateway_replica_id", "interval_start", name="uq_usage_batches_replica_minute" ), + Index("ix_usage_batches_gateway_interval", "gateway_id", "interval_start"), ) id: Mapped[uuid.UUID] = mapped_column( UUIDType(binary=False), primary_key=True, default=uuid.uuid4 ) - collector_id: Mapped[str] = mapped_column(ForeignKey("usage_collectors.collector_id")) + # Historical snapshots deliberately have no FK to deletable infrastructure. + gateway_replica_id: Mapped[uuid.UUID] = mapped_column(UUIDType(binary=False)) + gateway_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUIDType(binary=False), nullable=True) + """NULL only for unresolved legacy history; new ingestion requires a parent.""" batch_id: Mapped[str] = mapped_column(String(128)) interval_start: Mapped[datetime] = mapped_column(NaiveDateTime) interval_end: Mapped[datetime] = mapped_column(NaiveDateTime) @@ -1542,7 +1538,9 @@ class UsageBatchModel(BaseModel): class UsageCounterModel(BaseModel): __tablename__ = "usage_counters" - receipt_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("usage_batches.id"), primary_key=True) + usage_baches_id: Mapped[uuid.UUID] = mapped_column( + ForeignKey("usage_batches.id"), primary_key=True + ) consumer_subject_id: Mapped[str] = mapped_column(String(128), primary_key=True) service_id: Mapped[str] = mapped_column(String(128), primary_key=True) # Historical source IDs deliberately have no cascading foreign keys to users/runs. diff --git a/src/dstack/_internal/server/services/gateways/__init__.py b/src/dstack/_internal/server/services/gateways/__init__.py index 678649426d..0a68bd271f 100644 --- a/src/dstack/_internal/server/services/gateways/__init__.py +++ b/src/dstack/_internal/server/services/gateways/__init__.py @@ -158,7 +158,8 @@ def emit_gateway_replica_status_change_event( GATEWAY_CONNECT_ATTEMPTS = 30 GATEWAY_CONNECT_DELAY = 10 -GATEWAY_CONFIGURE_ATTEMPTS = 50 +# Allow slow first-boot Certbot/package downloads during this local experiment. +GATEWAY_CONFIGURE_ATTEMPTS = 300 GATEWAY_CONFIGURE_DELAY = 3 diff --git a/src/dstack/_internal/server/services/gateways/client.py b/src/dstack/_internal/server/services/gateways/client.py index 55b3ed9f13..bbc5354d74 100644 --- a/src/dstack/_internal/server/services/gateways/client.py +++ b/src/dstack/_internal/server/services/gateways/client.py @@ -18,6 +18,7 @@ from dstack._internal.proxy.gateway.schemas.services import ServiceListItem, ServiceListResponse from dstack._internal.proxy.gateway.schemas.stats import ServiceStats from dstack._internal.proxy.lib.schemas.usage import ( + LegacyUsageBatchPage, UsageAckRequest, UsageAckResponse, UsageBatchPage, @@ -254,7 +255,13 @@ async def fetch_usage_batches(self, limit: int = 100) -> UsageBatchPage: self._url("/api/usage/batches"), params={"limit": limit}, timeout=10 ) response.raise_for_status() - return UsageBatchPage.model_validate(response.json()) + payload = response.json() + if isinstance(payload, dict) and payload.get("schema_version", 1) == 1: + legacy = LegacyUsageBatchPage.model_validate(payload) + return UsageBatchPage.model_validate( + legacy.model_dump(exclude={"schema_version", "collector_id"}) + ) + return UsageBatchPage.model_validate(payload) async def acknowledge_usage(self, batch_ids: list[str]) -> UsageAckResponse: payload = UsageAckRequest(batch_ids=batch_ids) diff --git a/src/dstack/_internal/server/services/usage.py b/src/dstack/_internal/server/services/usage.py index 5cdc996ab7..1faab76ff0 100644 --- a/src/dstack/_internal/server/services/usage.py +++ b/src/dstack/_internal/server/services/usage.py @@ -10,7 +10,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from dstack._internal.proxy.lib.schemas.usage import UsageBatch -from dstack._internal.server.models import UsageBatchModel, UsageCollectorModel, UsageCounterModel +from dstack._internal.server.models import UsageBatchModel, UsageCounterModel class UsageConflict(ValueError): @@ -25,12 +25,13 @@ class ReceiptResult: async def ingest_usage_batch( - session: AsyncSession, gateway_replica_id: uuid.UUID, collector_id: str, batch: UsageBatch + session: AsyncSession, + gateway_replica_id: uuid.UUID, + gateway_id: uuid.UUID | None, + batch: UsageBatch, ) -> ReceiptResult: # Validate even callers that constructed an unchecked model_copy(). batch = UsageBatch.model_validate(batch.model_dump()) - if not collector_id or len(collector_id) > 128: - raise ValueError("Invalid collector identity") content = batch.model_dump(mode="json") content["entries"].sort(key=lambda entry: (entry["consumer_subject_id"], entry["service_id"])) canonical = json.dumps(content, sort_keys=True, separators=(",", ":")) @@ -48,47 +49,44 @@ async def ingest_usage_batch( dialect_insert = ( pg_insert if session.get_bind().dialect.name == "postgresql" else sqlite_insert ) - # INSERT first avoids a read-to-write upgrade and handles cross-process races in Postgres. - await session.execute( - dialect_insert(UsageCollectorModel) - .values(collector_id=collector_id, gateway_replica_id=gateway_replica_id) - .on_conflict_do_nothing() - ) - owner = await session.scalar( - select(UsageCollectorModel.gateway_replica_id).where( - UsageCollectorModel.collector_id == collector_id - ) - ) - if owner != gateway_replica_id: - raise UsageConflict("Collector identity reset or moved to another Gateway") - - receipt_id = uuid.uuid4() - created = await session.scalar( - dialect_insert(UsageBatchModel) - .values( - id=receipt_id, - collector_id=collector_id, - batch_id=batch.batch_id, - interval_start=batch.interval_start, - interval_end=batch.interval_end, - content=canonical, + batch_record_id = uuid.uuid4() + created = None + if gateway_id is not None: + # INSERT first avoids SQLite read-to-write upgrades and serializes PG conflicts. + created = await session.scalar( + dialect_insert(UsageBatchModel) + .values( + id=batch_record_id, + gateway_replica_id=gateway_replica_id, + gateway_id=gateway_id, + batch_id=batch.batch_id, + interval_start=batch.interval_start, + interval_end=batch.interval_end, + content=canonical, + ) + .on_conflict_do_nothing() + .returning(UsageBatchModel.id) ) - .on_conflict_do_nothing() - .returning(UsageBatchModel.id) - ) if created is None: - existing = await session.scalar( - select(UsageBatchModel.content).where( - UsageBatchModel.collector_id == collector_id, - UsageBatchModel.batch_id == batch.batch_id, + existing = ( + await session.execute( + select(UsageBatchModel.content, UsageBatchModel.gateway_id).where( + UsageBatchModel.gateway_replica_id == gateway_replica_id, + UsageBatchModel.batch_id == batch.batch_id, + ) ) - ) - if existing != canonical: - raise UsageConflict("Conflicting batch content or duplicate minute under a new ID") + ).one_or_none() + if existing is None or existing.content != canonical: + raise UsageConflict("Missing source, conflicting content or duplicate minute") + if gateway_id is not None and existing.gateway_id not in (None, gateway_id): + raise UsageConflict("Historical Gateway identity cannot change") return ReceiptResult(batch.batch_id, inserted=False) if batch.entries: await session.execute( insert(UsageCounterModel), - [{"receipt_id": receipt_id, **entry.model_dump()} for entry in batch.entries], + [ + {"usage_baches_id": batch_record_id, **entry.model_dump()} + for entry in batch.entries + ], ) return ReceiptResult(batch.batch_id, inserted=True) diff --git a/src/tests/_internal/proxy/gateway/metering/receiver.py b/src/tests/_internal/proxy/gateway/metering/receiver.py index 0dbe251d8d..d9781847ac 100644 --- a/src/tests/_internal/proxy/gateway/metering/receiver.py +++ b/src/tests/_internal/proxy/gateway/metering/receiver.py @@ -30,21 +30,46 @@ class ReceiptReport: class MockReceiver: - def __init__(self, url: str, ledger: Path, client: httpx.AsyncClient | None = None): - self.client = client or httpx.AsyncClient(base_url=url, timeout=10) - self._owns_client = client is None + def __init__( + self, + url: str, + ledger: Path, + client: httpx.AsyncClient | None = None, + *, + gateway_replica_id: str, + gateway_id: str, + ): + if not gateway_replica_id or not gateway_id: + raise ValueError("Test receiver requires explicit source identities") + self.gateway_replica_id = gateway_replica_id + self.gateway_id = gateway_id self.db = sqlite3.connect(ledger) + tables = { + row[0] for row in self.db.execute("SELECT name FROM sqlite_master WHERE type='table'") + } + columns = {row[1] for row in self.db.execute("PRAGMA table_info(receipts)")} + entry_columns = {row[1] for row in self.db.execute("PRAGMA table_info(entries)")} + if ( + "metadata" in tables + or ("receipts" in tables and not {"gateway_replica_id", "gateway_id"} <= columns) + or ("entries" in tables and "gateway_replica_id" not in entry_columns) + ): + self.db.close() + raise ValueError( + "Unsupported legacy receiver ledger; convert explicitly or use a new test ledger" + ) self.db.executescript(""" - CREATE TABLE IF NOT EXISTS metadata (collector_id TEXT PRIMARY KEY); CREATE TABLE IF NOT EXISTS receipts ( - collector_id TEXT, batch_id TEXT, content TEXT NOT NULL, - PRIMARY KEY (collector_id,batch_id)); + gateway_replica_id TEXT, batch_id TEXT, gateway_id TEXT NOT NULL, content TEXT NOT NULL, + PRIMARY KEY (gateway_replica_id,batch_id)); CREATE TABLE IF NOT EXISTS entries ( - collector_id TEXT, batch_id TEXT, subject TEXT, service TEXT, + gateway_replica_id TEXT, batch_id TEXT, subject TEXT, service TEXT, prompt_tokens INTEGER, cached_prompt_tokens INTEGER, completion_tokens INTEGER, total_tokens INTEGER, unknown_usage_attempts INTEGER, - PRIMARY KEY (collector_id,batch_id,subject,service)); + PRIMARY KEY (gateway_replica_id,batch_id,subject,service)); """) + self.client = client or httpx.AsyncClient(base_url=url, timeout=10) + self._owns_client = client is None async def collect_once(self, limit: int = 100, acknowledge: bool = True) -> ReceiptReport: response = await self.client.get("/api/usage/batches", params={"limit": limit}) @@ -60,32 +85,28 @@ async def collect_once(self, limit: int = 100, acknowledge: bool = True) -> Rece def commit_page(self, page: UsageBatchPage) -> tuple[list[str], list[str]]: new, replay = [], [] with self.db: - bound = self.db.execute("SELECT collector_id FROM metadata").fetchone() - if bound and bound[0] != page.collector_id: - raise ValueError("Collector identity changed; reconcile") - self.db.execute("INSERT OR IGNORE INTO metadata VALUES (?)", (page.collector_id,)) for batch in page.batches: content = json.dumps( batch.model_dump(mode="json"), sort_keys=True, separators=(",", ":") ) existing = self.db.execute( - "SELECT content FROM receipts WHERE collector_id=? AND batch_id=?", - (page.collector_id, batch.batch_id), + "SELECT content,gateway_id FROM receipts WHERE gateway_replica_id=? AND batch_id=?", + (self.gateway_replica_id, batch.batch_id), ).fetchone() if existing: - if existing[0] != content: + if existing != (content, self.gateway_id): raise ValueError("Same batch ID has conflicting content") replay.append(batch.batch_id) continue self.db.execute( - "INSERT INTO receipts VALUES (?,?,?)", - (page.collector_id, batch.batch_id, content), + "INSERT INTO receipts VALUES (?,?,?,?)", + (self.gateway_replica_id, batch.batch_id, self.gateway_id, content), ) for entry in batch.entries: self.db.execute( "INSERT INTO entries VALUES (?,?,?,?,?,?,?,?,?)", ( - page.collector_id, + self.gateway_replica_id, batch.batch_id, entry.consumer_subject_id, entry.service_id, @@ -105,7 +126,11 @@ async def acknowledge_committed(self, batch_ids: list[str]) -> UsageAckResponse: def receipt_ids(self) -> list[str]: return [ - row[0] for row in self.db.execute("SELECT batch_id FROM receipts ORDER BY batch_id") + row[0] + for row in self.db.execute( + "SELECT batch_id FROM receipts WHERE gateway_replica_id=? ORDER BY batch_id", + (self.gateway_replica_id,), + ) ] def totals(self) -> dict[tuple[str, str], dict[str, int]]: @@ -123,7 +148,12 @@ async def close(self) -> None: async def _run(args) -> None: - receiver = MockReceiver(args.url, Path(args.ledger)) + receiver = MockReceiver( + args.url, + Path(args.ledger), + gateway_replica_id=args.gateway_replica_id, + gateway_id=args.gateway_id, + ) try: while True: report = await receiver.collect_once(args.limit, acknowledge=not args.no_ack) @@ -141,6 +171,8 @@ def main() -> None: "--url", required=True, help="Private Gateway management URL / local SSH forward" ) parser.add_argument("--ledger", required=True) + parser.add_argument("--gateway-replica-id", required=True) + parser.add_argument("--gateway-id", required=True) parser.add_argument("--limit", type=int, default=100) parser.add_argument("--no-ack", action="store_true") parser.add_argument("--watch", action="store_true") diff --git a/src/tests/_internal/proxy/gateway/metering/test_helpers.py b/src/tests/_internal/proxy/gateway/metering/test_helpers.py index e826a59f94..eb55515edb 100644 --- a/src/tests/_internal/proxy/gateway/metering/test_helpers.py +++ b/src/tests/_internal/proxy/gateway/metering/test_helpers.py @@ -1,3 +1,5 @@ +import sqlite3 + import httpx import pytest @@ -10,7 +12,6 @@ def page(batch_id="a", completion=3): return UsageBatchPage.model_validate( { - "collector_id": "collector", "batches": [ { "batch_id": batch_id, @@ -36,7 +37,9 @@ def page(batch_id="a", completion=3): @pytest.mark.asyncio async def test_receiver_commits_once_reopens_and_rejects_conflicting_content(tmp_path): ledger = tmp_path / "receiver.sqlite" - receiver = MockReceiver("http://unused", ledger) + receiver = MockReceiver( + "http://unused", ledger, gateway_replica_id="replica-a", gateway_id="gateway" + ) assert receiver.commit_page(page()) == (["a"], []) assert receiver.commit_page(page()) == ([], ["a"]) with pytest.raises(ValueError, match="content"): @@ -49,7 +52,9 @@ async def test_receiver_commits_once_reopens_and_rejects_conflicting_content(tmp unknown_usage_attempts=0, ) await receiver.close() - receiver = MockReceiver("http://unused", ledger) + receiver = MockReceiver( + "http://unused", ledger, gateway_replica_id="replica-a", gateway_id="gateway" + ) assert receiver.commit_page(page()) == ([], ["a"]) assert receiver.totals()[("u", "s")]["total_tokens"] == 23 with pytest.raises(ValueError, match="committed"): @@ -59,11 +64,14 @@ async def test_receiver_commits_once_reopens_and_rejects_conflicting_content(tmp @pytest.mark.asyncio async def test_receiver_page_conflict_rolls_back_other_new_batches(tmp_path): - receiver = MockReceiver("http://unused", tmp_path / "receiver.sqlite") - receiver.commit_page(page()) - mixed = UsageBatchPage( - collector_id="collector", batches=[page("new").batches[0], page(completion=4).batches[0]] + receiver = MockReceiver( + "http://unused", + tmp_path / "receiver.sqlite", + gateway_replica_id="replica-a", + gateway_id="gateway", ) + receiver.commit_page(page()) + mixed = UsageBatchPage(batches=[page("new").batches[0], page(completion=4).batches[0]]) with pytest.raises(ValueError): receiver.commit_page(mixed) assert receiver.receipt_ids() == ["a"] @@ -109,3 +117,37 @@ async def test_separate_gateway_uses_real_model_and_management_routes(tmp_path): finally: await driver.close() await harness.stop() + + +@pytest.mark.asyncio +async def test_receiver_shared_ledger_scopes_replay_and_ack_to_replica(tmp_path): + ledger = tmp_path / "receiver.sqlite" + first = MockReceiver("http://one", ledger, gateway_replica_id="r1", gateway_id="g") + second = MockReceiver("http://two", ledger, gateway_replica_id="r2", gateway_id="g") + try: + first.commit_page(page("only-first")) + with pytest.raises(ValueError, match="committed"): + await second.acknowledge_committed(["only-first"]) + first.commit_page(page("shared")) + second.commit_page(page("shared", completion=4)) + assert second.commit_page(page("shared", completion=4)) == ([], ["shared"]) + assert first.receipt_ids() == ["only-first", "shared"] + assert second.receipt_ids() == ["shared"] + assert first.totals()[("u", "s")]["completion_tokens"] == 10 + assert first.db.execute( + "SELECT gateway_id, COUNT(*) FROM receipts GROUP BY gateway_id" + ).fetchall() == [("g", 3)] + finally: + await first.close() + await second.close() + + +def test_receiver_refuses_legacy_ledger_without_modifying_it(tmp_path): + ledger = tmp_path / "old.sqlite" + with sqlite3.connect(ledger) as db: + db.execute("CREATE TABLE metadata (collector_id TEXT PRIMARY KEY)") + db.execute("INSERT INTO metadata VALUES ('old')") + before = ledger.read_bytes() + with pytest.raises(ValueError, match="legacy"): + MockReceiver("http://unused", ledger, gateway_replica_id="r", gateway_id="g") + assert ledger.read_bytes() == before diff --git a/src/tests/_internal/proxy/gateway/metering/test_scenarios.py b/src/tests/_internal/proxy/gateway/metering/test_scenarios.py index 78ea090724..50b769e410 100644 --- a/src/tests/_internal/proxy/gateway/metering/test_scenarios.py +++ b/src/tests/_internal/proxy/gateway/metering/test_scenarios.py @@ -46,7 +46,12 @@ async def close_minute(h): async def two_intervals(h): driver = TrafficDriver(h.gateway_url, artifact_dir=h.state) - receiver = MockReceiver(h.gateway_url, h.state / "receiver.sqlite") + receiver = MockReceiver( + h.gateway_url, + h.state / "receiver.sqlite", + gateway_replica_id="replica-a", + gateway_id="gateway-a", + ) evidence: dict = {"started_at": datetime.now(timezone.utc).isoformat()} try: for i in range(10): @@ -97,7 +102,12 @@ async def test_two_intervals_and_ack(harness): async def test_selective_ack_during_traffic(harness): h = harness d = TrafficDriver(h.gateway_url, artifact_dir=h.state) - r = MockReceiver(h.gateway_url, h.state / "receiver.sqlite") + r = MockReceiver( + h.gateway_url, + h.state / "receiver.sqlite", + gateway_replica_id="replica-a", + gateway_id="gateway-a", + ) try: await send(h, d, "P") await close_minute(h) @@ -246,20 +256,34 @@ async def test_receiver_outage_and_retry(harness): pending = (await h.batches())["batches"] assert len(pending) == 2 async with httpx.AsyncClient(base_url=h.gateway_url, transport=LostReply("GET")) as client: - r = MockReceiver(h.gateway_url, ledger, client) + r = MockReceiver( + h.gateway_url, + ledger, + client, + gateway_replica_id="replica-a", + gateway_id="gateway-a", + ) with pytest.raises(httpx.ReadError): await r.collect_once(1) assert r.receipt_ids() == [] and (await h.batches())["batches"] == pending first = await r.collect_once(1, acknowledge=False) await r.close() - r = MockReceiver(h.gateway_url, ledger) + r = MockReceiver( + h.gateway_url, ledger, gateway_replica_id="replica-a", gateway_id="gateway-a" + ) replay = await r.collect_once(1, acknowledge=False) assert replay.replayed_ids == first.committed_ids await r.close() async with httpx.AsyncClient( base_url=h.gateway_url, transport=LostReply("POST") ) as client: - r = MockReceiver(h.gateway_url, ledger, client) + r = MockReceiver( + h.gateway_url, + ledger, + client, + gateway_replica_id="replica-a", + gateway_id="gateway-a", + ) with pytest.raises(httpx.ReadError): await r.acknowledge_committed(first.committed_ids) assert len((await h.batches())["batches"]) == 1 @@ -277,7 +301,12 @@ async def test_receiver_outage_and_retry(harness): async def test_gateway_restart_persistence(harness, kill): h = harness d = TrafficDriver(h.gateway_url, artifact_dir=h.state) - r = MockReceiver(h.gateway_url, h.state / "receiver.sqlite") + r = MockReceiver( + h.gateway_url, + h.state / "receiver.sqlite", + gateway_replica_id="replica-a", + gateway_id="gateway-a", + ) try: await send(h, d, "P") await close_minute(h) @@ -291,7 +320,12 @@ async def test_gateway_restart_persistence(harness, kill): await h.restart(kill) assert (await h.batches()) == page d = TrafficDriver(h.gateway_url, artifact_dir=h.state) - r = MockReceiver(h.gateway_url, h.state / "receiver.sqlite") + r = MockReceiver( + h.gateway_url, + h.state / "receiver.sqlite", + gateway_replica_id="replica-a", + gateway_id="gateway-a", + ) await r.collect_once() await send(h, d, "R", case="C") await close_minute(h) @@ -335,3 +369,53 @@ async def test_two_intervals_real_minutes(tmp_path): await two_intervals(h) finally: await h.stop() + + +@pytest.mark.asyncio +async def test_subject_service_totals_across_two_gateway_replicas(tmp_path): + # Separate processes exercise source attribution through actual HTTP endpoints, + # not just synthetic pages passed straight into the receiver. + gateways = [Harness(tmp_path / f"gateway-{i}") for i in range(2)] + drivers, receivers = [], [] + try: + for i, h in enumerate(gateways): + await h.start() + driver = TrafficDriver(h.gateway_url) + drivers.append(driver) + receivers.append( + MockReceiver( + h.gateway_url, + tmp_path / "shared.sqlite", + gateway_replica_id=f"replica-{i}", + gateway_id="logical-gateway", + ) + ) + await send(h, driver, f"request-{i}", case="A") + await h.advance_clock() + page = await h.batches() + assert page["schema_version"] == 2 and "collector_id" not in page + await receivers[-1].collect_once() + assert not (await h.batches())["batches"] + assert receivers[0].totals()[PAIR] == dict( + prompt_tokens=40, + cached_prompt_tokens=10, + completion_tokens=6, + total_tokens=46, + unknown_usage_attempts=0, + ) + rows = ( + receivers[0] + .db.execute( + "SELECT gateway_id,COUNT(DISTINCT gateway_replica_id),COUNT(*) " + "FROM receipts GROUP BY gateway_id" + ) + .fetchall() + ) + assert rows == [("logical-gateway", 2, 2)] + finally: + for driver in drivers: + await driver.close() + for receiver in receivers: + await receiver.close() + for h in gateways: + await h.stop() diff --git a/src/tests/_internal/proxy/gateway/services/test_metering_store.py b/src/tests/_internal/proxy/gateway/services/test_metering_store.py index edab714ae2..7bf7732968 100644 --- a/src/tests/_internal/proxy/gateway/services/test_metering_store.py +++ b/src/tests/_internal/proxy/gateway/services/test_metering_store.py @@ -1,4 +1,5 @@ import asyncio +import json import threading from datetime import datetime, timedelta, timezone @@ -11,7 +12,6 @@ def checkpoint(): start = datetime(2026, 11, 16, 10, tzinfo=timezone.utc) return UsageCheckpoint( - collector_id="collector", active_batch=UsageBatch( batch_id="a", interval_start=start, interval_end=start + timedelta(seconds=60) ), @@ -99,3 +99,89 @@ def delayed(state): assert saved is not None assert saved.active_batch.batch_id == "b" store.close() + + +@pytest.mark.asyncio +async def test_v1_conversion_preserves_all_batches_and_survives_marker_failure( + tmp_path, monkeypatch +): + path = tmp_path / "usage.json" + marker = path.with_suffix(".json.initialized") + data = checkpoint().model_dump(mode="json") + old_batch = dict( + data["active_batch"], + batch_id="pending", + interval_start="2026-11-16T09:59:00Z", + interval_end="2026-11-16T10:00:00Z", + entries=[ + dict( + consumer_subject_id="u", + service_id="s", + prompt_tokens=20, + cached_prompt_tokens=5, + completion_tokens=3, + total_tokens=23, + unknown_usage_attempts=0, + ) + ], + ) + data.update(schema_version=1, collector_id="a" * 32, pending_batches=[old_batch]) + path.write_text(json.dumps(data)) + marker.write_text("a" * 32) + store = MeteringStore(path) + original = store._atomic_write + + def fail_marker(target, content): + if target == marker: + raise OSError("marker write interrupted") + original(target, content) + + monkeypatch.setattr(store, "_atomic_write", fail_marker) + try: + with pytest.raises(OSError, match="interrupted"): + store.load() + saved = json.loads(path.read_text()) + assert saved["schema_version"] == 2 and "collector_id" not in saved + finally: + store.close() + resumed = MeteringStore(path) + try: + state = resumed.load() + assert state is not None + assert state.schema_version == 2 + assert state.active_batch.batch_id == "a" + assert state.pending_batches[0].batch_id == "pending" + assert state.pending_batches[0].entries[0].total_tokens == 23 + assert marker.read_text() == "usage-state-v2" + assert resumed.load() == state + assert set(json.loads(path.read_text())) == { + "schema_version", + "active_batch", + "pending_batches", + } + finally: + resumed.close() + + +@pytest.mark.parametrize( + "version,marker_value", + [(1, "b" * 32), (1, "usage-state-v2"), (2, "bad marker"), (3, "a" * 32)], +) +def test_legacy_mismatch_and_unsupported_state_do_not_modify_file(tmp_path, version, marker_value): + path = tmp_path / "usage.json" + data = checkpoint().model_dump(mode="json") + data["schema_version"] = version + if version == 1: + data["collector_id"] = "a" * 32 + path.write_text(json.dumps(data)) + marker = path.with_suffix(".json.initialized") + marker.write_text(marker_value) + before = path.read_bytes() + store = MeteringStore(path) + try: + with pytest.raises(ValueError): + store.load() + assert path.read_bytes() == before + assert marker.read_text() == marker_value + finally: + store.close() diff --git a/src/tests/_internal/proxy/lib/test_usage.py b/src/tests/_internal/proxy/lib/test_usage.py index bce76a57f9..19458f3ed5 100644 --- a/src/tests/_internal/proxy/lib/test_usage.py +++ b/src/tests/_internal/proxy/lib/test_usage.py @@ -96,7 +96,7 @@ def test_checkpoint_rejects_duplicate_keys_and_ids(self): with pytest.raises(ValidationError): UsageBatch.model_validate(batch.model_dump() | {"entries": [entry, entry]}) with pytest.raises(ValidationError): - UsageCheckpoint(collector_id="c", active_batch=batch, pending_batches=[batch]) + UsageCheckpoint(active_batch=batch, pending_batches=[batch]) with pytest.raises(ValidationError): UsageBatch.model_validate( batch.model_dump() | {"interval_end": start + timedelta(seconds=30)} diff --git a/src/tests/_internal/server/background/scheduled_tasks/test_usage.py b/src/tests/_internal/server/background/scheduled_tasks/test_usage.py index 788e9deb5e..73be0e3b4d 100644 --- a/src/tests/_internal/server/background/scheduled_tasks/test_usage.py +++ b/src/tests/_internal/server/background/scheduled_tasks/test_usage.py @@ -1,6 +1,5 @@ import asyncio import contextvars -import uuid from contextlib import asynccontextmanager from unittest.mock import AsyncMock @@ -10,9 +9,15 @@ from dstack._internal.proxy.lib.schemas.usage import UsageAckResponse, UsageBatchPage from dstack._internal.server.background.scheduled_tasks import usage -from dstack._internal.server.models import UsageBatchModel, UsageCounterModel +from dstack._internal.server.models import ( + BackendModel, + GatewayModel, + UsageBatchModel, + UsageCounterModel, +) from dstack._internal.server.testing.common import ( create_backend, + create_gateway, create_gateway_replica, create_project, create_user, @@ -37,15 +42,16 @@ def assert_no_db_connection(self): async def fetch_usage_batches(self, limit=100): self.assert_no_db_connection() self.fetches += 1 - return UsageBatchPage( - collector_id="collector", batches=self.items[:limit], has_more=len(self.items) > limit - ) + return UsageBatchPage(batches=self.items[:limit], has_more=len(self.items) > limit) async def acknowledge_usage(self, ids): self.assert_no_db_connection() - async with self.db.get_session() as session: - committed = set(await session.scalars(select(UsageBatchModel.batch_id))) - assert set(ids) <= committed + # The in-memory SQLite fixture shares one physical connection. Serialize this + # test-only observation so closing it cannot roll back another collector's work. + async with usage._ingestion_lock(): + async with self.db.get_session() as session: + committed = set(await session.scalars(select(UsageBatchModel.batch_id))) + assert set(ids) <= committed self.acks.append(ids) self.items = [b for b in self.items if b.batch_id not in ids] if self.lose_ack: @@ -54,7 +60,7 @@ async def acknowledge_usage(self, ids): return UsageAckResponse(acknowledged_batch_ids=ids) -def setup(monkeypatch, db, client): +def setup(monkeypatch, db, client, ip_address="1.1.1.1"): original = usage.get_session_ctx @asynccontextmanager @@ -73,7 +79,7 @@ async def connection_client(): yield client connection = type( - "Connection", (), {"ip_address": "1.1.1.1", "client": staticmethod(connection_client)} + "Connection", (), {"ip_address": ip_address, "client": staticmethod(connection_client)} )() monkeypatch.setattr( usage.gateway_connections_pool, "all", AsyncMock(return_value=[connection]) @@ -85,7 +91,8 @@ async def registered(session): user = await create_user(session) project = await create_project(session, owner=user) backend = await create_backend(session, project.id) - return await create_gateway_replica(session, backend) + gateway = await create_gateway(session, project.id, backend.id) + return await create_gateway_replica(session, backend, gateway_id=gateway.id) @pytest.mark.asyncio @@ -123,11 +130,11 @@ async def fail(*args, **kwargs): @pytest.mark.asyncio async def test_conflict_never_acknowledged(session, test_db, monkeypatch): - await registered(session) - client = Client(test_db, [batch()]) + replica = await registered(session) + client = Client(test_db, [batch(tokens=4)]) setup(monkeypatch, test_db, client) async with test_db.get_session() as s: - await usage.ingest_usage_batch(s, uuid.uuid4(), "collector", batch()) + await usage.ingest_usage_batch(s, replica.id, replica.gateway_id, batch()) await s.commit() await usage.collect_gateway_usage() assert not client.acks and client.items @@ -165,3 +172,46 @@ async def unavailable(limit=100): monkeypatch.setattr(client, "fetch_usage_batches", unavailable) await usage.collect_gateway_usage() assert not client.acks + + +@pytest.mark.asyncio +async def test_multiple_replicas_and_legacy_parent(session, test_db, monkeypatch): + first = await registered(session) + backend = await session.get(BackendModel, first.backend_id) + second = await create_gateway_replica( + session, backend, gateway_id=first.gateway_id, ip_address="2.2.2.2" + ) + legacy = await create_gateway_replica(session, backend, ip_address="3.3.3.3") + parent = await session.get(GatewayModel, first.gateway_id) + parent.gateway_replica_id = legacy.id + await session.commit() + clients, connections = [], [] + for replica in (first, second, legacy): + assert replica.ip_address is not None + client = Client(test_db, [batch()]) + connection = setup(monkeypatch, test_db, client, ip_address=replica.ip_address) + clients.append(client) + connections.append(connection) + monkeypatch.setattr(usage.gateway_connections_pool, "all", AsyncMock(return_value=connections)) + await usage.collect_gateway_usage() + async with test_db.get_session() as s: + rows = (await s.scalars(select(UsageBatchModel))).all() + assert {row.gateway_replica_id for row in rows} == {first.id, second.id, legacy.id} + assert {row.gateway_id for row in rows} == {first.gateway_id} + assert all(client.acks == [["batch-1"]] for client in clients) + + +@pytest.mark.asyncio +async def test_unbound_or_ambiguous_source_is_not_acknowledged(session, test_db, monkeypatch): + replica = await registered(session) + replica.gateway_id = None + await session.commit() + client = Client(test_db, [batch()]) + setup(monkeypatch, test_db, client) + await usage.collect_gateway_usage() + assert not client.acks + backend = await session.get(BackendModel, replica.backend_id) + await create_gateway_replica(session, backend, ip_address=replica.ip_address) + before = client.fetches + await usage.collect_gateway_usage() + assert client.fetches == before and not client.acks diff --git a/src/tests/_internal/server/services/gateways/test_usage_client.py b/src/tests/_internal/server/services/gateways/test_usage_client.py index a9e96e8421..0da0e5e721 100644 --- a/src/tests/_internal/server/services/gateways/test_usage_client.py +++ b/src/tests/_internal/server/services/gateways/test_usage_client.py @@ -6,7 +6,8 @@ @pytest.mark.asyncio -async def test_usage_client_contract(): +@pytest.mark.parametrize("version", [1, 2]) +async def test_usage_client_contract(version): seen = [] def response(request): @@ -14,7 +15,13 @@ def response(request): if request.method == "GET": assert request.url.path == "/api/usage/batches" and request.url.params["limit"] == "2" return httpx.Response( - 200, json={"collector_id": "c", "batches": [], "has_more": False} + 200, + json={ + "schema_version": version, + "batches": [], + "has_more": False, + **({"collector_id": "c"} if version == 1 else {}), + }, ) assert request.url.path == "/api/usage/batches/ack" return httpx.Response(200, json={"acknowledged_batch_ids": ["b"]}) @@ -23,7 +30,9 @@ def response(request): await client._client.aclose() async with AsyncClientWrapper(transport=httpx.MockTransport(response)) as http: client._client = http - assert (await client.fetch_usage_batches(2)).collector_id == "c" + page = await client.fetch_usage_batches(2) + assert page.schema_version == 2 + assert "collector_id" not in page.model_dump() assert (await client.acknowledge_usage(["b"])).acknowledged_batch_ids == ["b"] assert all(r.extensions["timeout"]["read"] == 10 for r in seen) @@ -42,11 +51,14 @@ async def test_usage_client_http_errors(code): @pytest.mark.asyncio -async def test_usage_client_rejects_malformed_data(): +@pytest.mark.parametrize( + "payload", [{}, {"schema_version": 3}, {"schema_version": 2, "collector_id": "spoofed"}] +) +async def test_usage_client_rejects_malformed_data(payload): client = GatewayClient(port=1) await client._client.aclose() async with AsyncClientWrapper( - transport=httpx.MockTransport(lambda r: httpx.Response(200, json={})) + transport=httpx.MockTransport(lambda r: httpx.Response(200, json=payload)) ) as http: client._client = http with pytest.raises(ValidationError): diff --git a/src/tests/_internal/server/services/test_usage.py b/src/tests/_internal/server/services/test_usage.py index 1193963dd8..d4e5d69a1b 100644 --- a/src/tests/_internal/server/services/test_usage.py +++ b/src/tests/_internal/server/services/test_usage.py @@ -6,7 +6,7 @@ from sqlalchemy import func, select from dstack._internal.proxy.lib.schemas.usage import UsageBatch, UsageEntry -from dstack._internal.server.models import UsageBatchModel, UsageCollectorModel, UsageCounterModel +from dstack._internal.server.models import UsageBatchModel, UsageCounterModel from dstack._internal.server.services.usage import UsageConflict, ingest_usage_batch @@ -33,16 +33,17 @@ def batch(batch_id="batch-1", offset=0, tokens=3): @pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) async def test_commit_replay_conflict_and_historical_ids(test_db): gateway = uuid.uuid4() + parent = uuid.uuid4() item = batch(tokens=2**40) async with test_db.get_session() as session: - assert (await ingest_usage_batch(session, gateway, "collector", item)).inserted + assert (await ingest_usage_batch(session, gateway, parent, item)).inserted await session.commit() async with test_db.get_session() as session: - assert not (await ingest_usage_batch(session, gateway, "collector", item)).inserted + assert not (await ingest_usage_batch(session, gateway, parent, item)).inserted await session.commit() async with test_db.get_session() as session: with pytest.raises(UsageConflict): - await ingest_usage_batch(session, gateway, "collector", batch(tokens=4)) + await ingest_usage_batch(session, gateway, parent, batch(tokens=4)) await session.rollback() row = (await session.scalars(select(UsageCounterModel))).one() assert row.completion_tokens == 2**40 @@ -55,10 +56,10 @@ async def test_commit_replay_conflict_and_historical_ids(test_db): @pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) async def test_rollback_leaves_no_receipt_or_entries(test_db): async with test_db.get_session() as session: - await ingest_usage_batch(session, uuid.uuid4(), "collector", batch()) + await ingest_usage_batch(session, uuid.uuid4(), uuid.uuid4(), batch()) await session.rollback() async with test_db.get_session() as session: - for model in [UsageCollectorModel, UsageBatchModel, UsageCounterModel]: + for model in [UsageBatchModel, UsageCounterModel]: assert await session.scalar(select(func.count()).select_from(model)) == 0 @@ -66,31 +67,62 @@ async def test_rollback_leaves_no_receipt_or_entries(test_db): @pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) async def test_identity_and_interval_conflicts(test_db): gateway = uuid.uuid4() + parent = uuid.uuid4() async with test_db.get_session() as session: - await ingest_usage_batch(session, gateway, "collector", batch()) + await ingest_usage_batch(session, gateway, parent, batch()) await session.commit() - for g, c, b in [ - (uuid.uuid4(), "collector", batch()), - (gateway, "reset", batch()), - (gateway, "collector", batch("duplicate-minute")), - ]: + for parent_id, item in [(uuid.uuid4(), batch()), (parent, batch("duplicate-minute"))]: async with test_db.get_session() as session: with pytest.raises(UsageConflict): - await ingest_usage_batch(session, g, c, b) + await ingest_usage_batch(session, gateway, parent_id, item) await session.rollback() + # An independent replica may legitimately use the same batch ID and minute. + async with test_db.get_session() as session: + assert (await ingest_usage_batch(session, uuid.uuid4(), parent, batch())).inserted + await session.commit() @pytest.mark.asyncio @pytest.mark.parametrize("test_db", ["postgres"], indirect=True) async def test_concurrent_pollers_commit_once(test_db): gateway = uuid.uuid4() + parent = uuid.uuid4() async def ingest(): async with test_db.get_session() as session: - result = await ingest_usage_batch(session, gateway, "collector", batch()) + result = await ingest_usage_batch(session, gateway, parent, batch()) await session.commit() return result.inserted assert sorted(await asyncio.gather(ingest(), ingest())) == [False, True] async with test_db.get_session() as session: assert await session.scalar(select(func.count()).select_from(UsageCounterModel)) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) +async def test_history_snapshot_missing_parent_and_renamed_link(test_db): + replica, parent = uuid.uuid4(), uuid.uuid4() + async with test_db.get_session() as session: + await ingest_usage_batch(session, replica, parent, batch()) + await session.commit() + async with test_db.get_session() as session: + assert not (await ingest_usage_batch(session, replica, None, batch())).inserted + row = (await session.scalars(select(UsageBatchModel))).one() + counter = (await session.scalars(select(UsageCounterModel))).one() + assert row.gateway_replica_id == replica + assert row.gateway_id == parent + assert counter.usage_baches_id == row.id + # No live infrastructure rows are needed to read the receipt's source. + assert counter.total_tokens == 23 + with pytest.raises(UsageConflict): + await ingest_usage_batch(session, replica, None, batch("new", offset=1)) + await session.rollback() + async with test_db.get_session() as session: + row = (await session.scalars(select(UsageBatchModel))).one() + row.gateway_id = None # Represents unresolved pre-upgrade history. + await session.commit() + async with test_db.get_session() as session: + assert not (await ingest_usage_batch(session, replica, parent, batch())).inserted + row = (await session.scalars(select(UsageBatchModel))).one() + assert row.gateway_id is None # Replay cannot silently rewrite history. diff --git a/src/tests/_internal/server/test_usage_migration.py b/src/tests/_internal/server/test_usage_migration.py new file mode 100644 index 0000000000..e5bf608437 --- /dev/null +++ b/src/tests/_internal/server/test_usage_migration.py @@ -0,0 +1,146 @@ +"""Initial DS-002 migration creates the final schema without rewriting existing data.""" + +import importlib +import uuid +from datetime import datetime + +import pytest +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations +from sqlalchemy.ext.asyncio import create_async_engine +from sqlalchemy_utils import UUIDType + +MIGRATION = ( + "dstack._internal.server.migrations.versions.2026." + "11_16_1201_9a2e8f1f3c37_add_gateway_usage_batches" +) + + +def run_case(conn, populated): + # Independent pre-existing data makes an accidental rewrite/drop observable. + meta = sa.MetaData() + gateways = sa.Table( + "gateways", + meta, + sa.Column("id", UUIDType(binary=False), primary_key=True), + sa.Column("name", sa.String(), nullable=False), + ) + replicas = sa.Table( + "gateway_computes", + meta, + sa.Column("id", UUIDType(binary=False), primary_key=True), + sa.Column("gateway_id", UUIDType(binary=False)), + ) + meta.create_all(conn) + parent, replica = uuid.uuid4(), uuid.uuid4() + conn.execute(gateways.insert().values(id=parent, name="existing-gateway")) + conn.execute(replicas.insert().values(id=replica, gateway_id=parent)) + before = conn.execute(sa.select(gateways)).all(), conn.execute(sa.select(replicas)).all() + migration = importlib.import_module(MIGRATION) + with Operations.context(MigrationContext.configure(conn)): + migration.upgrade() + assert ( + conn.execute(sa.select(gateways)).all(), + conn.execute(sa.select(replicas)).all(), + ) == before + inspector = sa.inspect(conn) + assert "usage_collectors" not in inspector.get_table_names() + tables = sa.MetaData() + batches = sa.Table("usage_batches", tables, autoload_with=conn) + counters = sa.Table("usage_counters", tables, autoload_with=conn) + assert {"gateway_id", "gateway_replica_id"} <= set(batches.c.keys()) + assert "collector_id" not in batches.c + assert "usage_baches_id" in counters.c and "receipt_id" not in counters.c + assert inspector.get_foreign_keys("usage_batches") == [] + assert { + tuple(c["column_names"]) for c in inspector.get_unique_constraints("usage_batches") + } == { + ("gateway_replica_id", "batch_id"), + ("gateway_replica_id", "interval_start"), + } + assert inspector.get_pk_constraint("usage_counters")["constrained_columns"] == [ + "usage_baches_id", + "consumer_subject_id", + "service_id", + ] + fk = inspector.get_foreign_keys("usage_counters") + assert len(fk) == 1 + assert fk[0]["constrained_columns"] == ["usage_baches_id"] + assert fk[0]["referred_table"] == "usage_batches" and fk[0]["referred_columns"] == ["id"] + if not populated: + migration.downgrade() + assert set(inspector.get_table_names()) >= {"gateways", "gateway_computes"} + assert "usage_batches" not in sa.inspect(conn).get_table_names() + assert ( + conn.execute(sa.select(gateways)).all(), + conn.execute(sa.select(replicas)).all(), + ) == before + return + batch_id = uuid.uuid4().hex + conn.execute( + batches.insert().values( + id=batch_id, + gateway_replica_id=replica.hex, + gateway_id=parent.hex, + batch_id="b1", + interval_start=datetime(2026, 11, 17, 10), + interval_end=datetime(2026, 11, 17, 10, 1), + received_at=datetime(2026, 11, 17, 10, 2), + content='{"fixture":true}', + ) + ) + conn.execute( + counters.insert().values( + usage_baches_id=batch_id, + consumer_subject_id="u", + service_id="s", + prompt_tokens=20, + cached_prompt_tokens=5, + completion_tokens=3, + total_tokens=23, + unknown_usage_attempts=0, + ) + ) + rows = conn.execute(sa.select(batches)).all() + conn.execute(replicas.delete()) + conn.execute(gateways.delete()) + assert conn.execute(sa.select(batches)).all() == rows + assert conn.scalar(sa.select(sa.func.sum(counters.c.total_tokens))) == 23 + assert ( + conn.scalar( + sa.select(sa.func.count()).select_from( + counters.join(batches, counters.c.usage_baches_id == batches.c.id) + ) + ) + == 1 + ) + with pytest.raises(ValueError, match="backup"): + migration.downgrade() + assert conn.execute(sa.select(batches)).all() == rows + assert conn.scalar(sa.select(sa.func.count()).select_from(counters)) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "dialect", ["sqlite", pytest.param("postgres", marks=pytest.mark.postgres)] +) +@pytest.mark.parametrize("populated", [False, True]) +async def test_initial_usage_schema_preserves_existing_data(tmp_path, request, dialect, populated): + url = ( + f"sqlite+aiosqlite:///{tmp_path / 'migration.sqlite'}" + if dialect == "sqlite" + else request.getfixturevalue("postgres_container") + ) + engine = create_async_engine(url) + schema = "usage_test_" + uuid.uuid4().hex + try: + async with engine.begin() as conn: + if dialect == "postgres": + await conn.execute(sa.text(f'CREATE SCHEMA "{schema}"')) + await conn.execute(sa.text(f'SET LOCAL search_path TO "{schema}"')) + await conn.run_sync(lambda c: run_case(c, populated)) + if dialect == "postgres": + await conn.execute(sa.text(f'DROP SCHEMA "{schema}" CASCADE')) + finally: + await engine.dispose() From dbece7447efe5b16614b9dea147664f6675ed779 Mon Sep 17 00:00:00 2001 From: Igx22 Date: Wed, 18 Nov 2026 15:06:13 +0700 Subject: [PATCH 3/7] Accept null system fingerprints in chat completion responses --- .../_internal/proxy/lib/schemas/model_proxy.py | 2 +- .../proxy/lib/services/test_openai_usage.py | 17 ++++++++++++++--- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/dstack/_internal/proxy/lib/schemas/model_proxy.py b/src/dstack/_internal/proxy/lib/schemas/model_proxy.py index 04d54aa0c7..0d86426a3c 100644 --- a/src/dstack/_internal/proxy/lib/schemas/model_proxy.py +++ b/src/dstack/_internal/proxy/lib/schemas/model_proxy.py @@ -61,7 +61,7 @@ class ChatCompletionsResponse(CoreModel): choices: List[ChatCompletionsChoice] created: int model: str - system_fingerprint: str = "" + system_fingerprint: Optional[str] = "" object: Literal["chat.completion"] = "chat.completion" usage: ChatCompletionsUsage diff --git a/src/tests/_internal/proxy/lib/services/test_openai_usage.py b/src/tests/_internal/proxy/lib/services/test_openai_usage.py index ce265c040b..80533f407a 100644 --- a/src/tests/_internal/proxy/lib/services/test_openai_usage.py +++ b/src/tests/_internal/proxy/lib/services/test_openai_usage.py @@ -162,8 +162,15 @@ def get_usage_observer(self): @pytest.mark.asyncio -@pytest.mark.parametrize("stream", [False, True]) -async def test_model_handler_finalizes_verified_usage(tmp_path, monkeypatch, stream): +@pytest.mark.parametrize( + "stream,metadata", + [ + pytest.param(False, {}, id="json"), + pytest.param(False, {"system_fingerprint": None}, id="json-null-fingerprint"), + pytest.param(True, {}, id="stream"), + ], +) +async def test_model_handler_finalizes_verified_usage(tmp_path, monkeypatch, stream, metadata): clock = FakeClock() collector = MeteringCollector( MeteringStore(tmp_path / "usage.json"), clock=clock, profiles={"s": VLLM_PROFILE} @@ -184,6 +191,7 @@ async def test_model_handler_finalizes_verified_usage(tmp_path, monkeypatch, str app.state.proxy_dependency_injector = MeteredInjector(repo, collector) app.include_router(model_router, prefix="/models") response = {"id": "answer", "created": 1, "model": "test", "choices": [], "usage": USAGE} + response.update(metadata) wire = ("data: " + json.dumps(response) + "\n\ndata: [DONE]\n\n").encode() async with httpx.AsyncClient( transport=httpx.MockTransport( @@ -218,7 +226,10 @@ async def connection(*args, **kwargs): if stream: assert '"cached_tokens":5' in result.text else: - assert result.json()["usage"]["prompt_tokens_details"]["cached_tokens"] == 5 + assert result.json()["system_fingerprint"] == metadata.get( + "system_fingerprint", "" + ) + assert result.json()["usage"] == USAGE clock.advance() await collector.rotate_if_due() batches = (await collector.get_batches()).batches From ce7a4cf693e14d6ea62d6a621b522f2a8cc90b24 Mon Sep 17 00:00:00 2001 From: Igx22 Date: Thu, 19 Nov 2026 16:17:48 +0700 Subject: [PATCH 4/7] Poll Gateway usage under the replica lease and drain before scale-in Keep serving requests and the management connection alive during retirement. Seal the final minute and require a durable ACK before terminating the VM so another server can replay a committed batch after lease takeover. --- contributing/PROXY.md | 18 +- .../proxy/gateway/resources/nginx/nginx.conf | 14 +- .../_internal/proxy/gateway/routers/usage.py | 16 +- .../proxy/gateway/services/metering.py | 103 ++++- .../_internal/proxy/gateway/services/nginx.py | 63 ++- .../_internal/proxy/lib/schemas/usage.py | 21 + .../pipeline_tasks/gateway_replicas.py | 22 +- .../background/pipeline_tasks/jobs_running.py | 21 +- .../pipeline_tasks/runs/__init__.py | 3 +- .../background/scheduled_tasks/__init__.py | 2 - .../background/scheduled_tasks/usage.py | 107 ----- .../server/services/gateways/__init__.py | 23 +- .../server/services/gateways/client.py | 6 + .../server/services/gateways/connection.py | 41 +- .../server/services/gateways/pool.py | 69 ++- .../server/services/gateways/usage.py | 153 +++++++ .../server/services/runs/__init__.py | 13 +- .../server/services/runs/replicas.py | 13 +- .../proxy/gateway/metering/harness.py | 4 + .../proxy/gateway/metering/test_scenarios.py | 36 ++ .../proxy/gateway/routers/test_usage.py | 121 ++++++ .../proxy/gateway/services/test_metering.py | 194 +++++++++ .../gateway/services/test_nginx_drain.py | 210 +++++++++ .../pipeline_tasks/runs/test_active.py | 37 +- .../pipeline_tasks/test_gateway_replicas.py | 65 ++- .../pipeline_tasks/test_jobs_running.py | 11 +- .../background/scheduled_tasks/test_usage.py | 217 ---------- src/tests/_internal/server/conftest.py | 5 + .../server/services/gateways/test_gateways.py | 50 +++ .../server/services/gateways/test_pool.py | 103 +++++ .../server/services/gateways/test_usage.py | 402 ++++++++++++++++++ .../services/gateways/test_usage_client.py | 26 ++ .../server/services/runs/test_runs.py | 34 +- 33 files changed, 1777 insertions(+), 446 deletions(-) delete mode 100644 src/dstack/_internal/server/background/scheduled_tasks/usage.py create mode 100644 src/dstack/_internal/server/services/gateways/usage.py create mode 100644 src/tests/_internal/proxy/gateway/services/test_nginx_drain.py delete mode 100644 src/tests/_internal/server/background/scheduled_tasks/test_usage.py create mode 100644 src/tests/_internal/server/services/gateways/test_pool.py create mode 100644 src/tests/_internal/server/services/gateways/test_usage.py diff --git a/contributing/PROXY.md b/contributing/PROXY.md index b098adf539..c5874ca7d5 100644 --- a/contributing/PROXY.md +++ b/contributing/PROXY.md @@ -187,9 +187,21 @@ observations since the last successful checkpoint can be lost on forced terminat The `.lock` sidecar enforces one process, and `.initialized` detects missing established state. Never delete/reset these files as a routine repair: reconcile identity/history first. -Server polls `/api/usage/batches` over the existing private SSH management connection, -commits idempotent receipts/entries, then POSTs `/api/usage/batches/ack`. No network -work happens inside its database transaction. Old Gateways lacking this API are skipped. +The `GatewayReplicaPipeline` worker holding the running replica's lease polls +`/api/usage/batches` over its private SSH management connection. It verifies the +source and lease token, commits the page's receipts and counters, then POSTs +`/api/usage/batches/ack` outside the transaction. If the server exits between +commit and ACK, another server can claim the replica after lease expiry and ACK +the replayed page. Old Gateways lacking the usage API still get normal state sync. + +On planned removal of a serving Gateway replica, the worker calls the private +`POST /api/usage/drain`. Nginx fences new public requests and lets open HTTP +streams and WebSockets finish. The collector then seals the final active minute. +The worker keeps delivering closed batches during the wait. Only a sealed, empty +queue permits the worker to mark the VM for termination. An open stream can +therefore delay scale-in. Update the Gateway and all server workers before +relying on this protocol. If a Gateway lacks the drain API or crashes with +unresolved requests, its VM stays in place pending upgrade or reconciliation. Public project model endpoints traverse metering; direct service hostnames still bypass it. Resolve that routing policy before paid use. Token quotas are outside DS-002. Local diff --git a/src/dstack/_internal/proxy/gateway/resources/nginx/nginx.conf b/src/dstack/_internal/proxy/gateway/resources/nginx/nginx.conf index 0e4820f58c..760c223e5a 100644 --- a/src/dstack/_internal/proxy/gateway/resources/nginx/nginx.conf +++ b/src/dstack/_internal/proxy/gateway/resources/nginx/nginx.conf @@ -1,5 +1,5 @@ user www-data; -worker_processes auto; +worker_processes {{ 1 if draining else "auto" }}; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; @@ -27,6 +27,18 @@ http { gzip on; + {% if draining %} + # The model proxy forwards already accepted requests to services over 127.0.0.1. + allow 127.0.0.1; + deny all; + server { + listen unix:{{ drain_socket }}; + return 200 "$pid"; + } + include /etc/nginx/sites-enabled/00-log-format.conf; + include /etc/nginx/sites-enabled/443-*.conf; + {% else %} include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; + {% endif %} } diff --git a/src/dstack/_internal/proxy/gateway/routers/usage.py b/src/dstack/_internal/proxy/gateway/routers/usage.py index 63f486c106..69caaacc67 100644 --- a/src/dstack/_internal/proxy/gateway/routers/usage.py +++ b/src/dstack/_internal/proxy/gateway/routers/usage.py @@ -4,17 +4,31 @@ from fastapi import APIRouter, Depends, Query -from dstack._internal.proxy.gateway.deps import get_metering +from dstack._internal.proxy.gateway.deps import get_metering, get_nginx from dstack._internal.proxy.gateway.services.metering import MeteringCollector +from dstack._internal.proxy.gateway.services.nginx import Nginx from dstack._internal.proxy.lib.schemas.usage import ( UsageAckRequest, UsageAckResponse, UsageBatchPage, + UsageDrainResponse, ) router = APIRouter() +@router.post("/drain", response_model=UsageDrainResponse) +async def drain_usage( + metering: Annotated[MeteringCollector, Depends(get_metering)], + nginx: Annotated[Nginx, Depends(get_nginx)], +) -> UsageDrainResponse: + # Record where a process crash can interrupt active requests before changing ingress. + await metering.drain(ingress_idle=False) + if not await nginx.drain(): + return UsageDrainResponse(sealed=False, empty=False) + return await metering.drain() + + @router.get("/batches", response_model=UsageBatchPage) async def get_batches( metering: Annotated[MeteringCollector, Depends(get_metering)], diff --git a/src/dstack/_internal/proxy/gateway/services/metering.py b/src/dstack/_internal/proxy/gateway/services/metering.py index 01126f89ee..8dc62afdf7 100644 --- a/src/dstack/_internal/proxy/gateway/services/metering.py +++ b/src/dstack/_internal/proxy/gateway/services/metering.py @@ -4,7 +4,7 @@ import uuid from collections.abc import Awaitable, Callable, Mapping from datetime import datetime, timedelta, timezone -from typing import Any +from typing import Any, Literal from dstack._internal.proxy.gateway.services.metering_store import MeteringStore from dstack._internal.proxy.lib.cancellation import await_completion @@ -15,6 +15,7 @@ UsageBatch, UsageBatchPage, UsageCheckpoint, + UsageDrainResponse, UsageEntry, UsageKey, ) @@ -59,6 +60,8 @@ def __init__( self._closed = False self._pending_bytes = 0 self._reconfiguring = False + self._interrupted_drain = False + self._saved_drain_state: str | None = None async def start(self) -> None: async with self._lock: @@ -66,18 +69,25 @@ async def start(self) -> None: return if not self.profiles and not self.store.exists(): return - saved = await asyncio.to_thread(self.store.load) - now = self.clock.utc_now() - self._state = saved or UsageCheckpoint(active_batch=self._new_batch(now)) - self._entries = {entry.key: entry for entry in self._state.active_batch.entries} - self._published = {batch.batch_id for batch in self._state.pending_batches} - self._pending_bytes = sum( - len(b.model_dump_json().encode()) for b in self._state.pending_batches - ) - self._last_time = self._state.active_batch.interval_start - await self._rotate(now) + await self._load() + await self._rotate(self.clock.utc_now()) await self._save(self._snapshot()) + async def _load(self) -> None: + saved = await asyncio.to_thread(self.store.load) + self._state = saved or UsageCheckpoint(active_batch=self._new_batch(self.clock.utc_now())) + self._entries = {entry.key: entry for entry in self._state.active_batch.entries} + self._published = {batch.batch_id for batch in self._state.pending_batches} + self._pending_bytes = sum( + len(b.model_dump_json().encode()) for b in self._state.pending_batches + ) + self._last_time = self._state.active_batch.interval_start + self._saved_drain_state = self._state.drain_state + self._interrupted_drain = self._state.drain_state in ("ingress", "waiting") + if self._state.drain_state == "ingress_stopped": + # start() checkpoints this before admitting traffic from the old Nginx generation. + self._state = self._state.model_copy(update={"drain_state": "ingress"}) + async def configure_profiles( self, profiles: Mapping[str, str], persist: Callable[[], Awaitable[None]] | None = None ) -> None: @@ -113,6 +123,8 @@ def start_attempt(self, key: UsageKey, profile: str) -> UsageAttempt: self._closed or self._reconfiguring or self._state is None + or self._interrupted_drain + or self._state.drain_state in ("waiting", "sealed") or self._storage_error or self._clock_error or self.profile_for(key.service_id) != profile @@ -142,6 +154,46 @@ async def rotate_if_due(self) -> None: if changed or self._storage_error: await self._save(self._snapshot()) + async def drain(self, *, ingress_idle: bool = True) -> UsageDrainResponse: + # Finish the checkpoint and publish its result even if the caller disconnects. + return await await_completion(asyncio.create_task(self._drain(ingress_idle))) + + async def _drain(self, ingress_idle: bool) -> UsageDrainResponse: + async with self._lock: + if self._state is None: + # An unused replica also needs a durable admission fence. + await self._load() + assert self._state is not None + if self._interrupted_drain: + if not ingress_idle: + # Still let the private router fence Nginx ingress after a restart. + return UsageDrainResponse(sealed=False, empty=False) + raise ProxyError( + "Gateway restarted with unresolved usage; reconcile the drain", 503 + ) + phase: Literal["waiting", "ingress"] = "waiting" if ingress_idle else "ingress" + if self._state.drain_state is None or ( + self._state.drain_state == "ingress" and ingress_idle + ): + self._state = self._state.model_copy(update={"drain_state": phase}) + self._seal_if_idle() + if self._state.drain_state != self._saved_drain_state or self._storage_error: + await self._save(self._snapshot()) + sealed = ingress_idle and self._state.drain_state == "sealed" + return UsageDrainResponse( + sealed=sealed, empty=sealed and not self._state.pending_batches + ) + + def _seal_if_idle(self) -> bool: + assert self._state is not None + if self._state.drain_state != "waiting" or self._attempts: + return False + if self._entries: + # Close the original UTC minute early. No new attempt can enter it. + self._rollover(self._state.active_batch.interval_end) + self._state = self._state.model_copy(update={"drain_state": "sealed"}) + return True + async def get_batches(self, limit: int = 100) -> UsageBatchPage: if not 1 <= limit <= 100: raise ProxyError("Batch limit must be between 1 and 100") @@ -155,6 +207,10 @@ async def get_batches(self, limit: int = 100) -> UsageBatchPage: ).model_copy(deep=True) async def acknowledge(self, batch_ids: list[str]) -> UsageAckResponse: + # The matching in-memory commit must finish together with its durable write. + return await await_completion(asyncio.create_task(self._acknowledge(batch_ids))) + + async def _acknowledge(self, batch_ids: list[str]) -> UsageAckResponse: async with self._lock: if self._state is None: raise ProxyError("Usage metering is not initialized", 404) @@ -189,7 +245,15 @@ async def close(self) -> None: try: for attempt in list(self._attempts): await attempt.finish() - await self.checkpoint() + async with self._lock: + if self._state is not None: + if self._state.drain_state == "ingress" and not self._interrupted_drain: + # An old Nginx worker can still be buffering a model request. + # The next collector must admit it until ingress confirms quiescence. + self._state = self._state.model_copy( + update={"drain_state": "ingress_stopped"} + ) + await self._save(self._snapshot()) finally: self.store.close() @@ -200,6 +264,8 @@ async def _finish(self, attempt: "MeteringAttempt") -> None: if not attempt.dispatched: attempt.finished = True self._attempts.discard(attempt) + if self._seal_if_idle(): + await self._save(self._snapshot()) return try: rotated = await self._rotate(self.clock.utc_now()) @@ -222,7 +288,7 @@ async def _finish(self, attempt: "MeteringAttempt") -> None: ) attempt.finished = True self._attempts.discard(attempt) - if rotated: + if self._seal_if_idle() or rotated: try: await self._save(self._snapshot()) except (OSError, ValueError): @@ -230,12 +296,19 @@ async def _finish(self, attempt: "MeteringAttempt") -> None: async def _rotate(self, now: datetime) -> bool: assert self._state is not None + if self._state.drain_state == "sealed": + return False if self._last_time is not None and now < self._last_time: self._clock_error = True raise ProxyError("Usage clock moved backwards; reconciliation is required", 503) self._last_time = now if now < self._state.active_batch.interval_end: return False + self._rollover(now) + return True + + def _rollover(self, next_minute: datetime) -> None: + assert self._state is not None previous = self._state.active_batch.model_copy( update={"entries": list(self._entries.values())} ) @@ -244,10 +317,9 @@ async def _rotate(self, now: datetime) -> bool: pending.append(previous) self._pending_bytes += len(previous.model_dump_json().encode()) self._state = self._state.model_copy( - update={"active_batch": self._new_batch(now), "pending_batches": pending} + update={"active_batch": self._new_batch(next_minute), "pending_batches": pending} ) self._entries = {} - return True def _snapshot(self) -> UsageCheckpoint: assert self._state is not None @@ -267,6 +339,7 @@ async def _save(self, state: UsageCheckpoint) -> None: self._storage_error = exc raise self._published = {batch.batch_id for batch in state.pending_batches} + self._saved_drain_state = state.drain_state self._storage_error = None @staticmethod diff --git a/src/dstack/_internal/proxy/gateway/services/nginx.py b/src/dstack/_internal/proxy/gateway/services/nginx.py index d55f04ada9..ba6038a8b8 100644 --- a/src/dstack/_internal/proxy/gateway/services/nginx.py +++ b/src/dstack/_internal/proxy/gateway/services/nginx.py @@ -1,16 +1,21 @@ +import asyncio import importlib.resources +import os import subprocess import tempfile from asyncio import Lock from pathlib import Path from typing import Literal, Optional +import httpx import jinja2 +import psutil from pydantic import BaseModel from dstack._internal.proxy.gateway.const import PROXY_PORT_ON_GATEWAY from dstack._internal.proxy.gateway.models import ACMESettings from dstack._internal.proxy.lib import models +from dstack._internal.proxy.lib.cancellation import await_completion from dstack._internal.proxy.lib.errors import ProxyError, UnexpectedProxyError from dstack._internal.utils.common import run_async from dstack._internal.utils.logging import get_logger @@ -18,6 +23,8 @@ CERTBOT_TIMEOUT = 40 CERTBOT_2ND_TIMEOUT = 5 NGINX_DIR = Path("/etc/nginx") +NGINX_PID_FILE = Path("/run/nginx.pid") +NGINX_DRAIN_SOCKET = Path("/run/dstack-nginx-drain.sock") logger = get_logger(__name__) @@ -84,6 +91,7 @@ def __init__(self, nginx_dir: Path = NGINX_DIR) -> None: self._nginx_dir = nginx_dir self._sites_enabled_dir = nginx_dir / "sites-enabled" self._nginx_conf_path = nginx_dir / "nginx.conf" + self._drain_marker = nginx_dir / ".dstack-draining" self._lock: Lock = Lock() async def register(self, conf: SiteConfig, acme: ACMESettings) -> None: @@ -181,9 +189,60 @@ def get_config_name(domain: str) -> str: def write_global_conf(self) -> None: log_format_conf = read_package_resource("00-log-format.conf") self.write_conf(log_format_conf, self._sites_enabled_dir / "00-log-format.conf") + self.write_conf(self._global_conf(), self._nginx_conf_path) + + def _global_conf(self) -> str: + template = jinja2.Template( + read_package_resource("nginx.conf"), + trim_blocks=True, + lstrip_blocks=True, + keep_trailing_newline=True, + ) + return template.render( + draining=self._drain_marker.exists(), drain_socket=NGINX_DRAIN_SOCKET + ) + + async def drain(self) -> bool: + """Fence public routes and poll until all pre-drain workers finish naturally.""" + async with self._lock: + return await await_completion(asyncio.create_task(run_async(self._drain))) + + def _drain(self) -> bool: + if not self._drain_marker.exists(): + sudo_write(self._drain_marker, "") + config = self._global_conf() + if not self._nginx_conf_path.exists() or self._nginx_conf_path.read_text() != config: + # Keep the fence on disk if reload fails. Nginx may restart before the next poll. + sudo_write(self._nginx_conf_path, config) + self.reload() + return False - nginx_conf = read_package_resource("nginx.conf") - self.write_conf(nginx_conf, self._nginx_conf_path) + # A successful HUP only acknowledges the signal. Probe the running generation + # through its private listener, then check that every older worker has exited. + try: + with httpx.Client(transport=httpx.HTTPTransport(uds=str(NGINX_DRAIN_SOCKET))) as http: + response = http.get("http://localhost/", timeout=1) + response.raise_for_status() + worker_pid = int(response.text) + except (httpx.HTTPError, ValueError): + # A crash can leave the correct file on disk before the reload signal. + self.reload() + return False + try: + master = psutil.Process(int(NGINX_PID_FILE.read_text())) + if [child.pid for child in master.children()] != [worker_pid]: + return False + except (OSError, ValueError, psutil.Error): + return False + # Either process may restart first. Persist both the Nginx boot config and the + # Gateway's mode marker, including their directory entries, before certifying. + for path in (self._nginx_conf_path, self._drain_marker, self._nginx_dir): + fd = os.open(path, os.O_RDONLY) + try: + os.fsync(fd) + finally: + os.close(fd) + return True def read_package_resource(file: str) -> str: diff --git a/src/dstack/_internal/proxy/lib/schemas/usage.py b/src/dstack/_internal/proxy/lib/schemas/usage.py index fe10feb1af..6a23822b5e 100644 --- a/src/dstack/_internal/proxy/lib/schemas/usage.py +++ b/src/dstack/_internal/proxy/lib/schemas/usage.py @@ -85,6 +85,16 @@ def check_batch_ids(self) -> Self: class UsageCheckpoint(_UsageCheckpoint): schema_version: Literal[2] = 2 + drain_state: Literal["ingress", "ingress_stopped", "waiting", "sealed"] | None = Field( + default=None, exclude_if=lambda state: state is None + ) + """ingress_stopped records a clean collector stop while old Nginx workers can still deliver.""" + + @model_validator(mode="after") + def check_sealed(self) -> Self: + if self.drain_state == "sealed" and self.active_batch.entries: + raise ValueError("A sealed checkpoint cannot have unclosed entries") + return self class LegacyUsageCheckpoint(_UsageCheckpoint): @@ -122,3 +132,14 @@ class UsageAckRequest(UsageModel): class UsageAckResponse(UsageModel): acknowledged_batch_ids: list[Identifier] + + +class UsageDrainResponse(UsageModel): + sealed: Annotated[bool, Field(strict=True)] + empty: Annotated[bool, Field(strict=True)] + + @model_validator(mode="after") + def check_empty(self) -> Self: + if self.empty and not self.sealed: + raise ValueError("An unsealed source cannot certify an empty drain") + return self diff --git a/src/dstack/_internal/server/background/pipeline_tasks/gateway_replicas.py b/src/dstack/_internal/server/background/pipeline_tasks/gateway_replicas.py index 8dafff69c0..930437261c 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/gateway_replicas.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/gateway_replicas.py @@ -64,6 +64,10 @@ from dstack._internal.server.services.gateways.client import GatewayClient from dstack._internal.server.services.gateways.connection import GatewayConnection from dstack._internal.server.services.gateways.pool import gateway_connections_pool +from dstack._internal.server.services.gateways.usage import ( + collect_gateway_usage, + drain_gateway_usage, +) from dstack._internal.server.services.instances import get_instance_remote_connection_info from dstack._internal.server.services.jobs import job_model_to_job_submission from dstack._internal.server.services.locking import get_locker @@ -655,12 +659,6 @@ async def _process_running_item(item: GatewayReplicaPipelineItem): if replica_model is None: return gateway_model = _get_loaded_gateway_model(replica_model) - if gateway_model is None: - await _commit_update(item, replica_model, update_map={}) - return - if update_map := _mark_terminating_if_needed(gateway_model, replica_model): - await _commit_update(item, replica_model, update_map=update_map) - return try: connection = await gateway_connections_pool.get_or_add( hostname=get_or_error(replica_model.ip_address), @@ -670,6 +668,18 @@ async def _process_running_item(item: GatewayReplicaPipelineItem): logger.warning("%s: failed to connect to gateway: %s", fmt(replica_model), e) await _commit_update(item, replica_model, update_map={}) return + if gateway_model is not None and ( + update_map := _mark_terminating_if_needed(gateway_model, replica_model) + ): + # Keep the replica active and its management tunnel usable until the final ACK. + # The token-guarded transition records permission for the terminating worker. + drained = await drain_gateway_usage(connection, item.id, gateway_model.id, item.lock_token) + await _commit_update(item, replica_model, update_map=update_map if drained else {}) + return + await collect_gateway_usage(connection, item.id, item.lock_token) + if gateway_model is None: + await _commit_update(item, replica_model, update_map={}) + return async with connection.client() as client: try: currently_registered_services = await client.list_services() diff --git a/src/dstack/_internal/server/background/pipeline_tasks/jobs_running.py b/src/dstack/_internal/server/background/pipeline_tasks/jobs_running.py index 56dcbf0076..5cd9a88d24 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/jobs_running.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/jobs_running.py @@ -21,7 +21,6 @@ ServiceConfiguration, ) from dstack._internal.core.models.files import FileArchiveMapping -from dstack._internal.core.models.gateways import GatewayReplicaStatus from dstack._internal.core.models.instances import InstanceStatus from dstack._internal.core.models.metrics import Metric from dstack._internal.core.models.profiles import StartupOrder @@ -82,7 +81,7 @@ resolve_provisioning_image, ) from dstack._internal.server.services.gateways import ( - get_gateway_replica_models, + get_serving_gateway_replica_models, skip_gateway_replicas_min_processing_interval, ) from dstack._internal.server.services.instances import ( @@ -543,11 +542,15 @@ async def _fetch_run_model( query = query.options( joinedload(RunModel.gateway) .selectinload(GatewayModel.gateway_replicas) - .load_only(GatewayReplicaModel.id, GatewayReplicaModel.status), + .load_only( + GatewayReplicaModel.id, GatewayReplicaModel.status, GatewayReplicaModel.scale_in + ), ).options( joinedload(RunModel.gateway) .joinedload(GatewayModel.gateway_replica) - .load_only(GatewayReplicaModel.id, GatewayReplicaModel.status), + .load_only( + GatewayReplicaModel.id, GatewayReplicaModel.status, GatewayReplicaModel.scale_in + ), ) if replica_num is not None: assert run_spec is not None, "run_spec must be provided when replica_num is set" @@ -1165,17 +1168,15 @@ async def _check_gpu_utilization( def _job_gateway_registration_failed(gateway: GatewayModel | None, job_model: JobModel) -> bool: if gateway is None: return False - running_gateway_replica_ids = { - replica.id - for replica in get_gateway_replica_models(gateway) - if replica.status == GatewayReplicaStatus.RUNNING + serving_gateway_replica_ids = { + replica.id for replica in get_serving_gateway_replica_models(gateway) } - if not running_gateway_replica_ids: + if not serving_gateway_replica_ids: return False registration_by_replica_id = { r.gateway_replica_id: r for r in job_model.service_replica_registrations } - for replica_id in running_gateway_replica_ids: + for replica_id in serving_gateway_replica_ids: registration = registration_by_replica_id.get(replica_id) if ( registration is None diff --git a/src/dstack/_internal/server/background/pipeline_tasks/runs/__init__.py b/src/dstack/_internal/server/background/pipeline_tasks/runs/__init__.py index 713828d27b..18029e701a 100644 --- a/src/dstack/_internal/server/background/pipeline_tasks/runs/__init__.py +++ b/src/dstack/_internal/server/background/pipeline_tasks/runs/__init__.py @@ -48,7 +48,6 @@ from dstack._internal.server.services import events from dstack._internal.server.services.gateways import ( get_combined_gateway_stats, - get_gateway_replica_models, ) from dstack._internal.server.services.jobs import emit_job_status_change_event from dstack._internal.server.services.locking import get_locker @@ -537,7 +536,7 @@ async def _load_gateway_stats(run_model: RunModel, run_spec: RunSpec) -> Optiona if run_spec.configuration.type != "service" or run_model.gateway is None: return None return await get_combined_gateway_stats( - get_gateway_replica_models(run_model.gateway), + run_model.gateway, run_model.project.name, run_model.run_name, ) diff --git a/src/dstack/_internal/server/background/scheduled_tasks/__init__.py b/src/dstack/_internal/server/background/scheduled_tasks/__init__.py index 1d2f20dca1..697133a1c8 100644 --- a/src/dstack/_internal/server/background/scheduled_tasks/__init__.py +++ b/src/dstack/_internal/server/background/scheduled_tasks/__init__.py @@ -30,7 +30,6 @@ collect_prometheus_metrics, delete_prometheus_metrics, ) -from dstack._internal.server.background.scheduled_tasks.usage import collect_gateway_usage from dstack._internal.server.services.backends.cache import close_unused_backends _scheduler = AsyncIOScheduler() @@ -55,7 +54,6 @@ def start_scheduled_tasks() -> AsyncIOScheduler: _scheduler.add_job(delete_metrics, IntervalTrigger(minutes=5), max_instances=1) _scheduler.add_job(delete_events, IntervalTrigger(minutes=7), max_instances=1) _scheduler.add_job(process_gateways_connections, IntervalTrigger(seconds=15)) - _scheduler.add_job(collect_gateway_usage, IntervalTrigger(seconds=15), max_instances=1) _scheduler.add_job(close_unused_backends, IntervalTrigger(minutes=1), max_instances=1) _scheduler.add_job( process_idle_volumes, IntervalTrigger(seconds=60, jitter=10), max_instances=1 diff --git a/src/dstack/_internal/server/background/scheduled_tasks/usage.py b/src/dstack/_internal/server/background/scheduled_tasks/usage.py deleted file mode 100644 index 9b26bc96ad..0000000000 --- a/src/dstack/_internal/server/background/scheduled_tasks/usage.py +++ /dev/null @@ -1,107 +0,0 @@ -"""Fetch durable minute batches, commit receipts, then ACK over existing SSH connections.""" - -import asyncio -import uuid -from collections import defaultdict -from contextlib import asynccontextmanager - -import httpx -from sqlalchemy import select - -from dstack._internal.server.db import get_db, get_session_ctx -from dstack._internal.server.models import GatewayModel, GatewayReplicaModel -from dstack._internal.server.services.gateways.connection import GatewayConnection -from dstack._internal.server.services.gateways.pool import gateway_connections_pool -from dstack._internal.server.services.usage import ingest_usage_batch -from dstack._internal.utils.logging import get_logger - -logger = get_logger(__name__) -PAGE_SIZE = 100 -MAX_PAGES = 10 -COLLECTION_TIMEOUT = 12 -_sqlite_ingestion_lock = asyncio.Lock() - - -async def collect_gateway_usage() -> None: - async with get_session_ctx() as session: - rows = ( - await session.execute( - select( - GatewayReplicaModel.id, - GatewayReplicaModel.ip_address, - GatewayReplicaModel.gateway_id, - ).where(GatewayReplicaModel.active == True) - ) - ).all() - legacy_rows = ( - await session.execute( - select(GatewayModel.gateway_replica_id, GatewayModel.id).where( - GatewayModel.gateway_replica_id.is_not(None) - ) - ) - ).all() - legacy_parents: dict[uuid.UUID, set[uuid.UUID]] = defaultdict(set) - for replica_id, gateway_id in legacy_rows: - legacy_parents[replica_id].add(gateway_id) - identities: dict[str, list[tuple[uuid.UUID, uuid.UUID | None]]] = defaultdict(list) - for replica_id, address, gateway_id in rows: - parents = legacy_parents[replica_id] | ({gateway_id} if gateway_id else set()) - if address is not None: - # Retain ambiguous entries so no other replica at this address is selected. - for parent in parents or {None}: - identities[address].append((replica_id, parent)) - semaphore = asyncio.Semaphore(8) - - async def collect(connection: GatewayConnection) -> None: - candidates = identities.get(connection.ip_address, []) - if len(candidates) != 1: - # Ambiguous/recycled addresses cannot establish a verified billing source. - return - async with semaphore: - try: - async with asyncio.timeout(COLLECTION_TIMEOUT): - await _collect_connection(connection, *candidates[0]) - except httpx.HTTPStatusError as exc: - if exc.response.status_code not in (404, 405): - logger.warning( - "Usage collection HTTP failure from %s: %s", connection.ip_address, exc - ) - except Exception: - logger.exception( - "Usage collection failed from %s; unacknowledged batches retained", - connection.ip_address, - ) - - await asyncio.gather( - *(collect(connection) for connection in await gateway_connections_pool.all()) - ) - - -async def _collect_connection( - connection: GatewayConnection, replica_id: uuid.UUID, gateway_id: uuid.UUID | None -) -> None: - for _ in range(MAX_PAGES): - async with connection.client() as client: - page = await client.fetch_usage_batches(PAGE_SIZE) - if not page.batches: - return - # SQLite is single-server; lock before opening a session. PG relies on DB constraints. - async with _ingestion_lock(): - async with get_session_ctx() as session: - for batch in page.batches: - await ingest_usage_batch(session, replica_id, gateway_id, batch) - # get_session_ctx commits and closes before leaving this block. - ids = [batch.batch_id for batch in page.batches] - async with connection.client() as client: - await client.acknowledge_usage(ids) - if not page.has_more: - return - - -@asynccontextmanager -async def _ingestion_lock(): - if get_db().dialect_name == "sqlite": - async with _sqlite_ingestion_lock: - yield - else: - yield diff --git a/src/dstack/_internal/server/services/gateways/__init__.py b/src/dstack/_internal/server/services/gateways/__init__.py index 0a68bd271f..5f99d6ea15 100644 --- a/src/dstack/_internal/server/services/gateways/__init__.py +++ b/src/dstack/_internal/server/services/gateways/__init__.py @@ -682,13 +682,13 @@ async def generate_gateway_name(session: AsyncSession, project: ProjectModel) -> async def get_or_add_gateway_connections( - gateway_replicas: Sequence[GatewayReplicaModel], + gateway: GatewayModel, ) -> List[GatewayConnection]: - running_replicas = [r for r in gateway_replicas if r.status == GatewayReplicaStatus.RUNNING] - if not running_replicas: + serving_replicas = get_serving_gateway_replica_models(gateway) + if not serving_replicas: raise GatewayError("Gateway replica not found") connections: List[GatewayConnection] = [] - for replica in running_replicas: + for replica in serving_replicas: if replica.ip_address is None: logger.warning("Gateway replica %s has no ip_address", replica.id) raise GatewayError("Failed to connect to gateway replica") @@ -705,7 +705,7 @@ async def get_or_add_gateway_connections( async def get_combined_gateway_stats( - gateway_replicas: Sequence[GatewayReplicaModel], + gateway: GatewayModel, project_name: str, run_name: str, ) -> Optional[PerWindowStats]: @@ -715,7 +715,7 @@ async def get_combined_gateway_stats( try: # FIXME: once a gateway replica is scaled in, its connection is no longer available and its # stats are lost, potentially resulting in incorrect service scaling decisions. - connections = await get_or_add_gateway_connections(gateway_replicas) + connections = await get_or_add_gateway_connections(gateway) except GatewayError: return None per_replica: list[PerWindowStats] = [] @@ -886,6 +886,17 @@ def get_gateway_replica_models(gateway_model: GatewayModel) -> List[GatewayRepli return replicas +def get_serving_gateway_replica_models(gateway: GatewayModel) -> list[GatewayReplicaModel]: + # Draining replicas remain RUNNING for final usage collection and skip registration. + if gateway.to_be_deleted or gateway.status == GatewayStatus.FAILED: + return [] + return [ + replica + for replica in get_gateway_replica_models(gateway) + if replica.status == GatewayReplicaStatus.RUNNING and not replica.scale_in + ] + + async def skip_gateway_replicas_min_processing_interval( session: AsyncSession, gateway_id: uuid.UUID ) -> None: diff --git a/src/dstack/_internal/server/services/gateways/client.py b/src/dstack/_internal/server/services/gateways/client.py index bbc5354d74..a0eb7c9318 100644 --- a/src/dstack/_internal/server/services/gateways/client.py +++ b/src/dstack/_internal/server/services/gateways/client.py @@ -22,6 +22,7 @@ UsageAckRequest, UsageAckResponse, UsageBatchPage, + UsageDrainResponse, ) from dstack._internal.server import settings @@ -274,6 +275,11 @@ async def acknowledge_usage(self, batch_ids: list[str]) -> UsageAckResponse: raise ValueError("Gateway acknowledged unexpected usage batch IDs") return result + async def drain_usage(self) -> UsageDrainResponse: + response = await self._client.post(self._url("/api/usage/drain"), timeout=10) + response.raise_for_status() + return UsageDrainResponse.model_validate(response.json()) + def _url(self, path: str) -> str: return f"{self.base_url}/{path.lstrip('/')}" diff --git a/src/dstack/_internal/server/services/gateways/connection.py b/src/dstack/_internal/server/services/gateways/connection.py index 555f9aaa09..0a2cf6a677 100644 --- a/src/dstack/_internal/server/services/gateways/connection.py +++ b/src/dstack/_internal/server/services/gateways/connection.py @@ -1,4 +1,5 @@ import contextlib +import hashlib import shutil import uuid from pathlib import Path @@ -6,6 +7,7 @@ import aiorwlock +from dstack._internal.core.errors import SSHError from dstack._internal.core.services.ssh.tunnel import ( SSH_DEFAULT_OPTIONS, IPSocket, @@ -21,7 +23,7 @@ from dstack._internal.server import settings from dstack._internal.server.services.gateways.client import GatewayClient from dstack._internal.utils.logging import get_logger -from dstack._internal.utils.path import FileContent, make_tmp_symlink_to_dir +from dstack._internal.utils.path import FileContent, FilePath, make_tmp_symlink_to_dir logger = get_logger(__name__) @@ -30,6 +32,10 @@ def _get_connections_dir() -> Path: return settings.SERVER_DIR_PATH / "gateway-connections" +def ssh_key_digest(id_rsa: str) -> str: + return hashlib.sha256(id_rsa.encode()).hexdigest() + + class GatewayConnection: """ `GatewayConnection` instances persist for the lifetime of the gateway replica. @@ -46,7 +52,9 @@ def __init__(self, ip_address: str, id_rsa: str, server_port: int): self.server_port = server_port # a persistent connection_dir is needed to discover and close leftover connections # in case of server restarts w/o graceful shutdown - self.connection_dir = _get_connections_dir() / ip_address + # Different server processes may share this directory while an IP is reassigned. + self.connection_dir = _get_connections_dir() / ip_address / ssh_key_digest(id_rsa) + self._closed = False # connection_dir can have a long path that won't be accepted by the ssh command, # so we create a short temporary symlink self.temp_dir, self.connection_symlink_dir = make_tmp_symlink_to_dir( @@ -59,6 +67,7 @@ def __init__(self, ip_address: str, id_rsa: str, server_port: int): control_sock_path=self.connection_symlink_dir / "control.sock", options={ **SSH_DEFAULT_OPTIONS, + "IdentitiesOnly": "yes", "ConnectTimeout": "1", "ServerAliveInterval": "60", }, @@ -75,6 +84,8 @@ def __init__(self, ip_address: str, id_rsa: str, server_port: int): async def check_or_restart(self) -> bool: async with self._lock.writer_lock: + if self._closed: + return False if not await self.tunnel.acheck(): logger.info("Connection to gateway %s is down, restarting", self.ip_address) await self._open_tunnel() @@ -83,12 +94,30 @@ async def check_or_restart(self) -> bool: async def open(self, close_existing_tunnel: bool = False) -> None: async with self._lock.writer_lock: + if self._closed: + raise SSHError("Gateway connection is closed") if close_existing_tunnel: # Close remaining tunnel if previous server process died w/o graceful shutdown + await self._close_legacy_tunnel() if await self.tunnel.acheck(): await self.tunnel.aclose() await self._open_tunnel() + async def _close_legacy_tunnel(self) -> None: + # Older servers placed control.sock directly under the address. Only use it + # for startup cleanup; management HTTP always uses the key-specific tunnel. + address_dir = self.connection_dir.parent + if not (address_dir / "control.sock").exists(): + return + temp_dir, short_path = make_tmp_symlink_to_dir(address_dir, "legacy") + with temp_dir: + legacy = SSHTunnel( + destination=self.tunnel.destination, + identity=FilePath(self.tunnel.identity_path), + control_sock_path=short_path / "control.sock", + ) + await legacy.aclose() + async def _open_tunnel(self) -> None: self.connection_dir.mkdir(parents=True, exist_ok=True) remote_socket_path = f"{SERVER_CONNECTIONS_DIR_ON_GATEWAY}/{self.tunnel_id}.sock" @@ -110,8 +139,14 @@ async def _open_tunnel(self) -> None: async def close(self) -> None: async with self._lock.writer_lock: + if self._closed: + return await self.tunnel.aclose() + self._closed = True + self.temp_dir.cleanup() shutil.rmtree(self.connection_dir, ignore_errors=True) + with contextlib.suppress(OSError): + self.connection_dir.parent.rmdir() async def try_collect_stats(self) -> None: if not self._client.is_server_ready: @@ -133,4 +168,6 @@ async def get_stats(self, project_name: str, run_name: str) -> Optional[PerWindo @contextlib.asynccontextmanager async def client(self) -> AsyncIterator[GatewayClient]: async with self._lock.reader_lock: + if self._closed: + raise SSHError("Gateway connection is closed") yield self._client diff --git a/src/dstack/_internal/server/services/gateways/pool.py b/src/dstack/_internal/server/services/gateways/pool.py index eaed7c2e95..03fde606a0 100644 --- a/src/dstack/_internal/server/services/gateways/pool.py +++ b/src/dstack/_internal/server/services/gateways/pool.py @@ -1,17 +1,14 @@ import asyncio -from typing import Dict, List +from weakref import WeakValueDictionary -from dstack._internal.server.services.gateways.connection import GatewayConnection +from dstack._internal.server.services.gateways.connection import GatewayConnection, ssh_key_digest from dstack._internal.server.settings import SERVER_PORT -from dstack._internal.utils.logging import get_logger - -logger = get_logger(__name__) class GatewayConnectionsPool: def __init__(self) -> None: - self._connections: Dict[str, GatewayConnection] = {} - self._lock = asyncio.Lock() + self._connections: dict[str, tuple[str, GatewayConnection]] = {} + self._locks: WeakValueDictionary[str, asyncio.Lock] = WeakValueDictionary() async def get_or_add( self, @@ -19,40 +16,40 @@ async def get_or_add( id_rsa: str, close_existing_tunnel: bool = False, ) -> GatewayConnection: - async with self._lock: - connection = self._connections.get(hostname) - if connection is not None: - return connection - self._connections[hostname] = GatewayConnection(hostname, id_rsa, SERVER_PORT) - open_task = self._connections[hostname].open( - close_existing_tunnel=close_existing_tunnel, - ) - try: - await open_task - return self._connections[hostname] - except Exception: - async with self._lock: - self._connections.pop(hostname, None) - raise + digest = ssh_key_digest(id_rsa) + async with self._locks.setdefault(hostname, asyncio.Lock()): + cached = self._connections.get(hostname) + if cached is not None: + cached_digest, connection = cached + if cached_digest == digest: + return connection + del self._connections[hostname] + await connection.close() + connection = GatewayConnection(hostname, id_rsa, SERVER_PORT) + try: + await connection.open(close_existing_tunnel=close_existing_tunnel) + except (Exception, asyncio.CancelledError): + await connection.close() + raise + self._connections[hostname] = (digest, connection) + return connection async def remove(self, hostname: str) -> bool: - async with self._lock: - if hostname not in self._connections: + async with self._locks.setdefault(hostname, asyncio.Lock()): + cached = self._connections.pop(hostname, None) + if cached is None: return False - close_task = self._connections.pop(hostname).close() - await close_task - return True + _, connection = cached + await connection.close() + return True async def remove_all(self) -> None: - async with self._lock: - await asyncio.gather( - *(conn.close() for conn in self._connections.values()), - return_exceptions=True, - ) - self._connections = {} - - async def all(self) -> List[GatewayConnection]: - return list(self._connections.values()) + # Include hosts still opening, before their connections have been published. + hosts = set(self._connections).union(self._locks) + await asyncio.gather(*(self.remove(host) for host in hosts), return_exceptions=True) + + async def all(self) -> list[GatewayConnection]: + return [connection for _, connection in self._connections.values()] gateway_connections_pool: GatewayConnectionsPool = GatewayConnectionsPool() diff --git a/src/dstack/_internal/server/services/gateways/usage.py b/src/dstack/_internal/server/services/gateways/usage.py new file mode 100644 index 0000000000..0587f80651 --- /dev/null +++ b/src/dstack/_internal/server/services/gateways/usage.py @@ -0,0 +1,153 @@ +"""Fetch durable minute batches, commit receipts, then ACK over existing SSH connections.""" + +import asyncio +import uuid +from contextlib import asynccontextmanager, nullcontext + +import httpx +from sqlalchemy import select, text +from sqlalchemy.ext.asyncio import AsyncSession + +from dstack._internal.server.db import get_db, get_session_ctx +from dstack._internal.server.models import GatewayModel, GatewayReplicaModel +from dstack._internal.server.services.gateways.connection import GatewayConnection +from dstack._internal.server.services.usage import ingest_usage_batch +from dstack._internal.utils.logging import get_logger + +logger = get_logger(__name__) +PAGE_SIZE = 100 +MAX_PAGES = 10 +COLLECTION_TIMEOUT = 12 +_sqlite_ingestion_lock = asyncio.Lock() + + +async def collect_gateway_usage( + connection: GatewayConnection, replica_id: uuid.UUID, lock_token: uuid.UUID +) -> None: + try: + async with asyncio.timeout(COLLECTION_TIMEOUT): + async with get_session_ctx() as session: + source = await _get_source(session, connection.ip_address, replica_id, lock_token) + if source is not None: + await _collect_pages(connection, source, lock_token) + except httpx.HTTPStatusError as exc: + if exc.response.status_code not in (404, 405): + logger.warning("Usage collection HTTP failure from %s: %s", replica_id, exc) + except Exception: + logger.exception( + "Usage collection failed from %s; unacknowledged batches retained", replica_id + ) + + +async def drain_gateway_usage( + connection: GatewayConnection, + replica_id: uuid.UUID, + gateway_id: uuid.UUID, + lock_token: uuid.UUID, +) -> bool: + """Only a sealed, empty queue from the retiring replica permits termination.""" + source = replica_id, gateway_id + try: + async with asyncio.timeout(COLLECTION_TIMEOUT): + async with get_session_ctx() as session: + if ( + await _get_source(session, connection.ip_address, replica_id, lock_token) + != source + ): + return False + try: + async with connection.client() as client: + state = await client.drain_usage() + except httpx.HTTPStatusError as exc: + if exc.response.status_code in (404, 405, 503): + # An old or interrupted drain can still have published, retryable minutes. + await _collect_pages(connection, source, lock_token) + raise + if state.empty: + return True + # An open stream may outlive many minutes. Keep delivering closed pages. + caught_up = await _collect_pages(connection, source, lock_token) + if not state.sealed or not caught_up: + return False + async with connection.client() as client: + state = await client.drain_usage() + return state.sealed and state.empty + except Exception as exc: + logger.warning("Gateway replica %s drain incomplete, will retry: %r", replica_id, exc) + return False + + +async def _collect_pages( + connection: GatewayConnection, + source: tuple[uuid.UUID, uuid.UUID | None], + lock_token: uuid.UUID, +) -> bool: + replica_id, gateway_id = source + for _ in range(MAX_PAGES): + async with connection.client() as client: + page = await client.fetch_usage_batches(PAGE_SIZE) + if not page.batches: + return True + async with _ingestion_session() as session: + # The lease or source may have changed while GET was in flight. + current = await _get_source( + session, connection.ip_address, replica_id, lock_token, for_update=True + ) + if current != source: + return False + for batch in page.batches: + await ingest_usage_batch(session, replica_id, gateway_id, batch) + # The whole page is committed before any ACK can reach the Gateway. + ids = [batch.batch_id for batch in page.batches] + async with connection.client() as client: + await client.acknowledge_usage(ids) + if not page.has_more: + return True + return False + + +async def _get_source( + session: AsyncSession, + address: str, + replica_id: uuid.UUID, + lock_token: uuid.UUID, + *, + for_update: bool = False, +) -> tuple[uuid.UUID, uuid.UUID | None] | None: + # The SSH pool is keyed by address. Two active replicas at the same address or + # conflicting modern and legacy parents cannot reliably identify a batch source. + stmt = ( + select( + GatewayReplicaModel.id, + GatewayReplicaModel.lock_token, + GatewayReplicaModel.gateway_id, + GatewayModel.id, + ) + .outerjoin(GatewayModel, GatewayModel.gateway_replica_id == GatewayReplicaModel.id) + .where(GatewayReplicaModel.active == True, GatewayReplicaModel.ip_address == address) + .limit(2) + ) + if for_update: + stmt = stmt.with_for_update(key_share=True, of=GatewayReplicaModel) + rows = (await session.execute(stmt)).all() + if len(rows) != 1: + return None + source_id, token, parent, legacy_parent = rows[0] + if source_id != replica_id or token != lock_token: + return None + if parent is not None and legacy_parent is not None and parent != legacy_parent: + return None + # An unbound replica can only replay an already committed receipt. + return source_id, parent or legacy_parent + + +@asynccontextmanager +async def _ingestion_session(): + sqlite = get_db().dialect_name == "sqlite" + async with _sqlite_ingestion_lock if sqlite else nullcontext(): + async with get_session_ctx() as session: + if sqlite: + # SQLite ignores FOR UPDATE. Reserve the writer before reading the + # token so a new claim cannot slip between the check and the insert. + await session.execute(text("BEGIN IMMEDIATE")) + yield session diff --git a/src/dstack/_internal/server/services/runs/__init__.py b/src/dstack/_internal/server/services/runs/__init__.py index f9033c1f5f..7ec215a06c 100644 --- a/src/dstack/_internal/server/services/runs/__init__.py +++ b/src/dstack/_internal/server/services/runs/__init__.py @@ -19,7 +19,6 @@ ServerClientError, ) from dstack._internal.core.models.common import ApplyAction, validate_json_extra_ignore -from dstack._internal.core.models.gateways import GatewayReplicaStatus from dstack._internal.core.models.profiles import ( RetryEvent, ) @@ -57,7 +56,7 @@ from dstack._internal.server.services import events, services from dstack._internal.server.services import projects as projects_services from dstack._internal.server.services import repos as repos_services -from dstack._internal.server.services.gateways import get_gateway_replica_models +from dstack._internal.server.services.gateways import get_serving_gateway_replica_models from dstack._internal.server.services.jobs import ( check_can_attach_job_volumes, get_job_configured_volumes, @@ -159,15 +158,13 @@ def get_run_spec(run_model: RunModel) -> RunSpec: def gateway_registration_failed(run_model: RunModel) -> bool: if run_model.gateway is None: return False - running_gateway_replica_ids = { - replica.id - for replica in get_gateway_replica_models(run_model.gateway) - if replica.status == GatewayReplicaStatus.RUNNING + serving_gateway_replica_ids = { + replica.id for replica in get_serving_gateway_replica_models(run_model.gateway) } - if not running_gateway_replica_ids: + if not serving_gateway_replica_ids: return False registration_by_replica_id = {r.gateway_replica_id: r for r in run_model.service_registrations} - for replica_id in running_gateway_replica_ids: + for replica_id in serving_gateway_replica_ids: registration = registration_by_replica_id.get(replica_id) if ( registration is None diff --git a/src/dstack/_internal/server/services/runs/replicas.py b/src/dstack/_internal/server/services/runs/replicas.py index df29a65b9c..f594589d39 100644 --- a/src/dstack/_internal/server/services/runs/replicas.py +++ b/src/dstack/_internal/server/services/runs/replicas.py @@ -2,10 +2,9 @@ from typing import List, Optional, Tuple from dstack._internal.core.models.configurations import ReplicaGroup -from dstack._internal.core.models.gateways import GatewayReplicaStatus from dstack._internal.core.models.runs import JobStatus, JobTerminationReason from dstack._internal.server.models import JobModel, RunModel -from dstack._internal.server.services.gateways import get_gateway_replica_models +from dstack._internal.server.services.gateways import get_serving_gateway_replica_models from dstack._internal.server.services.jobs import ( get_job_spec, group_jobs_by_replica_latest, @@ -140,17 +139,15 @@ def is_replica_receiving_traffic(run_model: RunModel, jobs: list[JobModel]) -> b if run_model.gateway is None: # served by the in-server proxy return True - running_gateway_replica_ids = { - replica.id - for replica in get_gateway_replica_models(run_model.gateway) - if replica.status == GatewayReplicaStatus.RUNNING + serving_gateway_replica_ids = { + replica.id for replica in get_serving_gateway_replica_models(run_model.gateway) } - if not running_gateway_replica_ids: + if not serving_gateway_replica_ids: return False registration_by_replica_id = { r.gateway_replica_id: r for r in job.service_replica_registrations } - for replica_id in running_gateway_replica_ids: + for replica_id in serving_gateway_replica_ids: registration = registration_by_replica_id.get(replica_id) if registration is None or not registration.is_registered: return False diff --git a/src/tests/_internal/proxy/gateway/metering/harness.py b/src/tests/_internal/proxy/gateway/metering/harness.py index c24c3b45fe..15a7714e5b 100644 --- a/src/tests/_internal/proxy/gateway/metering/harness.py +++ b/src/tests/_internal/proxy/gateway/metering/harness.py @@ -71,6 +71,10 @@ class TestNginx(Nginx): def write_global_conf(self): pass + async def drain(self) -> bool: + # This harness forwards directly to its fixture backend and owns no Nginx workers. + return True + async def _noop(*args, **kwargs): pass diff --git a/src/tests/_internal/proxy/gateway/metering/test_scenarios.py b/src/tests/_internal/proxy/gateway/metering/test_scenarios.py index 50b769e410..63e8b3195f 100644 --- a/src/tests/_internal/proxy/gateway/metering/test_scenarios.py +++ b/src/tests/_internal/proxy/gateway/metering/test_scenarios.py @@ -98,6 +98,42 @@ async def test_two_intervals_and_ack(harness): await two_intervals(harness) +@pytest.mark.asyncio +async def test_drain_allows_open_stream_to_deliver_its_final_usage(harness): + h = harness + driver = TrafficDriver(h.gateway_url, artifact_dir=h.state) + try: + await h.backend_control(hold=["draining-stream"]) + stream = asyncio.create_task(send(h, driver, "draining-stream", stream=True)) + try: + await h.wait_backend_started("draining-stream") + async with httpx.AsyncClient(base_url=h.gateway_url, timeout=10) as control: + response = await control.post("/api/usage/drain") + assert response.json() == {"sealed": False, "empty": False} + with pytest.raises(httpx.HTTPStatusError) as exc: + await driver.send("after-fence") + assert exc.value.response.status_code == 503 + finally: + await h.backend_control(release=["draining-stream"]) + await stream + # No clock advance: the final usage-only SSE event must be present immediately. + async with httpx.AsyncClient(base_url=h.gateway_url, timeout=10) as control: + response = await control.post("/api/usage/drain") + assert response.json() == {"sealed": True, "empty": False} + (batch,) = (await h.batches())["batches"] + assert totals(batch) == expected("A") + ack = await control.post( + "/api/usage/batches/ack", json={"batch_ids": [batch["batch_id"]]} + ) + ack.raise_for_status() + assert (await control.post("/api/usage/drain")).json() == { + "sealed": True, + "empty": True, + } + finally: + await driver.close() + + @pytest.mark.asyncio async def test_selective_ack_during_traffic(harness): h = harness diff --git a/src/tests/_internal/proxy/gateway/routers/test_usage.py b/src/tests/_internal/proxy/gateway/routers/test_usage.py index 60b836cda1..b6d49cd9db 100644 --- a/src/tests/_internal/proxy/gateway/routers/test_usage.py +++ b/src/tests/_internal/proxy/gateway/routers/test_usage.py @@ -4,10 +4,20 @@ from dstack._internal.proxy.gateway.app import make_app from dstack._internal.proxy.gateway.repo.repo import GatewayProxyRepo from dstack._internal.proxy.gateway.services.metering_store import MeteringStore +from dstack._internal.proxy.gateway.services.nginx import Nginx +from dstack._internal.proxy.lib.errors import ProxyError +from dstack._internal.proxy.lib.schemas.usage import UsageKey from dstack._internal.proxy.lib.services.usage import VLLM_PROFILE from tests._internal.proxy.gateway.services.test_metering import FakeClock, record +class DrainingNginx(Nginx): + idle = True + + async def drain(self) -> bool: + return self.idle + + @pytest.mark.asyncio async def test_fetch_and_ack_preserve_active_and_reject_active_ids(tmp_path): clock = FakeClock() @@ -49,3 +59,114 @@ async def test_fetch_and_ack_preserve_active_and_reject_active_ids(tmp_path): await client.post("/api/usage/batches/ack", json={"batch_ids": []}) ).status_code == 422 await collector.close() + + +@pytest.mark.asyncio +async def test_drain_of_unused_replica_is_durable_before_profiles_are_configured(tmp_path): + path = tmp_path / "usage.json" + for restart in [False, True]: + app = make_app( + repo=GatewayProxyRepo(), metering_store=MeteringStore(path), nginx=DrainingNginx() + ) + collector = app.state.proxy_dependency_injector.get_metering() + await collector.start() + try: + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://control" + ) as client: + if restart: + await collector.configure_profiles({"s": VLLM_PROFILE}) + with pytest.raises(ProxyError) as exc: + collector.start_attempt( + UsageKey(consumer_subject_id="u", service_id="s"), VLLM_PROFILE + ) + assert exc.value.status_code == 503 + response = await client.post("/api/usage/drain") + assert response.status_code == 200 + assert response.json() == {"sealed": True, "empty": True} + assert (await client.get("/api/usage/batches")).json()["batches"] == [] + finally: + await collector.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kill", [True, False]) +async def test_traffic_accepted_by_old_nginx_worker_with_gateway_restart(tmp_path, kill): + store = MeteringStore(tmp_path / "usage.json") + nginx = DrainingNginx() + nginx.idle = False + clock = FakeClock() + app = make_app(repo=GatewayProxyRepo(), nginx=nginx, metering_store=store, clock=clock) + collector = app.state.proxy_dependency_injector.get_metering() + await collector.configure_profiles({"s": VLLM_PROFILE}) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://control" + ) as client: + assert (await client.post("/api/usage/drain")).json() == {"sealed": False, "empty": False} + # A request already accepted by the retiring worker can still reach Python. + await record(collector) + if kill: + store.close() + else: + await collector.close() + + app = make_app( + repo=GatewayProxyRepo(), nginx=nginx, metering_store=MeteringStore(store.path), clock=clock + ) + collector = app.state.proxy_dependency_injector.get_metering() + await collector.configure_profiles({"s": VLLM_PROFILE}) + try: + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://control" + ) as client: + if not kill: + # A request buffered in an old Nginx worker enters Python after restart. + await record(collector) + nginx.idle = True + result = await client.post("/api/usage/drain") + if kill: + assert result.status_code == 503 + else: + assert result.json() == {"sealed": True, "empty": False} + (batch,) = (await client.get("/api/usage/batches")).json()["batches"] + assert batch["entries"][0]["total_tokens"] == 46 + with pytest.raises(ProxyError): + await record(collector) + finally: + await collector.close() + + +@pytest.mark.asyncio +async def test_final_ack_still_requires_current_ingress_proof(tmp_path): + nginx = DrainingNginx() + app = make_app( + repo=GatewayProxyRepo(), nginx=nginx, metering_store=MeteringStore(tmp_path / "usage.json") + ) + collector = app.state.proxy_dependency_injector.get_metering() + await collector.configure_profiles({"s": VLLM_PROFILE}) + try: + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://control" + ) as client: + await record(collector) + assert (await client.post("/api/usage/drain")).json() == { + "sealed": True, + "empty": False, + } + (batch,) = (await client.get("/api/usage/batches")).json()["batches"] + ack = await client.post( + "/api/usage/batches/ack", json={"batch_ids": [batch["batch_id"]]} + ) + ack.raise_for_status() + nginx.idle = False + assert (await client.post("/api/usage/drain")).json() == { + "sealed": False, + "empty": False, + } + nginx.idle = True + assert (await client.post("/api/usage/drain")).json() == { + "sealed": True, + "empty": True, + } + finally: + await collector.close() diff --git a/src/tests/_internal/proxy/gateway/services/test_metering.py b/src/tests/_internal/proxy/gateway/services/test_metering.py index f1cdf112fc..5c34d480ea 100644 --- a/src/tests/_internal/proxy/gateway/services/test_metering.py +++ b/src/tests/_internal/proxy/gateway/services/test_metering.py @@ -50,6 +50,168 @@ async def record(collector, user="u", service="s", usage=None): @pytest.mark.asyncio class TestMeteringCollector: + async def test_drain_finishes_admitted_attempts_and_replays_final_minute(self, tmp_path): + path = tmp_path / "usage.json" + clock = FakeClock() + store = MeteringStore(path) + c = MeteringCollector(store, clock=clock, profiles={"s": VLLM_PROFILE}) + await c.start() + try: + await record(c) + clock.advance() + await c.rotate_if_due() + (previous,) = (await c.get_batches()).batches + saved = store.load() + assert saved is not None + final_minute = saved.active_batch + key = UsageKey(consumer_subject_id="u", service_id="s") + attempt = c.start_attempt(key, VLLM_PROFILE) + attempt.mark_dispatched() + assert (await c.drain()).model_dump() == {"sealed": False, "empty": False} + with pytest.raises(ProxyError) as exc: + c.start_attempt(key, VLLM_PROFILE) + assert exc.value.status_code == 503 + await c.acknowledge([previous.batch_id]) + assert not (await c.drain()).empty + attempt.observe_usage(dict(prompt_tokens=20, completion_tokens=3, total_tokens=23)) + await attempt.finish() + assert (await c.drain()).model_dump() == {"sealed": True, "empty": False} + (batch,) = (await c.get_batches()).batches + assert (batch.batch_id, batch.interval_start, batch.interval_end) == ( + final_minute.batch_id, + final_minute.interval_start, + final_minute.interval_end, + ) + assert batch.entries[0].total_tokens == 23 + finally: + await c.close() + + # Restart within the sealed UTC minute. Old ACKs cannot remove the final batch. + c = MeteringCollector(MeteringStore(path), clock=clock, profiles={"s": VLLM_PROFILE}) + await c.start() + try: + await c.rotate_if_due() + await c.acknowledge([previous.batch_id]) + assert (await c.get_batches()).batches == [batch] + with pytest.raises(ProxyError): + c.start_attempt(key, VLLM_PROFILE) + await c.acknowledge([batch.batch_id]) + assert (await c.drain()).model_dump() == {"sealed": True, "empty": True} + finally: + await c.close() + + async def test_drain_fails_closed_across_disk_failure_and_ack_retry(self, tmp_path): + path = tmp_path / "usage.json" + store = FailingStore(path) + c = MeteringCollector(store, clock=FakeClock(), profiles={"s": VLLM_PROFILE}) + await c.start() + try: + await record(c) + store.fail = True + with pytest.raises(OSError): + await c.drain() + with pytest.raises(ProxyError): + await record(c) + assert not (await c.get_batches()).batches + store.fail = False + assert (await c.drain()).model_dump() == {"sealed": True, "empty": False} + (batch,) = (await c.get_batches()).batches + store.fail = True + with pytest.raises(OSError): + await c.acknowledge([batch.batch_id]) + store.fail = False + assert not (await c.drain()).empty + assert (await c.get_batches()).batches == [batch] + await c.acknowledge([batch.batch_id]) + assert (await c.drain()).empty + finally: + store.fail = False + await c.close() + + async def test_restart_with_unresolved_drain_keeps_admission_and_deletion_fenced( + self, tmp_path + ): + path = tmp_path / "usage.json" + clock = FakeClock() + store = MeteringStore(path) + c = MeteringCollector(store, clock=clock, profiles={"s": VLLM_PROFILE}) + await c.start() + key = UsageKey(consumer_subject_id="u", service_id="s") + c.start_attempt(key, VLLM_PROFILE).mark_dispatched() + assert not (await c.drain()).sealed + # Abrupt loss of the process, without graceful request finalization. + store.close() + for _ in range(2): + c = MeteringCollector(MeteringStore(path), clock=clock, profiles={"s": VLLM_PROFILE}) + await c.start() + try: + with pytest.raises(ProxyError) as exc: + await c.drain() + assert exc.value.status_code == 503 + with pytest.raises(ProxyError): + c.start_attempt(key, VLLM_PROFILE) + finally: + await c.close() + + async def test_cancelled_drain_persists_final_batch_before_unlock(self, tmp_path, monkeypatch): + clock = FakeClock() + store = MeteringStore(tmp_path / "usage.json") + c = MeteringCollector(store, clock=clock, profiles={"s": VLLM_PROFILE}) + await c.start() + await record(c) + writing, release = asyncio.Event(), asyncio.Event() + save = store.save + + async def delay_save(state): + writing.set() + await release.wait() + await save(state) + + monkeypatch.setattr(store, "save", delay_save) + drain = asyncio.create_task(c.drain()) + await writing.wait() + drain.cancel() + await asyncio.sleep(0) + with pytest.raises(ProxyError): + await record(c) + release.set() + with pytest.raises(asyncio.CancelledError): + await drain + page = await c.get_batches() + assert len(page.batches) == 1 + # Inspect the result after abrupt process loss without an extra close/checkpoint. + store.close() + c = MeteringCollector(MeteringStore(store.path), clock=clock) + await c.start() + try: + assert await c.get_batches() == page + assert (await c.drain()).model_dump() == {"sealed": True, "empty": False} + finally: + await c.close() + + async def test_interrupted_checkpoint_cannot_certify_a_seal(self, tmp_path, monkeypatch): + store = MeteringStore(tmp_path / "usage.json") + c = MeteringCollector(store, clock=FakeClock(), profiles={"s": VLLM_PROFILE}) + await c.start() + try: + await record(c) + with monkeypatch.context() as injection: + + async def stop_writer(state): + raise asyncio.CancelledError + + injection.setattr(store, "save", stop_writer) + with pytest.raises(asyncio.CancelledError): + await c.drain() + with pytest.raises(asyncio.CancelledError): + await c.drain() + assert not (await c.get_batches()).batches + assert (await c.drain()).model_dump() == {"sealed": True, "empty": False} + (batch,) = (await c.get_batches()).batches + assert batch.entries[0].total_tokens == 23 + finally: + await c.close() + async def test_ack_does_not_clear_active(self, tmp_path): clock = FakeClock() collector = MeteringCollector( @@ -72,6 +234,38 @@ async def test_ack_does_not_clear_active(self, tmp_path): assert b.batch_id != a.batch_id await collector.close() + async def test_cancelled_ack_cannot_resurrect_a_durably_deleted_final_batch( + self, tmp_path, monkeypatch + ): + store = MeteringStore(tmp_path / "usage.json") + c = MeteringCollector(store, clock=FakeClock(), profiles={"s": VLLM_PROFILE}) + await c.start() + try: + await record(c) + await c.drain() + (batch,) = (await c.get_batches()).batches + saved, release = asyncio.Event(), asyncio.Event() + save = store.save + + async def lose_reply(state): + await save(state) + saved.set() + await release.wait() + + monkeypatch.setattr(store, "save", lose_reply) + ack = asyncio.create_task(c.acknowledge([batch.batch_id])) + await saved.wait() + ack.cancel() + release.set() + with pytest.raises(asyncio.CancelledError): + await ack + assert (await c.drain()).empty + await c.checkpoint() + state = store.load() + assert state is not None and state.pending_batches == [] + finally: + await c.close() + async def test_ack_preserves_other_pending(self, tmp_path): clock = FakeClock() c = MeteringCollector( diff --git a/src/tests/_internal/proxy/gateway/services/test_nginx_drain.py b/src/tests/_internal/proxy/gateway/services/test_nginx_drain.py new file mode 100644 index 0000000000..3806dcac3b --- /dev/null +++ b/src/tests/_internal/proxy/gateway/services/test_nginx_drain.py @@ -0,0 +1,210 @@ +import asyncio +import os +import signal +import socket +import subprocess +import tempfile +from pathlib import Path + +import httpx +import psutil +import pytest + +from dstack._internal.proxy.gateway.services import nginx as nginx_service +from dstack._internal.proxy.gateway.services.nginx import ( + LocationConfig, + Nginx, + ReplicaConfig, + ServiceConfig, +) + + +@pytest.mark.asyncio +async def test_missing_worker_proof_survives_reload_failure_and_gateway_restart( + tmp_path, system_mocks, monkeypatch +): + monkeypatch.setattr(nginx_service, "NGINX_DRAIN_SOCKET", tmp_path / "missing.sock") + monkeypatch.setattr(nginx_service, "NGINX_PID_FILE", tmp_path / "nginx.pid") + (tmp_path / "sites-enabled").mkdir() + controller = Nginx(tmp_path) + controller.write_global_conf() + public_config = (tmp_path / "nginx.conf").read_bytes() + system_mocks.reload_nginx.side_effect = nginx_service.UnexpectedProxyError("reload failed") + with pytest.raises(nginx_service.UnexpectedProxyError, match="reload failed"): + await controller.drain() + # Restarting Nginx itself must already load the fence, even before the Gateway retries. + draining_config = (tmp_path / "nginx.conf").read_bytes() + assert draining_config != public_config + + system_mocks.reload_nginx.side_effect = None + restarted = Nginx(tmp_path) + restarted.write_global_conf() + assert (tmp_path / "nginx.conf").read_bytes() == draining_config + assert not await restarted.drain() + + +@pytest.mark.asyncio +@pytest.mark.skipif( + not os.environ.get("DS002_NGINX"), reason="set DS002_NGINX to a local nginx binary" +) +@pytest.mark.parametrize("websocket", [False, True], ids=["stream", "websocket"]) +async def test_ordinary_response_finishes_before_nginx_is_drained( + tmp_path, monkeypatch, record_property, websocket +): + # A real master and two generations of workers are required to observe a connection + # that already bypassed the Python gateway. Launch only a disposable, unprivileged instance. + executable = os.environ["DS002_NGINX"] + release = asyncio.Event() + proc = None + with tempfile.TemporaryDirectory(dir="/tmp") as sock_dir: + sockets = Path(sock_dir) + probe_socket = sockets / "drain.sock" + backend_socket = sockets / "backend.sock" + pid = tmp_path / "nginx.pid" + sites = tmp_path / "sites-enabled" + sites.mkdir() + monkeypatch.setattr(nginx_service, "sudo", lambda: []) + read_resource = nginx_service.read_package_resource + + def resource(name): + template = read_resource(name) + return ( + template.replace("user www-data;", "") + .replace("pid /run/nginx.pid;", f"pid {pid};") + .replace("/etc/nginx/mime.types", f"{tmp_path}/mime.types") + .replace("/etc/nginx/", f"{tmp_path}/") + .replace("/var/log/nginx/", f"{tmp_path}/") + .replace("/tmp/dstack-dummy-nginx.sock", str(sockets / "dummy.sock")) + .replace( + "http {", + f"http {{\nclient_body_temp_path {tmp_path}/body;\n" + f"proxy_temp_path {tmp_path}/proxy;", + ) + ) + + monkeypatch.setattr(nginx_service, "read_package_resource", resource) + monkeypatch.setattr( + Nginx, "reload", staticmethod(lambda: proc and proc.send_signal(signal.SIGHUP)) + ) + (tmp_path / "mime.types").touch() + controller = Nginx(tmp_path) + # Override only OS paths that belong to the separately launched master. + monkeypatch.setattr(nginx_service, "NGINX_PID_FILE", pid) + monkeypatch.setattr(nginx_service, "NGINX_DRAIN_SOCKET", probe_socket) + with socket.socket(socket.AF_INET6) as reservation: + reservation.bind(("::1", 0)) + port = reservation.getsockname()[1] + # IPv6 loopback exercises the public ACL, while the model proxy uses exactly 127.0.0.1. + site = ServiceConfig( + domain="service.test", + project_name="p", + https=False, + auth=False, + client_max_body_size=1024, + access_log_path=tmp_path / "access.log", + limit_req_zones=[], + locations=[LocationConfig(prefix="/")], + replicas=[ReplicaConfig(id="test", socket=backend_socket, port=8000)], + proxy_buffering=False, + read_timeout=10, + ) + (sites / "443-service.test.conf").write_text( + site.render().replace("listen 80;", f"listen [::1]:{port};\nlisten 127.0.0.1:{port};") + ) + + async def upstream(reader, writer): + request = await reader.readuntil(b"\r\n\r\n") + upgraded = websocket and request.startswith(b"GET /held ") + if upgraded: + # RFC 6455 example nonce, followed by complete unmasked server text frames. + writer.write( + b"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n" + b"Connection: Upgrade\r\nSec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\n\r\n\x81\x01A" + ) + else: + writer.write(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nA") + await writer.drain() + if request.startswith(b"GET /held "): + await release.wait() + writer.write(b"\x81\x01B\x88\x02\x03\xe8" if upgraded else b"B") + await writer.drain() + writer.close() + await writer.wait_closed() + + backend = await asyncio.start_unix_server(upstream, path=str(backend_socket)) + controller.write_global_conf() + command = [ + executable, + "-p", + str(tmp_path), + "-c", + str(tmp_path / "nginx.conf"), + "-e", + str(tmp_path / "error.log"), + "-g", + "daemon off;", + ] + try: + proc = subprocess.Popen(command) + async with ( + backend, + httpx.AsyncClient(base_url=f"http://[::1]:{port}", trust_env=False) as client, + httpx.AsyncClient( + base_url=f"http://127.0.0.1:{port}", trust_env=False + ) as internal, + asyncio.timeout(15), + ): + while True: + assert proc.poll() is None, (tmp_path / "error.log").read_text() + try: + held, connection = await asyncio.open_connection("::1", port) + break + except ConnectionRefusedError: + await asyncio.sleep(0.02) + try: + upgrade = ( + b"Connection: Upgrade\r\nUpgrade: websocket\r\n" + b"Sec-WebSocket-Version: 13\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n" + ) + connection.write( + b"GET /held HTTP/1.1\r\nHost: service.test\r\n" + + (upgrade if websocket else b"Connection: close\r\n") + + b"\r\n" + ) + headers = await held.readuntil(b"\r\n\r\n") + assert headers.startswith(b"HTTP/1.1 101" if websocket else b"HTTP/1.1 200") + frame = b"\x81\x01" if websocket else b"" + assert await held.readexactly(len(frame) + 1) == frame + b"A" + assert not await controller.drain() + while (await client.get("/new")).status_code == 200: + await asyncio.sleep(0.02) + status = (await client.get("/new")).status_code + assert status == 403 + assert (await internal.get("/accepted-model-hop")).content == b"AB" + restarted = Nginx(tmp_path) + restarted.write_global_conf() + assert not await restarted.drain() + children = psutil.Process(proc.pid).children + record_property("master_pid", proc.pid) + record_property("workers_while_held", [p.pid for p in children()]) + record_property("fresh_external_status", status) + release.set() + assert await held.readexactly(len(frame) + 1) == frame + b"B" + if websocket: + assert ( + await held.readexactly(4) == b"\x88\x02\x03\xe8" + ) # Normal close, 1000. + finally: + connection.close() + await connection.wait_closed() + while not await restarted.drain(): + await asyncio.sleep(0.02) + record_property("workers_at_completion", [p.pid for p in children()]) + assert (await client.get("/new")).status_code == 403 + finally: + release.set() + backend.close() + await backend.wait_closed() + if proc is not None and proc.poll() is None: + proc.terminate() + await asyncio.to_thread(proc.wait, 5) diff --git a/src/tests/_internal/server/background/pipeline_tasks/runs/test_active.py b/src/tests/_internal/server/background/pipeline_tasks/runs/test_active.py index a289e1a5f0..82b4da1ac3 100644 --- a/src/tests/_internal/server/background/pipeline_tasks/runs/test_active.py +++ b/src/tests/_internal/server/background/pipeline_tasks/runs/test_active.py @@ -364,9 +364,18 @@ async def test_does_not_terminate_run_when_one_running_replica_has_not_attempted assert run.termination_reason is None assert run.lock_token is None - async def test_terminates_run_ignoring_registration_on_non_running_replica( - self, test_db, session: AsyncSession, worker: RunWorker + @pytest.mark.parametrize( + "retiring_status", [GatewayReplicaStatus.TERMINATING, GatewayReplicaStatus.RUNNING] + ) + async def test_terminates_run_ignoring_registration_on_retiring_replica( + self, + test_db, + session: AsyncSession, + worker: RunWorker, + mock_gateway_connection, + retiring_status: GatewayReplicaStatus, ) -> None: + mock_gateway_connection.return_value.get_stats.return_value = None project = await create_project(session=session) user = await create_user(session=session) repo = await create_repo(session=session, project_id=project.id) @@ -380,15 +389,14 @@ async def test_terminates_run_ignoring_registration_on_non_running_replica( gateway_replica_running = await create_gateway_replica( session=session, gateway_id=gateway.id, backend=backend, replica_num=0 ) - # Terminated replica successfully registered before going away — should be ignored, - # since only currently running replicas count towards the predicate. gateway_replica_terminating = await create_gateway_replica( session=session, gateway_id=gateway.id, backend=backend, replica_num=1, - status=GatewayReplicaStatus.TERMINATING, + status=retiring_status, ) + gateway_replica_terminating.scale_in = retiring_status == GatewayReplicaStatus.RUNNING run = await create_run( session=session, project=project, @@ -1545,10 +1553,20 @@ async def test_service_rolling_deployment_scale_down_old_unregistered( assert old_job.status == JobStatus.TERMINATING assert old_job.termination_reason == JobTerminationReason.SCALED_DOWN - @pytest.mark.parametrize("failed_registration", [False, True]) - async def test_service_rolling_deployment_keeps_old_replica_until_new_replica_registered_with_gateway( - self, test_db, session: AsyncSession, worker: RunWorker, failed_registration: bool + @pytest.mark.parametrize( + ("failed_registration", "scale_in"), + [(False, False), (True, False), (False, True)], + ) + async def test_service_rolling_deployment_waits_for_registrations_on_serving_gateway_replicas( + self, + test_db, + session: AsyncSession, + worker: RunWorker, + mock_gateway_connection, + failed_registration: bool, + scale_in: bool, ) -> None: + mock_gateway_connection.return_value.get_stats.return_value = None project = await create_project(session=session) user = await create_user(session=session) repo = await create_repo(session=session, project_id=project.id) @@ -1565,6 +1583,7 @@ async def test_service_rolling_deployment_keeps_old_replica_until_new_replica_re gateway_replica_2 = await create_gateway_replica( session=session, gateway_id=gateway.id, backend=backend, replica_num=1 ) + gateway_replica_2.scale_in = scale_in run_spec = get_run_spec( repo_id=repo.name, run_name="service-run", @@ -1653,7 +1672,7 @@ async def test_service_rolling_deployment_keeps_old_replica_until_new_replica_re await session.refresh(old_job) await session.refresh(new_job) - assert old_job.status == JobStatus.RUNNING + assert old_job.status == (JobStatus.TERMINATING if scale_in else JobStatus.RUNNING) assert new_job.status == JobStatus.RUNNING async def test_service_rolling_deployment_scales_down_old_replica_once_new_replica_registered_with_gateway( diff --git a/src/tests/_internal/server/background/pipeline_tasks/test_gateway_replicas.py b/src/tests/_internal/server/background/pipeline_tasks/test_gateway_replicas.py index 5e61a972a1..5b584281ee 100644 --- a/src/tests/_internal/server/background/pipeline_tasks/test_gateway_replicas.py +++ b/src/tests/_internal/server/background/pipeline_tasks/test_gateway_replicas.py @@ -25,6 +25,7 @@ ) from dstack._internal.core.models.runs import JobStatus, RunStatus, ServiceSpec from dstack._internal.proxy.gateway.schemas.services import ServiceListItem, ServiceListReplicaItem +from dstack._internal.proxy.lib.schemas.usage import UsageBatchPage, UsageDrainResponse from dstack._internal.server import settings from dstack._internal.server.background.pipeline_tasks.gateway_replicas import ( GatewayReplicaFetcher, @@ -36,6 +37,8 @@ GatewayReplicaModel, ServiceRegistrationModel, ServiceReplicaRegistrationModel, + UsageBatchModel, + UsageCounterModel, ) from dstack._internal.server.testing.common import ( AsyncContextManager, @@ -58,6 +61,7 @@ mock_lease, ) from dstack._internal.utils.common import get_current_datetime +from tests._internal.server.services.test_usage import batch from tests._internal.utils.test_ssh import PRIVATE_KEY, PUBLIC_KEY @@ -670,6 +674,31 @@ async def test_submitted_to_terminated_when_scaled_in( @pytest.mark.asyncio @pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) class TestGatewayReplicaWorkerRunning: + async def test_collects_minute_batch_for_claimed_replica( + self, test_db, session, worker, mock_gateway_connection + ): + project = await create_project(session) + backend = await create_backend(session, project.id) + gateway = await create_gateway( + session, project.id, backend.id, status=GatewayStatus.RUNNING + ) + replica = await create_gateway_replica(session, backend, gateway_id=gateway.id) + _lock_replica(replica) + await session.commit() + mock_gateway_connection.return_value.ip_address = replica.ip_address + client = _get_client_mock(mock_gateway_connection) + client.fetch_usage_batches.return_value = UsageBatchPage(batches=[batch()]) + client.list_services.return_value = [] + + await worker.process(_replica_to_pipeline_item(replica)) + + receipt = (await session.scalars(select(UsageBatchModel))).one_or_none() + assert receipt is not None + assert (receipt.gateway_replica_id, receipt.gateway_id) == (replica.id, gateway.id) + counter = (await session.scalars(select(UsageCounterModel))).one() + assert counter.usage_baches_id == receipt.id and counter.total_tokens == 23 + client.acknowledge_usage.assert_awaited_once_with(["batch-1"]) + @pytest.mark.parametrize( "gateway_status,to_be_deleted", [ @@ -684,6 +713,7 @@ async def test_running_to_terminating( test_db, session: AsyncSession, worker: GatewayReplicaWorker, + mock_gateway_connection, gateway_status: GatewayStatus, to_be_deleted: bool, legacy_replica: bool, @@ -726,8 +756,14 @@ async def test_running_to_terminating( assert replica.status == GatewayReplicaStatus.TERMINATING assert replica.active is False + @pytest.mark.parametrize("waiting", ["inflight", "ack_failed", "unreachable", "drained"]) async def test_running_to_terminating_when_scaled_in( - self, test_db, session: AsyncSession, worker: GatewayReplicaWorker + self, + test_db, + session: AsyncSession, + worker: GatewayReplicaWorker, + mock_gateway_connection, + waiting, ): project = await create_project(session=session) backend = await create_backend(session=session, project_id=project.id) @@ -747,13 +783,26 @@ async def test_running_to_terminating_when_scaled_in( replica.scale_in = True _lock_replica(replica) await session.commit() + client = _get_client_mock(mock_gateway_connection) + client.drain_usage.return_value = UsageDrainResponse( + sealed=waiting != "inflight", empty=waiting == "drained" + ) + if waiting == "ack_failed": + client.fetch_usage_batches.return_value = UsageBatchPage(batches=[batch()]) + client.acknowledge_usage.side_effect = TimeoutError("ACK timed out") + elif waiting == "unreachable": + client.drain_usage.side_effect = TimeoutError("Gateway is unavailable") await worker.process(_replica_to_pipeline_item(replica)) await session.refresh(replica) - assert replica.status == GatewayReplicaStatus.TERMINATING - assert replica.active is False - assert replica.status_message == "Scaled in" + if waiting == "drained": + assert replica.status == GatewayReplicaStatus.TERMINATING + assert not replica.active and replica.status_message == "Scaled in" + else: + assert replica.status == GatewayReplicaStatus.RUNNING + assert replica.active and replica.scale_in + assert replica.lock_token is None def _get_client_mock(mock_gateway_connection: AsyncMock) -> AsyncMock: @@ -1414,12 +1463,14 @@ async def test_unregisters_replicas_of_dangling_service_without_extra_gateway_ca "Service replica unregistered", } - async def test_no_gateway_calls_when_state_already_in_sync( + @pytest.mark.parametrize("usage_unavailable", [False, True]) + async def test_reconciles_in_sync_registrations_without_gateway_writes( self, test_db, session: AsyncSession, worker: GatewayReplicaWorker, mock_gateway_connection: AsyncMock, + usage_unavailable: bool, ): project = await create_project(session=session) user = await create_user(session=session) @@ -1444,6 +1495,8 @@ async def test_no_gateway_calls_when_state_already_in_sync( await session.commit() client_mock = _get_client_mock(mock_gateway_connection) + if usage_unavailable: + client_mock.fetch_usage_batches.side_effect = TimeoutError("Gateway usage timed out") client_mock.list_services.return_value = [ ServiceListItem( id=run.id.hex, @@ -1463,7 +1516,7 @@ async def test_no_gateway_calls_when_state_already_in_sync( client_mock.submit_gateway_config.assert_not_called() # Registration records are still (re)created to reflect the confirmed state, - # even though no gateway calls were needed this tick. + # even when the usage endpoint is unavailable. service_registration = ( await session.execute( select(ServiceRegistrationModel).where( diff --git a/src/tests/_internal/server/background/pipeline_tasks/test_jobs_running.py b/src/tests/_internal/server/background/pipeline_tasks/test_jobs_running.py index e5b115ce44..064b74169d 100644 --- a/src/tests/_internal/server/background/pipeline_tasks/test_jobs_running.py +++ b/src/tests/_internal/server/background/pipeline_tasks/test_jobs_running.py @@ -2475,11 +2475,15 @@ async def test_does_not_terminate_job_when_gateway_replica_has_not_attempted_reg assert job.status == JobStatus.RUNNING assert job.termination_reason is None - async def test_terminates_job_ignoring_registration_on_non_running_replica( + @pytest.mark.parametrize( + "retiring_status", [GatewayReplicaStatus.TERMINATING, GatewayReplicaStatus.RUNNING] + ) + async def test_terminates_job_ignoring_registration_on_retiring_replica( self, test_db, session: AsyncSession, worker: JobRunningWorker, + retiring_status: GatewayReplicaStatus, ) -> None: project = await create_project(session=session) user = await create_user(session=session) @@ -2494,15 +2498,14 @@ async def test_terminates_job_ignoring_registration_on_non_running_replica( gateway_replica_running = await create_gateway_replica( session=session, gateway_id=gateway.id, backend=backend, replica_num=0 ) - # Terminated replica successfully registered before going away — should be ignored, - # since only currently running replicas count towards the predicate. gateway_replica_terminating = await create_gateway_replica( session=session, gateway_id=gateway.id, backend=backend, replica_num=1, - status=GatewayReplicaStatus.TERMINATING, + status=retiring_status, ) + gateway_replica_terminating.scale_in = retiring_status == GatewayReplicaStatus.RUNNING run = await create_run( session=session, project=project, diff --git a/src/tests/_internal/server/background/scheduled_tasks/test_usage.py b/src/tests/_internal/server/background/scheduled_tasks/test_usage.py deleted file mode 100644 index 73be0e3b4d..0000000000 --- a/src/tests/_internal/server/background/scheduled_tasks/test_usage.py +++ /dev/null @@ -1,217 +0,0 @@ -import asyncio -import contextvars -from contextlib import asynccontextmanager -from unittest.mock import AsyncMock - -import httpx -import pytest -from sqlalchemy import func, select - -from dstack._internal.proxy.lib.schemas.usage import UsageAckResponse, UsageBatchPage -from dstack._internal.server.background.scheduled_tasks import usage -from dstack._internal.server.models import ( - BackendModel, - GatewayModel, - UsageBatchModel, - UsageCounterModel, -) -from dstack._internal.server.testing.common import ( - create_backend, - create_gateway, - create_gateway_replica, - create_project, - create_user, -) -from tests._internal.server.services.test_usage import batch - -DB_SESSION = contextvars.ContextVar("usage_test_db_session", default=False) - - -class Client: - def __init__(self, test_db, items): - self.db = test_db - self.items = items - self.acks = [] - self.fetches = 0 - self.lose_ack = False - - def assert_no_db_connection(self): - # Async sessions are tracked explicitly below, independent of pool implementation. - assert not DB_SESSION.get() - - async def fetch_usage_batches(self, limit=100): - self.assert_no_db_connection() - self.fetches += 1 - return UsageBatchPage(batches=self.items[:limit], has_more=len(self.items) > limit) - - async def acknowledge_usage(self, ids): - self.assert_no_db_connection() - # The in-memory SQLite fixture shares one physical connection. Serialize this - # test-only observation so closing it cannot roll back another collector's work. - async with usage._ingestion_lock(): - async with self.db.get_session() as session: - committed = set(await session.scalars(select(UsageBatchModel.batch_id))) - assert set(ids) <= committed - self.acks.append(ids) - self.items = [b for b in self.items if b.batch_id not in ids] - if self.lose_ack: - self.lose_ack = False - raise httpx.ReadError("ACK reply lost") - return UsageAckResponse(acknowledged_batch_ids=ids) - - -def setup(monkeypatch, db, client, ip_address="1.1.1.1"): - original = usage.get_session_ctx - - @asynccontextmanager - async def tracked(): - token = DB_SESSION.set(True) - try: - async with original() as session: - yield session - finally: - DB_SESSION.reset(token) - - monkeypatch.setattr(usage, "get_session_ctx", tracked) - - @asynccontextmanager - async def connection_client(): - yield client - - connection = type( - "Connection", (), {"ip_address": ip_address, "client": staticmethod(connection_client)} - )() - monkeypatch.setattr( - usage.gateway_connections_pool, "all", AsyncMock(return_value=[connection]) - ) - return connection - - -async def registered(session): - user = await create_user(session) - project = await create_project(session, owner=user) - backend = await create_backend(session, project.id) - gateway = await create_gateway(session, project.id, backend.id) - return await create_gateway_replica(session, backend, gateway_id=gateway.id) - - -@pytest.mark.asyncio -async def test_commit_before_ack_and_lost_reply(session, test_db, monkeypatch): - await registered(session) - client = Client(test_db, [batch()]) - setup(monkeypatch, test_db, client) - client.lose_ack = True - await usage.collect_gateway_usage() - # Simulate a retry of the same already committed batch. - client.items = [batch()] - await usage.collect_gateway_usage() - async with test_db.get_session() as s: - assert await s.scalar(select(func.count()).select_from(UsageCounterModel)) == 1 - assert client.acks == [["batch-1"], ["batch-1"]] - - -@pytest.mark.asyncio -async def test_failed_transaction_sends_no_ack(session, test_db, monkeypatch): - await registered(session) - client = Client(test_db, [batch()]) - setup(monkeypatch, test_db, client) - original = usage.ingest_usage_batch - - async def fail(*args, **kwargs): - await original(*args, **kwargs) - raise RuntimeError("Injected transaction failure") - - monkeypatch.setattr(usage, "ingest_usage_batch", fail) - await usage.collect_gateway_usage() - assert not client.acks - async with test_db.get_session() as s: - assert await s.scalar(select(func.count()).select_from(UsageBatchModel)) == 0 - - -@pytest.mark.asyncio -async def test_conflict_never_acknowledged(session, test_db, monkeypatch): - replica = await registered(session) - client = Client(test_db, [batch(tokens=4)]) - setup(monkeypatch, test_db, client) - async with test_db.get_session() as s: - await usage.ingest_usage_batch(s, replica.id, replica.gateway_id, batch()) - await s.commit() - await usage.collect_gateway_usage() - assert not client.acks and client.items - - -@pytest.mark.asyncio -async def test_page_budget_and_overlapping_collectors(session, test_db, monkeypatch): - await registered(session) - client = Client(test_db, [batch(f"b-{i}", i) for i in range(5)]) - setup(monkeypatch, test_db, client) - monkeypatch.setattr(usage, "PAGE_SIZE", 1) - monkeypatch.setattr(usage, "MAX_PAGES", 2) - await usage.collect_gateway_usage() - assert len(client.items) == 3 and client.fetches == 2 - await asyncio.gather(usage.collect_gateway_usage(), usage.collect_gateway_usage()) - await ( - usage.collect_gateway_usage() - ) # Overlapping pages may replay; a later tick drains the rest. - async with test_db.get_session() as s: - assert await s.scalar(select(func.count()).select_from(UsageBatchModel)) == 5 - - -@pytest.mark.asyncio -async def test_old_gateway_skipped_without_stats_calls(session, test_db, monkeypatch): - await registered(session) - client = Client(test_db, []) - setup(monkeypatch, test_db, client) - - async def unavailable(limit=100): - response = httpx.Response( - 404, request=httpx.Request("GET", "http://gateway/api/usage/batches") - ) - response.raise_for_status() - - monkeypatch.setattr(client, "fetch_usage_batches", unavailable) - await usage.collect_gateway_usage() - assert not client.acks - - -@pytest.mark.asyncio -async def test_multiple_replicas_and_legacy_parent(session, test_db, monkeypatch): - first = await registered(session) - backend = await session.get(BackendModel, first.backend_id) - second = await create_gateway_replica( - session, backend, gateway_id=first.gateway_id, ip_address="2.2.2.2" - ) - legacy = await create_gateway_replica(session, backend, ip_address="3.3.3.3") - parent = await session.get(GatewayModel, first.gateway_id) - parent.gateway_replica_id = legacy.id - await session.commit() - clients, connections = [], [] - for replica in (first, second, legacy): - assert replica.ip_address is not None - client = Client(test_db, [batch()]) - connection = setup(monkeypatch, test_db, client, ip_address=replica.ip_address) - clients.append(client) - connections.append(connection) - monkeypatch.setattr(usage.gateway_connections_pool, "all", AsyncMock(return_value=connections)) - await usage.collect_gateway_usage() - async with test_db.get_session() as s: - rows = (await s.scalars(select(UsageBatchModel))).all() - assert {row.gateway_replica_id for row in rows} == {first.id, second.id, legacy.id} - assert {row.gateway_id for row in rows} == {first.gateway_id} - assert all(client.acks == [["batch-1"]] for client in clients) - - -@pytest.mark.asyncio -async def test_unbound_or_ambiguous_source_is_not_acknowledged(session, test_db, monkeypatch): - replica = await registered(session) - replica.gateway_id = None - await session.commit() - client = Client(test_db, [batch()]) - setup(monkeypatch, test_db, client) - await usage.collect_gateway_usage() - assert not client.acks - backend = await session.get(BackendModel, replica.backend_id) - await create_gateway_replica(session, backend, ip_address=replica.ip_address) - before = client.fetches - await usage.collect_gateway_usage() - assert client.fetches == before and not client.acks diff --git a/src/tests/_internal/server/conftest.py b/src/tests/_internal/server/conftest.py index 9459c377c4..201d657a83 100644 --- a/src/tests/_internal/server/conftest.py +++ b/src/tests/_internal/server/conftest.py @@ -6,6 +6,7 @@ import httpx import pytest +from dstack._internal.proxy.lib.schemas.usage import UsageBatchPage, UsageDrainResponse from dstack._internal.server.main import app from dstack._internal.server.services import encryption as encryption # import for side-effect from dstack._internal.server.services import logs as logs_services @@ -61,6 +62,10 @@ def mock_gateway_connection() -> Generator[AsyncMock, None, None]: with patch( "dstack._internal.server.services.gateways.gateway_connections_pool.get_or_add" ) as get_conn_mock: + get_conn_mock.return_value.ip_address = "1.1.1.1" get_conn_mock.return_value.client = Mock() get_conn_mock.return_value.client.return_value = AsyncMock() + client = get_conn_mock.return_value.client.return_value.__aenter__.return_value + client.fetch_usage_batches.return_value = UsageBatchPage(batches=[]) + client.drain_usage.return_value = UsageDrainResponse(sealed=True, empty=True) yield get_conn_mock diff --git a/src/tests/_internal/server/services/gateways/test_gateways.py b/src/tests/_internal/server/services/gateways/test_gateways.py index 78cecf9036..29a3d4158b 100644 --- a/src/tests/_internal/server/services/gateways/test_gateways.py +++ b/src/tests/_internal/server/services/gateways/test_gateways.py @@ -6,8 +6,17 @@ from dstack._internal import settings as core_settings from dstack._internal.core.backends.base.compute import get_dstack_gateway_install_command +from dstack._internal.core.models.configurations import ServiceConfiguration +from dstack._internal.core.models.gateways import GatewayReplicaStatus, GatewayStatus from dstack._internal.proxy.gateway.const import SERVICE_SCALING_WINDOWS from dstack._internal.proxy.gateway.schemas.stats import Stat +from dstack._internal.server.background.pipeline_tasks.runs import _load_gateway_stats +from dstack._internal.server.models import ( + GatewayModel, + GatewayReplicaModel, + ProjectModel, + RunModel, +) from dstack._internal.server.services import gateways from dstack._internal.server.services.gateways import ( _merge_per_window_stats, @@ -18,9 +27,50 @@ create_gateway, create_gateway_replica, create_project, + get_run_spec, ) +@pytest.mark.asyncio +@pytest.mark.parametrize("deleting", [False, True]) +async def test_autoscaling_uses_only_serving_gateway_stats(monkeypatch, deleting): + healthy = GatewayReplicaModel( + ip_address="1.1.1.1", + ssh_private_key="key", + status=GatewayReplicaStatus.RUNNING, + scale_in=False, + ) + retiring = GatewayReplicaModel( + ip_address="2.2.2.2", + ssh_private_key="key", + status=GatewayReplicaStatus.RUNNING, + scale_in=True, + ) + gateway = GatewayModel( + status=GatewayStatus.RUNNING, + to_be_deleted=deleting, + gateway_replicas=[retiring], + gateway_replica=healthy, + ) + run = RunModel(gateway=gateway, project=ProjectModel(name="project"), run_name="service") + spec = get_run_spec( + repo_id="repo", configuration=ServiceConfiguration(port=80, image="ubuntu") + ) + stats = {w: Stat(requests=12, request_time=0.5) for w in SERVICE_SCALING_WINDOWS} + + async def get_connection(hostname, id_rsa): + conn = AsyncMock() + conn.get_stats.return_value = ( + stats + if hostname == healthy.ip_address + else {w: Stat(requests=99, request_time=5.0) for w in SERVICE_SCALING_WINDOWS} + ) + return conn + + monkeypatch.setattr(gateways.gateway_connections_pool, "get_or_add", get_connection) + assert await _load_gateway_stats(run, spec) == (None if deleting else stats) + + class TestMergePerWindowStats: def test_empty_returns_zero_stats(self): result = _merge_per_window_stats([]) diff --git a/src/tests/_internal/server/services/gateways/test_pool.py b/src/tests/_internal/server/services/gateways/test_pool.py new file mode 100644 index 0000000000..f1c342bdde --- /dev/null +++ b/src/tests/_internal/server/services/gateways/test_pool.py @@ -0,0 +1,103 @@ +import asyncio +from pathlib import Path +from unittest.mock import AsyncMock, patch + +import pytest + +from dstack._internal.core.errors import SSHError +from dstack._internal.server.services.gateways.connection import GatewayConnection +from dstack._internal.server.services.gateways.pool import GatewayConnectionsPool + + +@pytest.mark.asyncio +async def test_recycled_address_does_not_reuse_previous_replicas_tunnel(): + pool = GatewayConnectionsPool() + with patch("dstack._internal.server.services.gateways.pool.GatewayConnection") as factory: + old = AsyncMock() + replacement = AsyncMock() + factory.side_effect = [old, replacement] + assert await pool.get_or_add("host", "first key") is old + assert await pool.get_or_add("host", "second key") is replacement + old.close.assert_awaited_once() + assert await pool.get_or_add("host", "second key") is replacement + assert await pool.all() == [replacement] + + +@pytest.mark.asyncio +async def test_opening_one_host_does_not_expose_unready_connection_or_block_other_hosts(): + pool = GatewayConnectionsPool() + entered, release = asyncio.Event(), asyncio.Event() + + async def delayed_open(**kwargs): + entered.set() + await release.wait() + + slow, other = AsyncMock(), AsyncMock() + slow.open.side_effect = delayed_open + with patch( + "dstack._internal.server.services.gateways.pool.GatewayConnection", + side_effect=[slow, other], + ): + first = asyncio.create_task(pool.get_or_add("slow", "key")) + await entered.wait() + second = asyncio.create_task(pool.get_or_add("slow", "key")) + try: + async with asyncio.timeout(2): + assert await pool.get_or_add("other", "key") is other + assert await pool.all() == [other] + finally: + release.set() + assert await first is slow + assert await second is slow + slow.open.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_socket_paths_are_scoped_to_key_and_invalidated_after_close(tmp_path): + # Two server processes can have independent pools that use the same server directory. + with ( + patch("dstack._internal.server.settings.SERVER_DIR_PATH", tmp_path), + patch("dstack._internal.server.services.gateways.connection.SSHTunnel", autospec=True), + ): + first = GatewayConnection("host", "first key", 8000) + second = GatewayConnection("host", "second key", 8000) + restarted = GatewayConnection("host", "second key", 8000) + assert first.gateway_socket_path.resolve() != second.gateway_socket_path.resolve() + assert second.gateway_socket_path.resolve() == restarted.gateway_socket_path.resolve() + await first.close() + assert not await first.check_or_restart() + with pytest.raises(SSHError): + async with first.client(): + pytest.fail("Retired connection returned a usable client") + assert not first.gateway_socket_path.parent.exists() + assert not first.gateway_socket_path.parent.is_symlink() + + +@pytest.mark.asyncio +async def test_startup_closes_pre_upgrade_control_socket_without_using_it_for_forwarding(tmp_path): + address_dir = tmp_path / "gateway-connections" / "host" + address_dir.mkdir(parents=True) + old_control = address_dir / "control.sock" + old_control.touch() + tunnels = {} + + def tunnel(**kwargs): + control = Path(kwargs["control_sock_path"]).resolve() + mock = AsyncMock(destination=kwargs["destination"], identity_path="identity") + mock.acheck.return_value = False + tunnels[control] = mock + return mock + + with ( + patch("dstack._internal.server.settings.SERVER_DIR_PATH", tmp_path), + patch( + "dstack._internal.server.services.gateways.connection.SSHTunnel", side_effect=tunnel + ), + ): + conn = GatewayConnection("host", "new key", 8000) + await conn.open(close_existing_tunnel=True) + tunnels[old_control].aclose.assert_awaited_once() + tunnels[old_control].aopen.assert_not_awaited() + assert conn.tunnel is tunnels[conn.connection_dir / "control.sock"] + assert conn.gateway_socket_path.resolve().parent != address_dir + await conn.close() diff --git a/src/tests/_internal/server/services/gateways/test_usage.py b/src/tests/_internal/server/services/gateways/test_usage.py new file mode 100644 index 0000000000..e013db6264 --- /dev/null +++ b/src/tests/_internal/server/services/gateways/test_usage.py @@ -0,0 +1,402 @@ +import asyncio +import logging +import sqlite3 +import uuid +from contextlib import asynccontextmanager +from datetime import timedelta +from unittest.mock import Mock + +import httpx +import pytest +import pytest_asyncio +from sqlalchemy import select, update +from sqlalchemy.exc import OperationalError + +from dstack._internal.proxy.lib.schemas.usage import ( + UsageAckResponse, + UsageBatchPage, + UsageDrainResponse, +) +from dstack._internal.server.db import Database +from dstack._internal.server.models import ( + BackendModel, + BaseModel, + GatewayModel, + GatewayReplicaModel, + UsageBatchModel, + UsageCounterModel, +) +from dstack._internal.server.services.gateways import usage +from dstack._internal.server.services.gateways.connection import GatewayConnection +from dstack._internal.server.services.usage import ingest_usage_batch +from dstack._internal.server.testing.common import ( + create_backend, + create_gateway, + create_gateway_replica, + create_project, + create_user, +) +from dstack._internal.utils.common import get_current_datetime +from tests._internal.server.services.test_usage import batch + + +class GatewayQueue: + def __init__(self, ip_address, items): + self.connection = Mock(spec=GatewayConnection, ip_address=ip_address, client=self.client) + self.items = items + self.acks = [] + self.fetches = 0 + + @asynccontextmanager + async def client(self): + yield self + + async def fetch_usage_batches(self, limit): + self.fetches += 1 + return UsageBatchPage(batches=self.items[:limit], has_more=len(self.items) > limit) + + async def acknowledge_usage(self, ids): + self.acks.append(ids) + self.items = [b for b in self.items if b.batch_id not in ids] + return UsageAckResponse(acknowledged_batch_ids=ids) + + async def drain_usage(self): + return UsageDrainResponse(sealed=True, empty=not self.items) + + +async def claim(session, replica): + replica.lock_token = uuid.uuid4() + replica.lock_expires_at = get_current_datetime() + timedelta(seconds=30) + replica.lock_owner = "GatewayReplicaPipeline" + await session.commit() + + +@pytest_asyncio.fixture +async def replica(session): + user = await create_user(session) + project = await create_project(session, owner=user) + backend = await create_backend(session, project.id) + gateway = await create_gateway(session, project.id, backend.id) + replica = await create_gateway_replica(session, backend, gateway_id=gateway.id) + await claim(session, replica) + return replica + + +@pytest.mark.asyncio +class TestDrainGatewayUsage: + @pytest.mark.parametrize("unsupported", [False, True]) + async def test_continues_collecting_closed_minutes_while_drain_is_pending( + self, session, replica, monkeypatch, unsupported + ): + queue = GatewayQueue(replica.ip_address, [batch()]) + + async def waiting(): + if unsupported: + response = httpx.Response( + 404, request=httpx.Request("POST", "http://gateway/drain") + ) + response.raise_for_status() + return UsageDrainResponse(sealed=False, empty=False) + + monkeypatch.setattr(queue, "drain_usage", waiting) + assert not await usage.drain_gateway_usage( + queue.connection, replica.id, replica.gateway_id, replica.lock_token + ) + assert queue.acks == [["batch-1"]] + assert (await session.scalars(select(UsageCounterModel.total_tokens))).all() == [23] + + async def test_recovers_lost_final_ack_response(self, session, replica, monkeypatch): + queue = GatewayQueue(replica.ip_address, [batch()]) + acknowledge = queue.acknowledge_usage + + async def lose_response(ids): + await acknowledge(ids) + raise httpx.ReadError("Lost the Gateway's successful ACK response") + + monkeypatch.setattr(queue, "acknowledge_usage", lose_response) + args = (queue.connection, replica.id, replica.gateway_id, replica.lock_token) + assert not await usage.drain_gateway_usage(*args) + assert queue.acks == [["batch-1"]] and queue.items == [] + assert await usage.drain_gateway_usage(*args) + assert (await session.scalars(select(UsageCounterModel.total_tokens))).all() == [23] + + async def test_does_not_start_drain_for_stale_claim_or_different_gateway( + self, replica, monkeypatch + ): + queue = GatewayQueue(replica.ip_address, []) + calls = [] + + async def empty(): + calls.append(True) + return UsageDrainResponse(sealed=True, empty=True) + + monkeypatch.setattr(queue, "drain_usage", empty) + assert not await usage.drain_gateway_usage( + queue.connection, replica.id, replica.gateway_id, uuid.uuid4() + ) + assert not await usage.drain_gateway_usage( + queue.connection, replica.id, uuid.uuid4(), replica.lock_token + ) + assert calls == [] + + +@pytest.mark.asyncio +class TestCollectGatewayUsage: + @pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) + async def test_commit_before_ack_and_retry_after_lost_ack( + self, session, test_db, replica, monkeypatch + ): + queue = GatewayQueue(replica.ip_address, [batch()]) + sessions = [] + get_session = test_db.get_session + + def track_session(*args, **kwargs): + db_session = get_session(*args, **kwargs) + sessions.append(db_session) + return db_session + + monkeypatch.setattr(test_db, "get_session", track_session) + fetch = queue.fetch_usage_batches + acknowledge = queue.acknowledge_usage + transactions_during_io = [] + observed_at_ack = [] + + async def tracked_fetch(limit): + transactions_during_io.append(any(s.in_transaction() for s in sessions)) + return await fetch(limit) + + async def lose_first_ack(ids): + transactions_during_io.append(any(s.in_transaction() for s in sessions)) + async with get_session() as observer: + batches = (await observer.scalars(select(UsageBatchModel.batch_id))).all() + counters = (await observer.scalars(select(UsageCounterModel.total_tokens))).all() + observed_at_ack.append((ids, batches, counters)) + raise httpx.WriteError("ACK lost in transit") + + monkeypatch.setattr(queue, "fetch_usage_batches", tracked_fetch) + monkeypatch.setattr(queue, "acknowledge_usage", lose_first_ack) + await usage.collect_gateway_usage(queue.connection, replica.id, replica.lock_token) + assert transactions_during_io == [False, False] + assert observed_at_ack == [(["batch-1"], ["batch-1"], [23])] + assert queue.items == [batch()] + monkeypatch.setattr(queue, "acknowledge_usage", acknowledge) + # A replacement worker fetches the already committed page from the Gateway. + await claim(session, replica) + await usage.collect_gateway_usage(queue.connection, replica.id, replica.lock_token) + assert queue.fetches == 2 + assert queue.acks == [["batch-1"]] + assert queue.items == [] + assert (await session.scalars(select(UsageCounterModel.total_tokens))).all() == [23] + + async def test_conflict_rolls_back_entire_page_without_ack(self, session, replica): + await ingest_usage_batch(session, replica.id, replica.gateway_id, batch()) + await session.commit() + items = [batch("new", offset=1), batch(tokens=4)] + queue = GatewayQueue(replica.ip_address, items) + await usage.collect_gateway_usage(queue.connection, replica.id, replica.lock_token) + assert queue.fetches == 1 + assert queue.acks == [] + assert queue.items == items + assert (await session.scalars(select(UsageBatchModel.batch_id))).all() == ["batch-1"] + assert (await session.scalars(select(UsageCounterModel.total_tokens))).all() == [23] + + async def test_page_budget_leaves_remainder_for_next_poll(self, session, replica, monkeypatch): + items = [batch(f"b-{i}", i) for i in range(5)] + queue = GatewayQueue(replica.ip_address, items) + monkeypatch.setattr(usage, "PAGE_SIZE", 2) + monkeypatch.setattr(usage, "MAX_PAGES", 2) + await usage.collect_gateway_usage(queue.connection, replica.id, replica.lock_token) + assert queue.fetches == 2 + assert queue.acks == [["b-0", "b-1"], ["b-2", "b-3"]] + assert queue.items == [items[4]] + await usage.collect_gateway_usage(queue.connection, replica.id, replica.lock_token) + assert queue.acks[-1] == ["b-4"] + assert queue.items == [] + assert sorted(await session.scalars(select(UsageBatchModel.batch_id))) == [ + "b-0", + "b-1", + "b-2", + "b-3", + "b-4", + ] + + async def test_timeout_during_fetch_leaves_page_pending(self, session, replica, monkeypatch): + queue = GatewayQueue(replica.ip_address, [batch()]) + fetch = queue.fetch_usage_batches + + async def fetch_past_deadline(limit): + page = await fetch(limit) + loop = asyncio.get_running_loop() + past_deadline = loop.time() + usage.COLLECTION_TIMEOUT + 1 + with monkeypatch.context() as clock: + clock.setattr(loop, "time", lambda: past_deadline) + # Let the loop dispatch its due timer before returning the page. + await asyncio.sleep(0) + await asyncio.sleep(0) + return page + + monkeypatch.setattr(queue, "fetch_usage_batches", fetch_past_deadline) + await usage.collect_gateway_usage(queue.connection, replica.id, replica.lock_token) + assert queue.fetches == 1 + assert queue.acks == [] + assert queue.items == [batch()] + assert (await session.scalars(select(UsageBatchModel))).all() == [] + + @pytest.mark.parametrize("status_code", [404, 405]) + async def test_old_gateway_endpoint_skipped(self, replica, monkeypatch, caplog, status_code): + queue = GatewayQueue(replica.ip_address, [batch()]) + + async def unavailable(limit): + queue.fetches += 1 + response = httpx.Response( + status_code, request=httpx.Request("GET", "http://gateway/api/usage/batches") + ) + response.raise_for_status() + + monkeypatch.setattr(queue, "fetch_usage_batches", unavailable) + await usage.collect_gateway_usage(queue.connection, replica.id, replica.lock_token) + assert queue.fetches == 1 + assert queue.acks == [] + queue.connection.try_collect_stats.assert_not_awaited() + assert not any( + r.levelno >= logging.WARNING and r.name == usage.__name__ for r in caplog.records + ) + + async def test_multiple_replicas_and_legacy_parent(self, session, replica): + backend = await session.get(BackendModel, replica.backend_id) + second = await create_gateway_replica( + session, backend, gateway_id=replica.gateway_id, ip_address="2.2.2.2" + ) + legacy = await create_gateway_replica(session, backend, ip_address="3.3.3.3") + parent = await session.get(GatewayModel, replica.gateway_id) + parent.gateway_replica_id = legacy.id + await claim(session, second) + await claim(session, legacy) + for source in [replica, second, legacy]: + queue = GatewayQueue(source.ip_address, [batch()]) + await usage.collect_gateway_usage(queue.connection, source.id, source.lock_token) + assert queue.acks == [["batch-1"]] + rows = (await session.scalars(select(UsageBatchModel))).all() + assert {row.gateway_replica_id for row in rows} == {replica.id, second.id, legacy.id} + assert {row.gateway_id for row in rows} == {parent.id} + + async def test_unbound_source_can_only_ack_historical_replay(self, session, replica): + await ingest_usage_batch(session, replica.id, replica.gateway_id, batch()) + parent_id = replica.gateway_id + replica.gateway_id = None + await session.commit() + queue = GatewayQueue(replica.ip_address, [batch()]) + await usage.collect_gateway_usage(queue.connection, replica.id, replica.lock_token) + assert queue.acks == [["batch-1"]] + queue.items = [batch("new", offset=1)] + await usage.collect_gateway_usage(queue.connection, replica.id, replica.lock_token) + assert queue.acks == [["batch-1"]] + assert queue.items == [batch("new", offset=1)] + row = (await session.scalars(select(UsageBatchModel))).one() + assert row.batch_id == "batch-1" and row.gateway_id == parent_id + + async def test_ambiguous_address_is_skipped(self, session, replica): + backend = await session.get(BackendModel, replica.backend_id) + await create_gateway_replica(session, backend, ip_address=replica.ip_address) + queue = GatewayQueue(replica.ip_address, [batch()]) + await usage.collect_gateway_usage(queue.connection, replica.id, replica.lock_token) + assert queue.fetches == 0 + + async def test_address_must_belong_to_claimed_replica(self, session, replica): + backend = await session.get(BackendModel, replica.backend_id) + other = await create_gateway_replica( + session, backend, gateway_id=replica.gateway_id, ip_address="2.2.2.2" + ) + # The pipeline gives all replicas claimed in one fetch the same token. + other.lock_token = replica.lock_token + other.lock_owner = replica.lock_owner + other.lock_expires_at = replica.lock_expires_at + await session.commit() + queue = GatewayQueue(other.ip_address, [batch()]) + await usage.collect_gateway_usage(queue.connection, replica.id, replica.lock_token) + assert queue.fetches == 0 + + async def test_conflicting_modern_and_legacy_parents_are_skipped(self, session, replica): + backend = await session.get(BackendModel, replica.backend_id) + other_parent = await create_gateway(session, backend.project_id, backend.id, name="other") + other_parent.gateway_replica_id = replica.id + await session.commit() + queue = GatewayQueue(replica.ip_address, [batch()]) + await usage.collect_gateway_usage(queue.connection, replica.id, replica.lock_token) + assert queue.fetches == 0 + + @pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) + async def test_takeover_during_fetch_fences_stale_page( + self, session, replica, monkeypatch, test_db + ): + queue = GatewayQueue(replica.ip_address, [batch()]) + fetch = queue.fetch_usage_batches + + async def fetch_then_take_over(limit): + page = await fetch(limit) + await claim(session, replica) + return page + + monkeypatch.setattr(queue, "fetch_usage_batches", fetch_then_take_over) + old_token = replica.lock_token + await usage.collect_gateway_usage(queue.connection, replica.id, old_token) + assert queue.fetches == 1 + assert queue.acks == [] + assert (await session.scalars(select(UsageBatchModel))).all() == [] + await session.commit() + monkeypatch.setattr(queue, "fetch_usage_batches", fetch) + await usage.collect_gateway_usage(queue.connection, replica.id, old_token) + assert queue.fetches == 1 + await usage.collect_gateway_usage(queue.connection, replica.id, replica.lock_token) + assert queue.acks == [["batch-1"]] + assert (await session.scalars(select(UsageCounterModel.total_tokens))).all() == [23] + + +@pytest.mark.asyncio +class TestCollectGatewayUsageSQLiteLock: + @pytest_asyncio.fixture + async def sqlite_db(self, tmp_path): + # Separate connections must see the same database to exercise SQLite's writer lock. + db = Database(f"sqlite+aiosqlite:///{tmp_path / 'usage.db'}") + try: + async with db.engine.begin() as conn: + await conn.run_sync(BaseModel.metadata.create_all) + yield db + finally: + await db.engine.dispose() + + async def test_claim_cannot_change_between_revalidation_and_insert( + self, session, replica, test_db, monkeypatch + ): + queue = GatewayQueue(replica.ip_address, [batch()]) + next_token = uuid.uuid4() + takeover = ( + update(GatewayReplicaModel) + .where( + GatewayReplicaModel.id == replica.id, + GatewayReplicaModel.lock_token == replica.lock_token, + ) + .values(lock_token=next_token) + ) + collisions = [] + async with test_db.engine.connect() as contender: + await contender.exec_driver_sql("PRAGMA busy_timeout=0") + + async def ingest_with_competing_claim(*args): + try: + await contender.execute(takeover) + await contender.commit() + except OperationalError as exc: + assert isinstance(exc.orig, sqlite3.OperationalError) + collisions.append(exc.orig.sqlite_errorcode) + await contender.rollback() + return await ingest_usage_batch(*args) + + monkeypatch.setattr(usage, "ingest_usage_batch", ingest_with_competing_claim) + await usage.collect_gateway_usage(queue.connection, replica.id, replica.lock_token) + assert collisions == [sqlite3.SQLITE_BUSY] + assert queue.acks == [["batch-1"]] + await contender.execute(takeover) + await contender.commit() + assert await session.scalar(select(GatewayReplicaModel.lock_token)) == next_token + assert (await session.scalars(select(UsageCounterModel.total_tokens))).all() == [23] diff --git a/src/tests/_internal/server/services/gateways/test_usage_client.py b/src/tests/_internal/server/services/gateways/test_usage_client.py index 0da0e5e721..a0815c47db 100644 --- a/src/tests/_internal/server/services/gateways/test_usage_client.py +++ b/src/tests/_internal/server/services/gateways/test_usage_client.py @@ -5,6 +5,32 @@ from dstack._internal.server.services.gateways.client import AsyncClientWrapper, GatewayClient +@pytest.mark.asyncio +@pytest.mark.parametrize( + "status,payload,error", + [ + (200, {"sealed": True, "empty": True}, None), + (404, {}, httpx.HTTPStatusError), + (200, {"sealed": False, "empty": True}, ValidationError), + (200, {"sealed": "true", "empty": True}, ValidationError), + ], +) +async def test_drain_requires_explicit_confirmation(status, payload, error): + def response(request): + assert request.method == "POST" and request.url.path == "/api/usage/drain" + return httpx.Response(status, json=payload) + + client = GatewayClient(port=1) + await client._client.aclose() + async with AsyncClientWrapper(transport=httpx.MockTransport(response)) as http: + client._client = http + if error: + with pytest.raises(error): + await client.drain_usage() + else: + assert (await client.drain_usage()).empty + + @pytest.mark.asyncio @pytest.mark.parametrize("version", [1, 2]) async def test_usage_client_contract(version): diff --git a/src/tests/_internal/server/services/runs/test_runs.py b/src/tests/_internal/server/services/runs/test_runs.py index 1a982c74c1..14517dfc36 100644 --- a/src/tests/_internal/server/services/runs/test_runs.py +++ b/src/tests/_internal/server/services/runs/test_runs.py @@ -1,3 +1,5 @@ +from uuid import uuid4 + import pytest from sqlalchemy import event, select from sqlalchemy.ext.asyncio import AsyncSession @@ -5,14 +7,23 @@ from dstack._internal.core.errors import ServerClientError from dstack._internal.core.models.backends.base import BackendType from dstack._internal.core.models.duration import Duration +from dstack._internal.core.models.gateways import GatewayReplicaStatus, GatewayStatus from dstack._internal.core.models.profiles import Profile, ProfileRetry, RetryEvent from dstack._internal.core.models.runs import JobStatus, JobTerminationReason, RunStatus from dstack._internal.core.models.users import GlobalRole, ProjectRole from dstack._internal.core.models.volumes import Volume -from dstack._internal.server.models import UserModel +from dstack._internal.server.models import ( + GatewayModel, + GatewayReplicaModel, + JobModel, + RunModel, + ServiceReplicaRegistrationModel, + UserModel, +) from dstack._internal.server.services import runs as runs_services from dstack._internal.server.services.jobs import check_can_attach_job_volumes from dstack._internal.server.services.projects import add_project_member +from dstack._internal.server.services.runs.replicas import is_replica_receiving_traffic from dstack._internal.server.testing.common import ( create_job, create_project, @@ -25,6 +36,27 @@ ) +@pytest.mark.parametrize("reason", ["scale_in", "deleting", "failed"]) +def test_registered_job_has_no_route_via_retiring_legacy_gateway(reason): + replica = GatewayReplicaModel( + id=uuid4(), status=GatewayReplicaStatus.RUNNING, scale_in=reason == "scale_in" + ) + gateway = GatewayModel( + status=GatewayStatus.FAILED if reason == "failed" else GatewayStatus.RUNNING, + to_be_deleted=reason == "deleting", + gateway_replica=replica, + ) + job = JobModel( + ready=True, + registered=True, + status=JobStatus.RUNNING, + service_replica_registrations=[ + ServiceReplicaRegistrationModel(gateway_replica_id=replica.id, is_registered=True) + ], + ) + assert not is_replica_receiving_traffic(RunModel(gateway=gateway), [job]) + + class TestListUserRuns: @pytest.mark.asyncio @pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) From 13ac26c8ccc29fcc84f742bfffaf425268aedc1d Mon Sep 17 00:00:00 2001 From: Igx22 Date: Fri, 20 Nov 2026 17:43:45 +0700 Subject: [PATCH 5/7] Store Gateway usage in one relational table Use numbered user/run rows to enforce delivery keys and verify full batch replays. Keep page writes atomic and acknowledge only committed batches. --- contributing/PROXY.md | 7 +- ..._9a2e8f1f3c37_add_gateway_usage_batches.py | 112 ++++--- src/dstack/_internal/server/models.py | 64 +++- .../server/services/gateways/usage.py | 4 +- src/dstack/_internal/server/services/usage.py | 130 +++++--- .../pipeline_tasks/test_gateway_replicas.py | 25 +- .../server/services/gateways/test_usage.py | 128 ++++++-- .../_internal/server/services/test_usage.py | 309 ++++++++++++------ .../_internal/server/test_usage_migration.py | 232 +++++++------ 9 files changed, 661 insertions(+), 350 deletions(-) diff --git a/contributing/PROXY.md b/contributing/PROXY.md index c5874ca7d5..fb943addd3 100644 --- a/contributing/PROXY.md +++ b/contributing/PROXY.md @@ -189,10 +189,13 @@ Never delete/reset these files as a routine repair: reconcile identity/history f The `GatewayReplicaPipeline` worker holding the running replica's lease polls `/api/usage/batches` over its private SSH management connection. It verifies the -source and lease token, commits the page's receipts and counters, then POSTs +source and lease token, commits the page's numbered `usage_batches` rows, then POSTs `/api/usage/batches/ack` outside the transaction. If the server exits between commit and ACK, another server can claim the replica after lease expiry and ACK -the replayed page. Old Gateways lacking the usage API still get normal state sync. +the replayed page after matching its full contents. Old Gateways lacking the usage API +still get normal state sync. For reports, aggregate the counter columns directly in +`usage_batches` by `user_id`, `run_id`, Gateway or minute. Each row represents one +user and run in a replica's batch. On planned removal of a serving Gateway replica, the worker calls the private `POST /api/usage/drain`. Nginx fences new public requests and lets open HTTP diff --git a/src/dstack/_internal/server/migrations/versions/2026/11_16_1201_9a2e8f1f3c37_add_gateway_usage_batches.py b/src/dstack/_internal/server/migrations/versions/2026/11_16_1201_9a2e8f1f3c37_add_gateway_usage_batches.py index 3d0afc8386..a54c49492d 100644 --- a/src/dstack/_internal/server/migrations/versions/2026/11_16_1201_9a2e8f1f3c37_add_gateway_usage_batches.py +++ b/src/dstack/_internal/server/migrations/versions/2026/11_16_1201_9a2e8f1f3c37_add_gateway_usage_batches.py @@ -1,4 +1,4 @@ -"""Add Gateway usage batches with historical replica/Gateway IDs +"""Add Gateway usage batches with one row per user and run Revision ID: 9a2e8f1f3c37 Revises: 6b5610ff36c1 @@ -7,10 +7,10 @@ """ import sqlalchemy as sa -import sqlalchemy_utils from alembic import op +from sqlalchemy_utils import UUIDType -import dstack._internal.server.models +from dstack._internal.server.models import NaiveDateTime # revision identifiers, used by Alembic. revision = "9a2e8f1f3c37" @@ -20,61 +20,85 @@ def upgrade() -> None: + row_number_check = "batch_row_number >= 0" + sqlite_checks = [] + if op.get_context().dialect.name == "sqlite": + row_number_check = "typeof(batch_row_number) = 'integer' AND " + row_number_check + sqlite_checks.append( + sa.CheckConstraint( + "typeof(prompt_tokens) = 'integer' AND typeof(cached_prompt_tokens) = 'integer' " + "AND typeof(completion_tokens) = 'integer' AND typeof(total_tokens) = 'integer' " + "AND typeof(unknown_usage_attempts) = 'integer'", + name=op.f("ck_usage_batches_integer_counters"), + ) + ) + op.create_table( "usage_batches", - sa.Column("id", sqlalchemy_utils.types.uuid.UUIDType(binary=False), nullable=False), - sa.Column( - "gateway_replica_id", - sqlalchemy_utils.types.uuid.UUIDType(binary=False), - nullable=False, - ), - sa.Column("gateway_id", sqlalchemy_utils.types.uuid.UUIDType(binary=False), nullable=True), + sa.Column("id", UUIDType(binary=False), nullable=False), + sa.Column("gateway_replica_id", UUIDType(binary=False), nullable=False), + sa.Column("gateway_id", UUIDType(binary=False), nullable=False), sa.Column("batch_id", sa.String(length=128), nullable=False), - sa.Column( - "interval_start", dstack._internal.server.models.NaiveDateTime(), nullable=False - ), - sa.Column("interval_end", dstack._internal.server.models.NaiveDateTime(), nullable=False), - sa.Column("received_at", dstack._internal.server.models.NaiveDateTime(), nullable=False), - sa.Column("content", sa.Text(), nullable=False), - sa.PrimaryKeyConstraint("id", name=op.f("pk_usage_batches")), - sa.UniqueConstraint( - "gateway_replica_id", "batch_id", name="uq_usage_batches_replica_batch" - ), - sa.UniqueConstraint( - "gateway_replica_id", "interval_start", name="uq_usage_batches_replica_minute" - ), - ) - op.create_index( - "ix_usage_batches_gateway_interval", "usage_batches", ["gateway_id", "interval_start"] - ) - op.create_table( - "usage_counters", - sa.Column( - "usage_baches_id", sqlalchemy_utils.types.uuid.UUIDType(binary=False), nullable=False - ), - sa.Column("consumer_subject_id", sa.String(length=128), nullable=False), - sa.Column("service_id", sa.String(length=128), nullable=False), + sa.Column("interval_start", NaiveDateTime(), nullable=False), + sa.Column("interval_end", NaiveDateTime(), nullable=False), + sa.Column("received_at", NaiveDateTime(), nullable=False), + sa.Column("user_id", UUIDType(binary=False), nullable=False), + sa.Column("run_id", UUIDType(binary=False), nullable=False), sa.Column("prompt_tokens", sa.BigInteger(), nullable=False), sa.Column("cached_prompt_tokens", sa.BigInteger(), nullable=False), sa.Column("completion_tokens", sa.BigInteger(), nullable=False), sa.Column("total_tokens", sa.BigInteger(), nullable=False), sa.Column("unknown_usage_attempts", sa.BigInteger(), nullable=False), + sa.Column("batch_row_number", sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint("id", name=op.f("pk_usage_batches")), sa.ForeignKeyConstraint( - ["usage_baches_id"], - ["usage_batches.id"], - name=op.f("fk_usage_counters_usage_baches_id_usage_batches"), + ["user_id"], + ["users.id"], + ondelete="RESTRICT", + name=op.f("fk_usage_batches_user_id_users"), ), - sa.PrimaryKeyConstraint( - "usage_baches_id", "consumer_subject_id", "service_id", name=op.f("pk_usage_counters") + sa.UniqueConstraint( + "gateway_replica_id", + "batch_id", + "user_id", + "run_id", + name="uq_usage_batches_replica_batch_pair", ), + sa.CheckConstraint(row_number_check, name=op.f("ck_usage_batches_row_number")), + sa.CheckConstraint( + "prompt_tokens >= 0 AND cached_prompt_tokens >= 0 " + "AND cached_prompt_tokens <= prompt_tokens AND completion_tokens >= 0 " + "AND total_tokens >= 0 AND total_tokens - prompt_tokens = completion_tokens " + "AND unknown_usage_attempts >= 0", + name=op.f("ck_usage_batches_counters"), + ), + *sqlite_checks, + ) + first_row = sa.text("batch_row_number = 0") + op.create_index( + "uq_usage_batches_replica_batch", + "usage_batches", + ["gateway_replica_id", "batch_id"], + unique=True, + sqlite_where=first_row, + postgresql_where=first_row, + ) + op.create_index( + "uq_usage_batches_replica_minute", + "usage_batches", + ["gateway_replica_id", "interval_start"], + unique=True, + sqlite_where=first_row, + postgresql_where=first_row, + ) + op.create_index( + "ix_usage_batches_gateway_interval", "usage_batches", ["gateway_id", "interval_start"] ) + op.create_index("ix_usage_batches_user_id", "usage_batches", ["user_id"]) + op.create_index("ix_usage_batches_run_id", "usage_batches", ["run_id"]) def downgrade() -> None: - conn = op.get_bind() - if conn.scalar(sa.text("SELECT COUNT(*) FROM usage_batches")) or conn.scalar( - sa.text("SELECT COUNT(*) FROM usage_counters") - ): + if op.get_bind().scalar(sa.text("SELECT 1 FROM usage_batches LIMIT 1")): raise ValueError("Populated usage downgrade requires a backup and reconciliation") - op.drop_table("usage_counters") op.drop_table("usage_batches") diff --git a/src/dstack/_internal/server/models.py b/src/dstack/_internal/server/models.py index 165270548b..82e7dd5bb9 100644 --- a/src/dstack/_internal/server/models.py +++ b/src/dstack/_internal/server/models.py @@ -7,6 +7,7 @@ from sqlalchemy import ( BigInteger, Boolean, + CheckConstraint, DateTime, Float, ForeignKey, @@ -18,6 +19,7 @@ Text, TypeDecorator, UniqueConstraint, + text, ) from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship from sqlalchemy.sql import false @@ -1512,12 +1514,49 @@ class ProviderRefModel(BaseModel): class UsageBatchModel(BaseModel): __tablename__ = "usage_batches" + _first_row = text("batch_row_number = 0") __table_args__ = ( - UniqueConstraint("gateway_replica_id", "batch_id", name="uq_usage_batches_replica_batch"), UniqueConstraint( - "gateway_replica_id", "interval_start", name="uq_usage_batches_replica_minute" + "gateway_replica_id", + "batch_id", + "user_id", + "run_id", + name="uq_usage_batches_replica_batch_pair", + ), + Index( + "uq_usage_batches_replica_batch", + "gateway_replica_id", + "batch_id", + unique=True, + sqlite_where=_first_row, + postgresql_where=_first_row, + ), + Index( + "uq_usage_batches_replica_minute", + "gateway_replica_id", + "interval_start", + unique=True, + sqlite_where=_first_row, + postgresql_where=_first_row, ), Index("ix_usage_batches_gateway_interval", "gateway_id", "interval_start"), + CheckConstraint( + "prompt_tokens >= 0 AND cached_prompt_tokens >= 0 " + "AND cached_prompt_tokens <= prompt_tokens AND completion_tokens >= 0 " + "AND total_tokens >= 0 AND total_tokens - prompt_tokens = completion_tokens " + "AND unknown_usage_attempts >= 0", + name="counters", + ), + CheckConstraint( + "typeof(prompt_tokens) = 'integer' AND typeof(cached_prompt_tokens) = 'integer' " + "AND typeof(completion_tokens) = 'integer' AND typeof(total_tokens) = 'integer' " + "AND typeof(unknown_usage_attempts) = 'integer'", + name="integer_counters", + ).ddl_if(dialect="sqlite"), + CheckConstraint( + "typeof(batch_row_number) = 'integer' AND batch_row_number >= 0", name="row_number" + ).ddl_if(dialect="sqlite"), + CheckConstraint("batch_row_number >= 0", name="row_number").ddl_if(dialect="postgresql"), ) id: Mapped[uuid.UUID] = mapped_column( @@ -1525,25 +1564,18 @@ class UsageBatchModel(BaseModel): ) # Historical snapshots deliberately have no FK to deletable infrastructure. gateway_replica_id: Mapped[uuid.UUID] = mapped_column(UUIDType(binary=False)) - gateway_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUIDType(binary=False), nullable=True) - """NULL only for unresolved legacy history; new ingestion requires a parent.""" + gateway_id: Mapped[uuid.UUID] = mapped_column(UUIDType(binary=False)) batch_id: Mapped[str] = mapped_column(String(128)) interval_start: Mapped[datetime] = mapped_column(NaiveDateTime) interval_end: Mapped[datetime] = mapped_column(NaiveDateTime) received_at: Mapped[datetime] = mapped_column(NaiveDateTime, default=get_current_datetime) - content: Mapped[str] = mapped_column(Text) - """Canonical normalized counters, never prompts, responses, or bearer tokens.""" - - -class UsageCounterModel(BaseModel): - __tablename__ = "usage_counters" - - usage_baches_id: Mapped[uuid.UUID] = mapped_column( - ForeignKey("usage_batches.id"), primary_key=True + batch_row_number: Mapped[int] = mapped_column(Integer) + """Row zero claims the batch ID and minute for this replica.""" + user_id: Mapped[uuid.UUID] = mapped_column( + ForeignKey("users.id", ondelete="RESTRICT"), index=True ) - consumer_subject_id: Mapped[str] = mapped_column(String(128), primary_key=True) - service_id: Mapped[str] = mapped_column(String(128), primary_key=True) - # Historical source IDs deliberately have no cascading foreign keys to users/runs. + run_id: Mapped[uuid.UUID] = mapped_column(UUIDType(binary=False), index=True) + """Historical run UUID retained after physical deletion.""" prompt_tokens: Mapped[int] = mapped_column(BigInteger) cached_prompt_tokens: Mapped[int] = mapped_column(BigInteger) completion_tokens: Mapped[int] = mapped_column(BigInteger) diff --git a/src/dstack/_internal/server/services/gateways/usage.py b/src/dstack/_internal/server/services/gateways/usage.py index 0587f80651..dc44183bd4 100644 --- a/src/dstack/_internal/server/services/gateways/usage.py +++ b/src/dstack/_internal/server/services/gateways/usage.py @@ -1,4 +1,4 @@ -"""Fetch durable minute batches, commit receipts, then ACK over existing SSH connections.""" +"""Fetch durable minute batches, commit usage rows, then ACK over SSH.""" import asyncio import uuid @@ -137,7 +137,7 @@ async def _get_source( return None if parent is not None and legacy_parent is not None and parent != legacy_parent: return None - # An unbound replica can only replay an already committed receipt. + # An unbound replica can only replay an already committed batch. return source_id, parent or legacy_parent diff --git a/src/dstack/_internal/server/services/usage.py b/src/dstack/_internal/server/services/usage.py index 1faab76ff0..6f8c0f765d 100644 --- a/src/dstack/_internal/server/services/usage.py +++ b/src/dstack/_internal/server/services/usage.py @@ -1,6 +1,5 @@ -"""Transactional receipt of Gateway minute counters; no pricing or quota decisions.""" +"""Transactional receipt of Gateway minute counters.""" -import json import uuid from dataclasses import dataclass @@ -10,7 +9,17 @@ from sqlalchemy.ext.asyncio import AsyncSession from dstack._internal.proxy.lib.schemas.usage import UsageBatch -from dstack._internal.server.models import UsageBatchModel, UsageCounterModel +from dstack._internal.server.models import UsageBatchModel +from dstack._internal.utils.common import get_current_datetime + +_COUNTER_FIELDS = ( + "prompt_tokens", + "cached_prompt_tokens", + "completion_tokens", + "total_tokens", + "unknown_usage_attempts", +) +_MAX_COUNTER = 2**63 - 1 class UsageConflict(ValueError): @@ -32,61 +41,76 @@ async def ingest_usage_batch( ) -> ReceiptResult: # Validate even callers that constructed an unchecked model_copy(). batch = UsageBatch.model_validate(batch.model_dump()) - content = batch.model_dump(mode="json") - content["entries"].sort(key=lambda entry: (entry["consumer_subject_id"], entry["service_id"])) - canonical = json.dumps(content, sort_keys=True, separators=(",", ":")) - for entry in batch.entries: - for name in ( - "prompt_tokens", - "cached_prompt_tokens", - "completion_tokens", - "total_tokens", - "unknown_usage_attempts", - ): - if getattr(entry, name) > 2**63 - 1: - raise ValueError("Usage counter exceeds signed 64-bit storage") - - dialect_insert = ( - pg_insert if session.get_bind().dialect.name == "postgresql" else sqlite_insert - ) - batch_record_id = uuid.uuid4() - created = None + entries = _normalize_entries(batch) if gateway_id is not None: - # INSERT first avoids SQLite read-to-write upgrades and serializes PG conflicts. + dialect_insert = ( + pg_insert if session.get_bind().dialect.name == "postgresql" else sqlite_insert + ) + received_at = get_current_datetime() + rows = [ + { + "id": uuid.uuid4(), + "gateway_replica_id": gateway_replica_id, + "gateway_id": gateway_id, + "batch_id": batch.batch_id, + "interval_start": batch.interval_start, + "interval_end": batch.interval_end, + "received_at": received_at, + "batch_row_number": number, + "user_id": user_id, + "run_id": run_id, + **counters, + } + for number, ((user_id, run_id), counters) in enumerate(sorted(entries.items())) + ] + # Row zero claims both delivery keys. A conflict can wait for a competing + # transaction and must be resolved against its entire committed batch. created = await session.scalar( dialect_insert(UsageBatchModel) - .values( - id=batch_record_id, - gateway_replica_id=gateway_replica_id, - gateway_id=gateway_id, - batch_id=batch.batch_id, - interval_start=batch.interval_start, - interval_end=batch.interval_end, - content=canonical, - ) + .values(rows[0]) .on_conflict_do_nothing() .returning(UsageBatchModel.id) ) - if created is None: - existing = ( - await session.execute( - select(UsageBatchModel.content, UsageBatchModel.gateway_id).where( - UsageBatchModel.gateway_replica_id == gateway_replica_id, - UsageBatchModel.batch_id == batch.batch_id, - ) + if created is not None: + if len(rows) > 1: + await session.execute(insert(UsageBatchModel), rows[1:]) + return ReceiptResult(batch.batch_id, inserted=True) + + existing = ( + await session.scalars( + select(UsageBatchModel).where( + UsageBatchModel.gateway_replica_id == gateway_replica_id, + UsageBatchModel.batch_id == batch.batch_id, ) - ).one_or_none() - if existing is None or existing.content != canonical: - raise UsageConflict("Missing source, conflicting content or duplicate minute") - if gateway_id is not None and existing.gateway_id not in (None, gateway_id): - raise UsageConflict("Historical Gateway identity cannot change") - return ReceiptResult(batch.batch_id, inserted=False) - if batch.entries: - await session.execute( - insert(UsageCounterModel), - [ - {"usage_baches_id": batch_record_id, **entry.model_dump()} - for entry in batch.entries - ], ) - return ReceiptResult(batch.batch_id, inserted=True) + ).all() + for row in existing: + if gateway_id is not None and row.gateway_id != gateway_id: + raise UsageConflict("Historical Gateway identity cannot change") + if row.interval_start != batch.interval_start or row.interval_end != batch.interval_end: + raise UsageConflict("Historical batch interval cannot change") + stored_entries = { + (row.user_id, row.run_id): {name: getattr(row, name) for name in _COUNTER_FIELDS} + for row in existing + } + if stored_entries != entries: + raise UsageConflict("Missing source, conflicting content or duplicate minute") + return ReceiptResult(batch.batch_id, inserted=False) + + +def _normalize_entries(batch: UsageBatch) -> dict[tuple[uuid.UUID, uuid.UUID], dict[str, int]]: + if not batch.entries: + raise ValueError("Usage batch must contain at least one entry") + entries = {} + for entry in batch.entries: + try: + key = uuid.UUID(entry.consumer_subject_id), uuid.UUID(entry.service_id) + except ValueError as exc: + raise ValueError("Usage entry requires valid user and run UUIDs") from exc + if key in entries: + raise ValueError("Duplicate usage key after UUID normalization") + counters = {name: getattr(entry, name) for name in _COUNTER_FIELDS} + if any(value > _MAX_COUNTER for value in counters.values()): + raise ValueError("Usage counter exceeds signed 64-bit storage") + entries[key] = counters + return entries diff --git a/src/tests/_internal/server/background/pipeline_tasks/test_gateway_replicas.py b/src/tests/_internal/server/background/pipeline_tasks/test_gateway_replicas.py index 5b584281ee..ff355c9592 100644 --- a/src/tests/_internal/server/background/pipeline_tasks/test_gateway_replicas.py +++ b/src/tests/_internal/server/background/pipeline_tasks/test_gateway_replicas.py @@ -38,7 +38,6 @@ ServiceRegistrationModel, ServiceReplicaRegistrationModel, UsageBatchModel, - UsageCounterModel, ) from dstack._internal.server.testing.common import ( AsyncContextManager, @@ -677,7 +676,8 @@ class TestGatewayReplicaWorkerRunning: async def test_collects_minute_batch_for_claimed_replica( self, test_db, session, worker, mock_gateway_connection ): - project = await create_project(session) + user = await create_user(session) + project = await create_project(session, owner=user) backend = await create_backend(session, project.id) gateway = await create_gateway( session, project.id, backend.id, status=GatewayStatus.RUNNING @@ -687,16 +687,18 @@ async def test_collects_minute_batch_for_claimed_replica( await session.commit() mock_gateway_connection.return_value.ip_address = replica.ip_address client = _get_client_mock(mock_gateway_connection) - client.fetch_usage_batches.return_value = UsageBatchPage(batches=[batch()]) + client.fetch_usage_batches.return_value = UsageBatchPage(batches=[batch(user.id)]) client.list_services.return_value = [] await worker.process(_replica_to_pipeline_item(replica)) - receipt = (await session.scalars(select(UsageBatchModel))).one_or_none() - assert receipt is not None - assert (receipt.gateway_replica_id, receipt.gateway_id) == (replica.id, gateway.id) - counter = (await session.scalars(select(UsageCounterModel))).one() - assert counter.usage_baches_id == receipt.id and counter.total_tokens == 23 + row = (await session.scalars(select(UsageBatchModel))).one() + assert (row.gateway_replica_id, row.gateway_id, row.user_id) == ( + replica.id, + gateway.id, + user.id, + ) + assert row.batch_row_number == 0 and row.total_tokens == 23 client.acknowledge_usage.assert_awaited_once_with(["batch-1"]) @pytest.mark.parametrize( @@ -788,7 +790,8 @@ async def test_running_to_terminating_when_scaled_in( sealed=waiting != "inflight", empty=waiting == "drained" ) if waiting == "ack_failed": - client.fetch_usage_batches.return_value = UsageBatchPage(batches=[batch()]) + user = await create_user(session) + client.fetch_usage_batches.return_value = UsageBatchPage(batches=[batch(user.id)]) client.acknowledge_usage.side_effect = TimeoutError("ACK timed out") elif waiting == "unreachable": client.drain_usage.side_effect = TimeoutError("Gateway is unavailable") @@ -802,6 +805,10 @@ async def test_running_to_terminating_when_scaled_in( else: assert replica.status == GatewayReplicaStatus.RUNNING assert replica.active and replica.scale_in + if waiting == "ack_failed": + row = (await session.scalars(select(UsageBatchModel))).one() + assert (row.batch_id, row.batch_row_number, row.total_tokens) == ("batch-1", 0, 23) + client.acknowledge_usage.assert_awaited_once_with(["batch-1"]) assert replica.lock_token is None diff --git a/src/tests/_internal/server/services/gateways/test_usage.py b/src/tests/_internal/server/services/gateways/test_usage.py index e013db6264..6eea52e510 100644 --- a/src/tests/_internal/server/services/gateways/test_usage.py +++ b/src/tests/_internal/server/services/gateways/test_usage.py @@ -4,12 +4,13 @@ import uuid from contextlib import asynccontextmanager from datetime import timedelta +from functools import partial from unittest.mock import Mock import httpx import pytest import pytest_asyncio -from sqlalchemy import select, update +from sqlalchemy import delete, select, update from sqlalchemy.exc import OperationalError from dstack._internal.proxy.lib.schemas.usage import ( @@ -24,7 +25,6 @@ GatewayModel, GatewayReplicaModel, UsageBatchModel, - UsageCounterModel, ) from dstack._internal.server.services.gateways import usage from dstack._internal.server.services.gateways.connection import GatewayConnection @@ -37,7 +37,8 @@ create_user, ) from dstack._internal.utils.common import get_current_datetime -from tests._internal.server.services.test_usage import batch +from tests._internal.server.services.test_usage import OTHER_RUN_ID, entry +from tests._internal.server.services.test_usage import batch as make_batch class GatewayQueue: @@ -72,9 +73,18 @@ async def claim(session, replica): @pytest_asyncio.fixture -async def replica(session): - user = await create_user(session) - project = await create_project(session, owner=user) +async def usage_user(session): + return await create_user(session) + + +@pytest.fixture +def batch(usage_user): + return partial(make_batch, usage_user.id) + + +@pytest_asyncio.fixture +async def replica(session, usage_user): + project = await create_project(session, owner=usage_user) backend = await create_backend(session, project.id) gateway = await create_gateway(session, project.id, backend.id) replica = await create_gateway_replica(session, backend, gateway_id=gateway.id) @@ -83,10 +93,11 @@ async def replica(session): @pytest.mark.asyncio +@pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) class TestDrainGatewayUsage: @pytest.mark.parametrize("unsupported", [False, True]) async def test_continues_collecting_closed_minutes_while_drain_is_pending( - self, session, replica, monkeypatch, unsupported + self, session, replica, batch, monkeypatch, unsupported ): queue = GatewayQueue(replica.ip_address, [batch()]) @@ -103,9 +114,9 @@ async def waiting(): queue.connection, replica.id, replica.gateway_id, replica.lock_token ) assert queue.acks == [["batch-1"]] - assert (await session.scalars(select(UsageCounterModel.total_tokens))).all() == [23] + assert (await session.scalars(select(UsageBatchModel.total_tokens))).all() == [23] - async def test_recovers_lost_final_ack_response(self, session, replica, monkeypatch): + async def test_recovers_lost_final_ack_response(self, session, replica, batch, monkeypatch): queue = GatewayQueue(replica.ip_address, [batch()]) acknowledge = queue.acknowledge_usage @@ -118,7 +129,7 @@ async def lose_response(ids): assert not await usage.drain_gateway_usage(*args) assert queue.acks == [["batch-1"]] and queue.items == [] assert await usage.drain_gateway_usage(*args) - assert (await session.scalars(select(UsageCounterModel.total_tokens))).all() == [23] + assert (await session.scalars(select(UsageBatchModel.total_tokens))).all() == [23] async def test_does_not_start_drain_for_stale_claim_or_different_gateway( self, replica, monkeypatch @@ -141,12 +152,14 @@ async def empty(): @pytest.mark.asyncio +@pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) class TestCollectGatewayUsage: - @pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) async def test_commit_before_ack_and_retry_after_lost_ack( - self, session, test_db, replica, monkeypatch + self, session, test_db, replica, batch, usage_user, monkeypatch ): - queue = GatewayQueue(replica.ip_address, [batch()]) + entries = [entry(usage_user.id), entry(usage_user.id, OTHER_RUN_ID, completion=7)] + items = [batch(entries=entries), batch("next", offset=1)] + queue = GatewayQueue(replica.ip_address, items) sessions = [] get_session = test_db.get_session @@ -168,27 +181,39 @@ async def tracked_fetch(limit): async def lose_first_ack(ids): transactions_during_io.append(any(s.in_transaction() for s in sessions)) async with get_session() as observer: - batches = (await observer.scalars(select(UsageBatchModel.batch_id))).all() - counters = (await observer.scalars(select(UsageCounterModel.total_tokens))).all() - observed_at_ack.append((ids, batches, counters)) + rows = ( + await observer.execute( + select( + UsageBatchModel.batch_id, + UsageBatchModel.batch_row_number, + UsageBatchModel.total_tokens, + ).order_by( + UsageBatchModel.interval_start, UsageBatchModel.batch_row_number + ) + ) + ).all() + observed_at_ack.append((ids, rows)) raise httpx.WriteError("ACK lost in transit") monkeypatch.setattr(queue, "fetch_usage_batches", tracked_fetch) monkeypatch.setattr(queue, "acknowledge_usage", lose_first_ack) await usage.collect_gateway_usage(queue.connection, replica.id, replica.lock_token) assert transactions_during_io == [False, False] - assert observed_at_ack == [(["batch-1"], ["batch-1"], [23])] - assert queue.items == [batch()] + assert observed_at_ack == [ + (["batch-1", "next"], [("batch-1", 0, 23), ("batch-1", 1, 27), ("next", 0, 23)]) + ] + assert queue.items == items + queue.items = [batch(entries=entries[::-1]), items[1]] monkeypatch.setattr(queue, "acknowledge_usage", acknowledge) # A replacement worker fetches the already committed page from the Gateway. await claim(session, replica) await usage.collect_gateway_usage(queue.connection, replica.id, replica.lock_token) assert queue.fetches == 2 - assert queue.acks == [["batch-1"]] + assert queue.acks == [["batch-1", "next"]] assert queue.items == [] - assert (await session.scalars(select(UsageCounterModel.total_tokens))).all() == [23] + assert sorted(await session.scalars(select(UsageBatchModel.total_tokens))) == [23, 23, 27] - async def test_conflict_rolls_back_entire_page_without_ack(self, session, replica): + async def test_conflict_rolls_back_entire_page_without_ack(self, session, replica, batch): await ingest_usage_batch(session, replica.id, replica.gateway_id, batch()) await session.commit() items = [batch("new", offset=1), batch(tokens=4)] @@ -198,9 +223,33 @@ async def test_conflict_rolls_back_entire_page_without_ack(self, session, replic assert queue.acks == [] assert queue.items == items assert (await session.scalars(select(UsageBatchModel.batch_id))).all() == ["batch-1"] - assert (await session.scalars(select(UsageCounterModel.total_tokens))).all() == [23] + assert (await session.scalars(select(UsageBatchModel.total_tokens))).all() == [23] + + async def test_invalid_last_row_rolls_back_page_without_ack( + self, session, replica, batch, usage_user + ): + missing = uuid.UUID(int=2**128 - 1) + assert usage_user.id < missing + last = batch("last", offset=1, entries=[entry(usage_user.id), entry(missing)]) + items = [batch(), last] + queue = GatewayQueue(replica.ip_address, items) + await usage.collect_gateway_usage(queue.connection, replica.id, replica.lock_token) + assert queue.fetches == 1 + assert queue.acks == [] and queue.items == items + assert (await session.scalars(select(UsageBatchModel))).all() == [] - async def test_page_budget_leaves_remainder_for_next_poll(self, session, replica, monkeypatch): + async def test_empty_page_caught_up_but_empty_batch_unacknowledged(self, replica, batch): + queue = GatewayQueue(replica.ip_address, []) + args = queue.connection, replica.id, replica.gateway_id, replica.lock_token + assert await usage.drain_gateway_usage(*args) + queue.items = [batch(entries=[])] + assert not await usage.drain_gateway_usage(*args) + assert queue.fetches == 1 + assert queue.acks == [] and queue.items == [batch(entries=[])] + + async def test_page_budget_leaves_remainder_for_next_poll( + self, session, replica, batch, monkeypatch + ): items = [batch(f"b-{i}", i) for i in range(5)] queue = GatewayQueue(replica.ip_address, items) monkeypatch.setattr(usage, "PAGE_SIZE", 2) @@ -220,7 +269,9 @@ async def test_page_budget_leaves_remainder_for_next_poll(self, session, replica "b-4", ] - async def test_timeout_during_fetch_leaves_page_pending(self, session, replica, monkeypatch): + async def test_timeout_during_fetch_leaves_page_pending( + self, session, replica, batch, monkeypatch + ): queue = GatewayQueue(replica.ip_address, [batch()]) fetch = queue.fetch_usage_batches @@ -243,7 +294,9 @@ async def fetch_past_deadline(limit): assert (await session.scalars(select(UsageBatchModel))).all() == [] @pytest.mark.parametrize("status_code", [404, 405]) - async def test_old_gateway_endpoint_skipped(self, replica, monkeypatch, caplog, status_code): + async def test_old_gateway_endpoint_skipped( + self, replica, batch, monkeypatch, caplog, status_code + ): queue = GatewayQueue(replica.ip_address, [batch()]) async def unavailable(limit): @@ -262,7 +315,7 @@ async def unavailable(limit): r.levelno >= logging.WARNING and r.name == usage.__name__ for r in caplog.records ) - async def test_multiple_replicas_and_legacy_parent(self, session, replica): + async def test_multiple_replicas_and_legacy_parent(self, session, replica, batch): backend = await session.get(BackendModel, replica.backend_id) second = await create_gateway_replica( session, backend, gateway_id=replica.gateway_id, ip_address="2.2.2.2" @@ -280,11 +333,13 @@ async def test_multiple_replicas_and_legacy_parent(self, session, replica): assert {row.gateway_replica_id for row in rows} == {replica.id, second.id, legacy.id} assert {row.gateway_id for row in rows} == {parent.id} - async def test_unbound_source_can_only_ack_historical_replay(self, session, replica): + async def test_unbound_source_can_only_ack_historical_replay(self, session, replica, batch): await ingest_usage_batch(session, replica.id, replica.gateway_id, batch()) parent_id = replica.gateway_id - replica.gateway_id = None + await session.execute(delete(GatewayModel).where(GatewayModel.id == parent_id)) await session.commit() + await session.refresh(replica) + assert replica.gateway_id is None queue = GatewayQueue(replica.ip_address, [batch()]) await usage.collect_gateway_usage(queue.connection, replica.id, replica.lock_token) assert queue.acks == [["batch-1"]] @@ -295,14 +350,14 @@ async def test_unbound_source_can_only_ack_historical_replay(self, session, repl row = (await session.scalars(select(UsageBatchModel))).one() assert row.batch_id == "batch-1" and row.gateway_id == parent_id - async def test_ambiguous_address_is_skipped(self, session, replica): + async def test_ambiguous_address_is_skipped(self, session, replica, batch): backend = await session.get(BackendModel, replica.backend_id) await create_gateway_replica(session, backend, ip_address=replica.ip_address) queue = GatewayQueue(replica.ip_address, [batch()]) await usage.collect_gateway_usage(queue.connection, replica.id, replica.lock_token) assert queue.fetches == 0 - async def test_address_must_belong_to_claimed_replica(self, session, replica): + async def test_address_must_belong_to_claimed_replica(self, session, replica, batch): backend = await session.get(BackendModel, replica.backend_id) other = await create_gateway_replica( session, backend, gateway_id=replica.gateway_id, ip_address="2.2.2.2" @@ -316,7 +371,9 @@ async def test_address_must_belong_to_claimed_replica(self, session, replica): await usage.collect_gateway_usage(queue.connection, replica.id, replica.lock_token) assert queue.fetches == 0 - async def test_conflicting_modern_and_legacy_parents_are_skipped(self, session, replica): + async def test_conflicting_modern_and_legacy_parents_are_skipped( + self, session, replica, batch + ): backend = await session.get(BackendModel, replica.backend_id) other_parent = await create_gateway(session, backend.project_id, backend.id, name="other") other_parent.gateway_replica_id = replica.id @@ -325,9 +382,8 @@ async def test_conflicting_modern_and_legacy_parents_are_skipped(self, session, await usage.collect_gateway_usage(queue.connection, replica.id, replica.lock_token) assert queue.fetches == 0 - @pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) async def test_takeover_during_fetch_fences_stale_page( - self, session, replica, monkeypatch, test_db + self, session, replica, batch, monkeypatch, test_db ): queue = GatewayQueue(replica.ip_address, [batch()]) fetch = queue.fetch_usage_batches @@ -349,7 +405,7 @@ async def fetch_then_take_over(limit): assert queue.fetches == 1 await usage.collect_gateway_usage(queue.connection, replica.id, replica.lock_token) assert queue.acks == [["batch-1"]] - assert (await session.scalars(select(UsageCounterModel.total_tokens))).all() == [23] + assert (await session.scalars(select(UsageBatchModel.total_tokens))).all() == [23] @pytest.mark.asyncio @@ -366,7 +422,7 @@ async def sqlite_db(self, tmp_path): await db.engine.dispose() async def test_claim_cannot_change_between_revalidation_and_insert( - self, session, replica, test_db, monkeypatch + self, session, replica, batch, test_db, monkeypatch ): queue = GatewayQueue(replica.ip_address, [batch()]) next_token = uuid.uuid4() @@ -399,4 +455,4 @@ async def ingest_with_competing_claim(*args): await contender.execute(takeover) await contender.commit() assert await session.scalar(select(GatewayReplicaModel.lock_token)) == next_token - assert (await session.scalars(select(UsageCounterModel.total_tokens))).all() == [23] + assert (await session.scalars(select(UsageBatchModel.total_tokens))).all() == [23] diff --git a/src/tests/_internal/server/services/test_usage.py b/src/tests/_internal/server/services/test_usage.py index d4e5d69a1b..54798e443f 100644 --- a/src/tests/_internal/server/services/test_usage.py +++ b/src/tests/_internal/server/services/test_usage.py @@ -3,126 +3,251 @@ from datetime import datetime, timedelta, timezone import pytest -from sqlalchemy import func, select +from sqlalchemy import delete, func, select +from sqlalchemy.exc import IntegrityError from dstack._internal.proxy.lib.schemas.usage import UsageBatch, UsageEntry -from dstack._internal.server.models import UsageBatchModel, UsageCounterModel +from dstack._internal.server.models import GatewayModel, RunModel, UsageBatchModel, UserModel from dstack._internal.server.services.usage import UsageConflict, ingest_usage_batch +from dstack._internal.server.services.users import delete_users +from dstack._internal.server.testing.common import ( + create_backend, + create_gateway, + create_project, + create_repo, + create_run, + create_user, +) + +RUN_ID = uuid.UUID("a" * 32) +OTHER_RUN_ID = uuid.UUID("b" * 32) + + +def entry(user_id, run_id=RUN_ID, prompt=20, cached=5, completion=3, unknown=0): + return UsageEntry( + consumer_subject_id=user_id.hex, + service_id=run_id.hex, + prompt_tokens=prompt, + cached_prompt_tokens=cached, + completion_tokens=completion, + total_tokens=prompt + completion, + unknown_usage_attempts=unknown, + ) -def batch(batch_id="batch-1", offset=0, tokens=3): - start = datetime(2026, 11, 16, 10, tzinfo=timezone.utc) + timedelta(minutes=offset) +def batch(user_id, batch_id="batch-1", offset=0, tokens=3, *, entries=None): + start = datetime(2026, 11, 20, 10, tzinfo=timezone.utc) + timedelta(minutes=offset) return UsageBatch( batch_id=batch_id, interval_start=start, interval_end=start + timedelta(minutes=1), - entries=[ - UsageEntry( - consumer_subject_id="1" * 32, - service_id="a" * 32, - prompt_tokens=20, - cached_prompt_tokens=5, - completion_tokens=tokens, - total_tokens=20 + tokens, - ) - ], + entries=[entry(user_id, completion=tokens)] if entries is None else entries, ) @pytest.mark.asyncio @pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) -async def test_commit_replay_conflict_and_historical_ids(test_db): - gateway = uuid.uuid4() - parent = uuid.uuid4() - item = batch(tokens=2**40) - async with test_db.get_session() as session: - assert (await ingest_usage_batch(session, gateway, parent, item)).inserted - await session.commit() - async with test_db.get_session() as session: - assert not (await ingest_usage_batch(session, gateway, parent, item)).inserted +class TestIngestUsageBatch: + async def test_numbered_rows_and_reordered_replay(self, session): + user = await create_user(session) + other = await create_user(session, name="another") + replica, parent = uuid.uuid4(), uuid.uuid4() + first = entry(user.id, prompt=15, cached=3, completion=5) + second = entry(user.id, OTHER_RUN_ID, prompt=5, cached=0, completion=2) + unknown = entry(other.id, prompt=0, cached=0, completion=0, unknown=1) + item = batch(user.id, entries=[second, first]) + next_minute = batch(user.id, "next-minute", offset=1, entries=[unknown, first]) + assert (await ingest_usage_batch(session, replica, parent, item)).inserted + assert (await ingest_usage_batch(session, replica, parent, next_minute)).inserted await session.commit() - async with test_db.get_session() as session: - with pytest.raises(UsageConflict): - await ingest_usage_batch(session, gateway, parent, batch(tokens=4)) - await session.rollback() - row = (await session.scalars(select(UsageCounterModel))).one() - assert row.completion_tokens == 2**40 - assert row.consumer_subject_id == "1" * 32 and row.service_id == "a" * 32 - assert await session.scalar(select(func.count()).select_from(UsageBatchModel)) == 1 - # Historical attribution is retained even without corresponding live user/run rows. + rows = ( + await session.scalars( + select(UsageBatchModel).order_by( + UsageBatchModel.interval_start, UsageBatchModel.batch_row_number + ) + ) + ).all() + assert [row.batch_row_number for row in rows] == [0, 1, 0, 1] + assert [(row.user_id, row.run_id, row.total_tokens) for row in rows[:2]] == [ + (user.id, RUN_ID, 20), + (user.id, OTHER_RUN_ID, 7), + ] + assert sum(row.total_tokens for row in rows[:2]) == 27 + assert rows[0].received_at == rows[1].received_at + assert [(row.user_id, row.unknown_usage_attempts) for row in rows[2:]] == sorted( + [(user.id, 0), (other.id, 1)] + ) + assert len({row.id for row in rows}) == 4 + replay = batch( + user.id, + entries=[ + first.model_copy(update={"consumer_subject_id": str(user.id).upper()}), + second.model_copy(update={"service_id": str(OTHER_RUN_ID).upper()}), + ], + ) + assert not (await ingest_usage_batch(session, replica, parent, replay)).inserted + await session.commit() + persisted = ( + await session.scalars( + select(UsageBatchModel).order_by( + UsageBatchModel.interval_start, UsageBatchModel.batch_row_number + ) + ) + ).all() + assert persisted == rows + + async def test_identity_interval_and_content_conflicts(self, session): + user = await create_user(session) + replica, parent = uuid.uuid4(), uuid.uuid4() + first = entry(user.id, completion=2**40) + second = entry(user.id, OTHER_RUN_ID) + third = entry(user.id, uuid.uuid4()) + original = batch(user.id, entries=[first, second]) + await ingest_usage_batch(session, replica, parent, original) + await session.commit() + for gateway, item in [ + (uuid.uuid4(), original), + (parent, batch(user.id, offset=1, entries=[first, second])), + (parent, batch(user.id, entries=[first])), + (parent, batch(user.id, entries=[first, second, third])), + ( + parent, + batch( + user.id, + entries=[first, second.model_copy(update={"unknown_usage_attempts": 1})], + ), + ), + (parent, batch(user.id, "duplicate-minute", entries=[third])), + ]: + with pytest.raises(UsageConflict): + await ingest_usage_batch(session, replica, gateway, item) + await session.rollback() -@pytest.mark.asyncio -@pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) -async def test_rollback_leaves_no_receipt_or_entries(test_db): - async with test_db.get_session() as session: - await ingest_usage_batch(session, uuid.uuid4(), uuid.uuid4(), batch()) + assert (await ingest_usage_batch(session, uuid.uuid4(), parent, original)).inserted + await session.commit() + assert await session.scalar(select(func.count()).select_from(UsageBatchModel)) == 4 + assert await session.scalar(select(func.sum(UsageBatchModel.total_tokens))) == 2 * ( + 2**40 + 43 + ) + + @pytest.mark.parametrize("field", ["consumer_subject_id", "service_id"]) + async def test_rejects_malformed_uuid(self, session, field): + user = await create_user(session) + item = batch(user.id, entries=[entry(user.id).model_copy(update={field: "malformed"})]) + with pytest.raises(ValueError, match="UUID"): + await ingest_usage_batch(session, uuid.uuid4(), uuid.uuid4(), item) + assert await session.scalar(select(func.count()).select_from(UsageBatchModel)) == 0 + + @pytest.mark.parametrize("invalid", ["duplicate", "overflow", "empty"]) + async def test_rejects_invalid_entries(self, session, invalid): + user = await create_user(session) + first = entry(user.id) + entries, message = { + "duplicate": ( + [first, first.model_copy(update={"service_id": str(RUN_ID)})], + "Duplicate", + ), + "overflow": ([entry(user.id, unknown=2**63)], "signed 64-bit"), + "empty": ([], "entry"), + }[invalid] + with pytest.raises(ValueError, match=message): + await ingest_usage_batch( + session, uuid.uuid4(), uuid.uuid4(), batch(user.id, entries=entries) + ) + assert await session.scalar(select(func.count()).select_from(UsageBatchModel)) == 0 + + async def test_remaining_insert_failure_rolls_back_row_zero(self, session): + user = await create_user(session) + missing = uuid.UUID(int=2**128 - 1) + user_id = user.id + assert user_id < missing + replica, parent = uuid.uuid4(), uuid.uuid4() + item = batch(user_id, entries=[entry(user_id), entry(missing)]) + with pytest.raises(IntegrityError, match="FOREIGN KEY|foreign key"): + await ingest_usage_batch(session, replica, parent, item) await session.rollback() - async with test_db.get_session() as session: - for model in [UsageBatchModel, UsageCounterModel]: - assert await session.scalar(select(func.count()).select_from(model)) == 0 + assert await session.scalar(select(func.count()).select_from(UsageBatchModel)) == 0 + assert (await ingest_usage_batch(session, replica, parent, batch(user_id))).inserted + await session.commit() + async def test_history_survives_deleted_run_gateway_and_soft_deleted_user(self, session): + user = await create_user(session) + admin = await create_user(session, name="another") + project = await create_project(session, owner=user) + repo = await create_repo(session, project_id=project.id) + backend = await create_backend(session, project.id) + gateway = await create_gateway(session, project.id, backend.id) + run = await create_run(session, project, repo, user, gateway=gateway) + replica, parent, user_id, run_id = uuid.uuid4(), gateway.id, user.id, run.id + item = batch(user_id, entries=[entry(user_id, run_id)]) + await ingest_usage_batch(session, replica, parent, item) + await session.commit() + await session.execute(delete(RunModel).where(RunModel.id == run_id)) + await delete_users(session, admin, [user.name]) + await session.commit() + assert user.deleted and not user.active -@pytest.mark.asyncio -@pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) -async def test_identity_and_interval_conflicts(test_db): - gateway = uuid.uuid4() - parent = uuid.uuid4() - async with test_db.get_session() as session: - await ingest_usage_batch(session, gateway, parent, batch()) + delayed = batch(user_id, "next-minute", offset=1, entries=[entry(user_id, run_id)]) + assert (await ingest_usage_batch(session, replica, parent, delayed)).inserted await session.commit() - for parent_id, item in [(uuid.uuid4(), batch()), (parent, batch("duplicate-minute"))]: - async with test_db.get_session() as session: - with pytest.raises(UsageConflict): - await ingest_usage_batch(session, gateway, parent_id, item) - await session.rollback() - # An independent replica may legitimately use the same batch ID and minute. - async with test_db.get_session() as session: - assert (await ingest_usage_batch(session, uuid.uuid4(), parent, batch())).inserted + await session.execute(delete(GatewayModel).where(GatewayModel.id == parent)) await session.commit() + assert not (await ingest_usage_batch(session, replica, None, item)).inserted + with pytest.raises(UsageConflict): + await ingest_usage_batch(session, replica, None, batch(user_id, "new", offset=2)) + report = select(func.sum(UsageBatchModel.total_tokens)).where( + UsageBatchModel.gateway_id == parent, + UsageBatchModel.user_id == user_id, + UsageBatchModel.run_id == run_id, + ) + assert await session.scalar(report) == 46 + with pytest.raises(IntegrityError, match="FOREIGN KEY|foreign key"): + await session.execute(delete(UserModel).where(UserModel.id == user_id)) + await session.rollback() + assert await session.scalar(report) == 46 + @pytest.mark.asyncio @pytest.mark.parametrize("test_db", ["postgres"], indirect=True) -async def test_concurrent_pollers_commit_once(test_db): - gateway = uuid.uuid4() - parent = uuid.uuid4() +@pytest.mark.parametrize("competing_minute", [False, True]) +async def test_concurrent_pollers_commit_once(test_db, session, competing_minute): + user = await create_user(session) + replica, parent = uuid.uuid4(), uuid.uuid4() + first, second = entry(user.id), entry(user.id, OTHER_RUN_ID) + original = batch(user.id, entries=[first, second]) + contender = ( + batch(user.id, "competing-minute", entries=[entry(user.id, uuid.uuid4())]) + if competing_minute + else batch(user.id, entries=[second, first]) + ) + + assert (await ingest_usage_batch(session, replica, parent, original)).inserted + contender_pid = asyncio.get_running_loop().create_future() async def ingest(): - async with test_db.get_session() as session: - result = await ingest_usage_batch(session, gateway, parent, batch()) - await session.commit() + async with test_db.get_session() as other: + contender_pid.set_result(await other.scalar(select(func.pg_backend_pid()))) + result = await ingest_usage_batch(other, replica, parent, contender) + await other.commit() return result.inserted - assert sorted(await asyncio.gather(ingest(), ingest())) == [False, True] - async with test_db.get_session() as session: - assert await session.scalar(select(func.count()).select_from(UsageCounterModel)) == 1 - - -@pytest.mark.asyncio -@pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True) -async def test_history_snapshot_missing_parent_and_renamed_link(test_db): - replica, parent = uuid.uuid4(), uuid.uuid4() - async with test_db.get_session() as session: - await ingest_usage_batch(session, replica, parent, batch()) - await session.commit() - async with test_db.get_session() as session: - assert not (await ingest_usage_batch(session, replica, None, batch())).inserted - row = (await session.scalars(select(UsageBatchModel))).one() - counter = (await session.scalars(select(UsageCounterModel))).one() - assert row.gateway_replica_id == replica - assert row.gateway_id == parent - assert counter.usage_baches_id == row.id - # No live infrastructure rows are needed to read the receipt's source. - assert counter.total_tokens == 23 - with pytest.raises(UsageConflict): - await ingest_usage_batch(session, replica, None, batch("new", offset=1)) - await session.rollback() - async with test_db.get_session() as session: - row = (await session.scalars(select(UsageBatchModel))).one() - row.gateway_id = None # Represents unresolved pre-upgrade history. + async def receive(): + if competing_minute: + with pytest.raises(UsageConflict): + await ingest() + else: + assert not await ingest() + + winner_pid = await session.scalar(select(func.pg_backend_pid())) + async with asyncio.timeout(5), asyncio.TaskGroup() as tasks: + tasks.create_task(receive()) + pid = await contender_pid + blockers = select(func.pg_blocking_pids(pid)) + async with test_db.get_session() as observer: + while winner_pid not in (await observer.scalar(blockers)): + pass await session.commit() - async with test_db.get_session() as session: - assert not (await ingest_usage_batch(session, replica, parent, batch())).inserted - row = (await session.scalars(select(UsageBatchModel))).one() - assert row.gateway_id is None # Replay cannot silently rewrite history. + assert await session.scalar(select(func.count()).select_from(UsageBatchModel)) == 2 + assert await session.scalar(select(func.sum(UsageBatchModel.total_tokens))) == 46 diff --git a/src/tests/_internal/server/test_usage_migration.py b/src/tests/_internal/server/test_usage_migration.py index e5bf608437..1a7a1cc881 100644 --- a/src/tests/_internal/server/test_usage_migration.py +++ b/src/tests/_internal/server/test_usage_migration.py @@ -1,16 +1,17 @@ -"""Initial DS-002 migration creates the final schema without rewriting existing data.""" +"""Exercise the rewritten Gateway usage revision with isolated databases.""" import importlib import uuid -from datetime import datetime +from datetime import datetime, timedelta import pytest import sqlalchemy as sa from alembic.migration import MigrationContext from alembic.operations import Operations -from sqlalchemy.ext.asyncio import create_async_engine from sqlalchemy_utils import UUIDType +from dstack._internal.server.db import Database + MIGRATION = ( "dstack._internal.server.migrations.versions.2026." "11_16_1201_9a2e8f1f3c37_add_gateway_usage_batches" @@ -18,107 +19,144 @@ def run_case(conn, populated): - # Independent pre-existing data makes an accidental rewrite/drop observable. - meta = sa.MetaData() - gateways = sa.Table( - "gateways", - meta, - sa.Column("id", UUIDType(binary=False), primary_key=True), - sa.Column("name", sa.String(), nullable=False), - ) - replicas = sa.Table( - "gateway_computes", - meta, - sa.Column("id", UUIDType(binary=False), primary_key=True), - sa.Column("gateway_id", UUIDType(binary=False)), - ) - meta.create_all(conn) - parent, replica = uuid.uuid4(), uuid.uuid4() - conn.execute(gateways.insert().values(id=parent, name="existing-gateway")) - conn.execute(replicas.insert().values(id=replica, gateway_id=parent)) - before = conn.execute(sa.select(gateways)).all(), conn.execute(sa.select(replicas)).all() + # Minimal tables from the parent revision, with data that the new revision must preserve. + metadata = sa.MetaData() + parents = [ + sa.Table(name, metadata, sa.Column("id", UUIDType(binary=False), primary_key=True)) + for name in ("users", "runs", "gateways", "gateway_computes") + ] + metadata.create_all(conn) + user, run, gateway, replica = (uuid.uuid4() for _ in parents) + for table, id_ in zip(parents, (user, run, gateway, replica)): + conn.execute(table.insert().values(id=id_)) migration = importlib.import_module(MIGRATION) + assert (migration.revision, migration.down_revision) == ("9a2e8f1f3c37", "6b5610ff36c1") with Operations.context(MigrationContext.configure(conn)): migration.upgrade() - assert ( - conn.execute(sa.select(gateways)).all(), - conn.execute(sa.select(replicas)).all(), - ) == before inspector = sa.inspect(conn) - assert "usage_collectors" not in inspector.get_table_names() - tables = sa.MetaData() - batches = sa.Table("usage_batches", tables, autoload_with=conn) - counters = sa.Table("usage_counters", tables, autoload_with=conn) - assert {"gateway_id", "gateway_replica_id"} <= set(batches.c.keys()) - assert "collector_id" not in batches.c - assert "usage_baches_id" in counters.c and "receipt_id" not in counters.c - assert inspector.get_foreign_keys("usage_batches") == [] - assert { - tuple(c["column_names"]) for c in inspector.get_unique_constraints("usage_batches") - } == { - ("gateway_replica_id", "batch_id"), - ("gateway_replica_id", "interval_start"), + assert set(inspector.get_table_names()) == {*metadata.tables, "usage_batches"} + batches = sa.Table("usage_batches", sa.MetaData(), autoload_with=conn) + identity = {"id", "user_id", "run_id", "gateway_id", "gateway_replica_id"} + times = {"interval_start", "interval_end", "received_at"} + counters = { + "prompt_tokens", + "cached_prompt_tokens", + "completion_tokens", + "total_tokens", + "unknown_usage_attempts", } - assert inspector.get_pk_constraint("usage_counters")["constrained_columns"] == [ - "usage_baches_id", - "consumer_subject_id", - "service_id", - ] - fk = inspector.get_foreign_keys("usage_counters") - assert len(fk) == 1 - assert fk[0]["constrained_columns"] == ["usage_baches_id"] - assert fk[0]["referred_table"] == "usage_batches" and fk[0]["referred_columns"] == ["id"] + assert set(batches.c.keys()) == identity | times | counters | { + "batch_id", + "batch_row_number", + } + assert all(not col.nullable for col in batches.c) + for name in identity: + coltype = batches.c[name].type + if conn.dialect.name == "sqlite": + assert isinstance(coltype, sa.CHAR) and coltype.length == 32 + else: + assert isinstance(coltype, sa.UUID) + assert all( + isinstance(batches.c[name].type, sa.DateTime) and not batches.c[name].type.timezone + for name in times + ) + assert all(isinstance(batches.c[name].type, sa.BigInteger) for name in counters) + assert batches.c.batch_row_number.type.compile(dialect=conn.dialect) == "INTEGER" + assert batches.c.batch_id.type.length == 128 + assert inspector.get_pk_constraint("usage_batches")["constrained_columns"] == ["id"] + (fk,) = inspector.get_foreign_keys("usage_batches") + assert fk["constrained_columns"] == ["user_id"] + assert fk["referred_table"] == "users" and fk["referred_columns"] == ["id"] + assert fk["options"]["ondelete"] == "RESTRICT" + (pair,) = inspector.get_unique_constraints("usage_batches") + assert pair["column_names"] == ["gateway_replica_id", "batch_id", "user_id", "run_id"] + indexes = { + ix["name"]: ix + for ix in inspector.get_indexes("usage_batches") + if not ix.get("duplicates_constraint") + } + assert {name: ix["column_names"] for name, ix in indexes.items()} == { + "uq_usage_batches_replica_batch": ["gateway_replica_id", "batch_id"], + "uq_usage_batches_replica_minute": ["gateway_replica_id", "interval_start"], + "ix_usage_batches_gateway_interval": ["gateway_id", "interval_start"], + "ix_usage_batches_user_id": ["user_id"], + "ix_usage_batches_run_id": ["run_id"], + } + for index in indexes.values(): + assert index["unique"] == index["name"].startswith("uq_") + if index["unique"]: + predicate = index["dialect_options"][f"{conn.dialect.name}_where"] + assert str(predicate).strip("()") == "batch_row_number = 0" + if not populated: migration.downgrade() - assert set(inspector.get_table_names()) >= {"gateways", "gateway_computes"} - assert "usage_batches" not in sa.inspect(conn).get_table_names() - assert ( - conn.execute(sa.select(gateways)).all(), - conn.execute(sa.select(replicas)).all(), - ) == before + assert set(sa.inspect(conn).get_table_names()) == set(metadata.tables) + for table, id_ in zip(parents, (user, run, gateway, replica)): + assert conn.scalar(sa.select(table.c.id)) == id_ + migration.upgrade() + assert sa.inspect(conn).has_table("usage_batches") return - batch_id = uuid.uuid4().hex - conn.execute( - batches.insert().values( - id=batch_id, - gateway_replica_id=replica.hex, - gateway_id=parent.hex, - batch_id="b1", - interval_start=datetime(2026, 11, 17, 10), - interval_end=datetime(2026, 11, 17, 10, 1), - received_at=datetime(2026, 11, 17, 10, 2), - content='{"fixture":true}', - ) + + def stored_id(value): + return value.hex if conn.dialect.name == "sqlite" else value + + start = datetime(2026, 11, 20, 10) + end = start + timedelta(minutes=1) + common = dict( + gateway_replica_id=stored_id(replica), + gateway_id=stored_id(gateway), + batch_id="B1", + interval_start=start, + interval_end=end, + received_at=end + timedelta(seconds=4), + user_id=stored_id(user), ) - conn.execute( - counters.insert().values( - usage_baches_id=batch_id, - consumer_subject_id="u", - service_id="s", - prompt_tokens=20, - cached_prompt_tokens=5, - completion_tokens=3, - total_tokens=23, + + def add_row(**changes): + row = dict( + **common, + id=stored_id(uuid.uuid4()), + run_id=stored_id(uuid.uuid4()), + batch_row_number=1, + prompt_tokens=15, + cached_prompt_tokens=3, + completion_tokens=5, + total_tokens=20, unknown_usage_attempts=0, ) - ) - rows = conn.execute(sa.select(batches)).all() - conn.execute(replicas.delete()) - conn.execute(gateways.delete()) - assert conn.execute(sa.select(batches)).all() == rows - assert conn.scalar(sa.select(sa.func.sum(counters.c.total_tokens))) == 23 - assert ( - conn.scalar( - sa.select(sa.func.count()).select_from( - counters.join(batches, counters.c.usage_baches_id == batches.c.id) - ) + conn.execute(batches.insert().values(row | changes)) + + add_row(run_id=stored_id(run), batch_row_number=0) + add_row(prompt_tokens=5, cached_prompt_tokens=0, completion_tokens=2, total_tokens=7) + assert conn.execute( + sa.select(batches.c.batch_row_number, batches.c.total_tokens).order_by( + batches.c.batch_row_number ) - == 1 - ) + ).all() == [(0, 20), (1, 7)] + assert conn.scalar(sa.select(sa.func.sum(batches.c.total_tokens))) == 27 + + invalid = [ + dict(batch_row_number=-1), + dict(batch_id="other-batch", batch_row_number=0), + dict(interval_start=end, batch_row_number=0), + dict(run_id=stored_id(run)), + dict(cached_prompt_tokens=16), + dict(total_tokens=21), + dict(user_id=stored_id(uuid.uuid4())), + ] + if conn.dialect.name == "sqlite": + invalid += [dict(batch_row_number=1.5), dict(unknown_usage_attempts=1.5)] + for changes in invalid: + with pytest.raises(sa.exc.IntegrityError), conn.begin_nested(): + add_row(**changes) + + for table in parents[1:]: + conn.execute(table.delete()) + with pytest.raises(sa.exc.IntegrityError), conn.begin_nested(): + conn.execute(parents[0].delete()) with pytest.raises(ValueError, match="backup"): migration.downgrade() - assert conn.execute(sa.select(batches)).all() == rows - assert conn.scalar(sa.select(sa.func.count()).select_from(counters)) == 1 + assert conn.scalar(sa.select(sa.func.sum(batches.c.total_tokens))) == 27 @pytest.mark.asyncio @@ -132,15 +170,17 @@ async def test_initial_usage_schema_preserves_existing_data(tmp_path, request, d if dialect == "sqlite" else request.getfixturevalue("postgres_container") ) - engine = create_async_engine(url) + db = Database(url) schema = "usage_test_" + uuid.uuid4().hex try: - async with engine.begin() as conn: + async with db.engine.begin() as conn: if dialect == "postgres": - await conn.execute(sa.text(f'CREATE SCHEMA "{schema}"')) - await conn.execute(sa.text(f'SET LOCAL search_path TO "{schema}"')) + await conn.exec_driver_sql(f'CREATE SCHEMA "{schema}"') + await conn.exec_driver_sql(f'SET LOCAL search_path TO "{schema}"') + else: + assert await conn.scalar(sa.text("PRAGMA foreign_keys")) == 1 await conn.run_sync(lambda c: run_case(c, populated)) if dialect == "postgres": - await conn.execute(sa.text(f'DROP SCHEMA "{schema}" CASCADE')) + await conn.exec_driver_sql(f'DROP SCHEMA "{schema}" CASCADE') finally: - await engine.dispose() + await db.engine.dispose() From 2f00aad0622c2c9ff05e09c7183333feb9347904 Mon Sep 17 00:00:00 2001 From: Igx22 Date: Fri, 20 Nov 2026 18:34:42 +0700 Subject: [PATCH 6/7] DS-015: Account for long and interrupted Gateway streams --- contributing/PROXY.md | 19 +- src/dstack/_internal/proxy/gateway/models.py | 7 +- .../_internal/proxy/gateway/schemas/config.py | 6 +- .../proxy/gateway/services/metering.py | 12 +- .../proxy/lib/routers/model_proxy.py | 20 +- .../services/model_proxy/clients/openai.py | 46 +-- .../lib/services/model_proxy/stream_usage.py | 156 ++++++++++ .../_internal/proxy/lib/services/usage.py | 16 +- .../proxy/gateway/metering/backend.py | 6 + .../proxy/gateway/metering/test_scenarios.py | 37 ++- .../proxy/lib/services/test_openai_usage.py | 274 +++++++++++++++++- 11 files changed, 554 insertions(+), 45 deletions(-) create mode 100644 src/dstack/_internal/proxy/lib/services/model_proxy/stream_usage.py diff --git a/contributing/PROXY.md b/contributing/PROXY.md index fb943addd3..505ce4f19d 100644 --- a/contributing/PROXY.md +++ b/contributing/PROXY.md @@ -173,9 +173,22 @@ ssh -i /tmp/gateway.key ubuntu@$GATEWAY_IP_ADDR sudo journalctl -u dstack.gatewa ## Gateway usage metering (DS-002) Metering is opt-in per registered OpenAI service via the private `/api/config` field -`usage_metering_profiles` (`service.id` → `vllm-0.19.1-prompt-details`). Legacy updates -that omit the field preserve it; an empty map disables it. Drain changed services -and cross a minute boundary before changing the profile. +`usage_metering_profiles`, which maps each service ID to a profile. Updates that omit +the field preserve it. An empty map disables it. Drain changed services and cross a +minute boundary before changing the profile. + +| Profile | Upstream behavior | +|---|---| +| `vllm-0.19.1-prompt-details` | Original final-only profile. Use it for a route that reports final usage in JSON or an SSE usage-only event. | +| `vllm-0.19.1-per-choice` | vLLM 0.19.1 choice-scoped progress, including through SMG HTTP when the worker forces usage. Older SMG HTTP can drop the per-request continuous option. | +| `dynamo-1.6.2-rust` | Dynamo 1.6.2 default chat processor with request-wide progress and a final usage-only event. | +| `dynamo-1.6.2-vllm` | Dynamo 1.6.2 Python vLLM chat processor with request-wide progress and usage on the finishing choice. | + +The progress profiles request `continuous_usage_stats` privately. Streaming callers +who request usage receive one request-wide final SSE event when the Gateway has a +complete measurement. The collector books the authoritative final or the measured +prefix once in the minute the attempt closes. A prefix contributes to the measured +totals, and `unknown_usage_attempts` includes attempts with an unmeasured remainder. The existing Python model proxy observes backend JSON/SSE usage and obtains a verified user ID from server's additive `authorize_proxy` endpoint. Counters use that user ID diff --git a/src/dstack/_internal/proxy/gateway/models.py b/src/dstack/_internal/proxy/gateway/models.py index c1254fd97b..2e205edd78 100644 --- a/src/dstack/_internal/proxy/gateway/models.py +++ b/src/dstack/_internal/proxy/gateway/models.py @@ -1,11 +1,12 @@ """Things stored in GatewayProxyRepo in addition to those from BaseProxyRepo.""" -from typing import Literal, Optional +from typing import Optional from pydantic import AnyHttpUrl, Field from dstack._internal.proxy.lib.const import DEFAULT_SERVICE_READ_TIMEOUT from dstack._internal.proxy.lib.models import ImmutableModel +from dstack._internal.proxy.lib.services.usage import MeteringProfile class ModelEntrypoint(ImmutableModel): @@ -23,6 +24,4 @@ class ACMESettings(ImmutableModel): class GlobalProxyConfig(ImmutableModel): acme_settings: ACMESettings = ACMESettings() - usage_metering_profiles: dict[str, Literal["vllm-0.19.1-prompt-details"]] = Field( - default_factory=dict - ) + usage_metering_profiles: dict[str, MeteringProfile] = Field(default_factory=dict) diff --git a/src/dstack/_internal/proxy/gateway/schemas/config.py b/src/dstack/_internal/proxy/gateway/schemas/config.py index da21202ef3..721e8e87ce 100644 --- a/src/dstack/_internal/proxy/gateway/schemas/config.py +++ b/src/dstack/_internal/proxy/gateway/schemas/config.py @@ -1,10 +1,12 @@ -from typing import Literal, Optional +from typing import Optional from pydantic import AnyHttpUrl, BaseModel +from dstack._internal.proxy.lib.services.usage import MeteringProfile + class ConfigRequest(BaseModel): acme_server: Optional[AnyHttpUrl] = None acme_eab_kid: Optional[str] = None acme_eab_hmac_key: Optional[str] = None - usage_metering_profiles: Optional[dict[str, Literal["vllm-0.19.1-prompt-details"]]] = None + usage_metering_profiles: Optional[dict[str, MeteringProfile]] = None diff --git a/src/dstack/_internal/proxy/gateway/services/metering.py b/src/dstack/_internal/proxy/gateway/services/metering.py index 8dc62afdf7..5955e844a4 100644 --- a/src/dstack/_internal/proxy/gateway/services/metering.py +++ b/src/dstack/_internal/proxy/gateway/services/metering.py @@ -20,7 +20,7 @@ UsageKey, ) from dstack._internal.proxy.lib.services.usage import ( - VLLM_PROFILE, + METERING_PROFILES, UsageAttempt, UsageObserver, normalize_usage, @@ -94,7 +94,7 @@ async def configure_profiles( async with self._lock: self._reconfiguring = True try: - if any(profile != VLLM_PROFILE for profile in profiles.values()): + if any(profile not in METERING_PROFILES for profile in profiles.values()): raise ProxyError("Unsupported metering profile") changed = { key @@ -128,7 +128,7 @@ def start_attempt(self, key: UsageKey, profile: str) -> UsageAttempt: or self._storage_error or self._clock_error or self.profile_for(key.service_id) != profile - or profile != VLLM_PROFILE + or profile not in METERING_PROFILES ): raise ProxyError("Usage metering is unavailable", 503) keys = set(self._entries) | {attempt.key for attempt in self._attempts} | {key} @@ -275,7 +275,7 @@ async def _finish(self, attempt: "MeteringAttempt") -> None: logger.error("Usage finalization paused after a backward clock jump") raise previous = self._entries.get(attempt.key) or UsageEntry(**attempt.key.model_dump()) - usage = attempt.usage or TokenUsage() + usage = attempt.usage or attempt.partial_usage or TokenUsage() values = { name: getattr(previous, name) + getattr(usage, name) for name in TokenUsage.model_fields @@ -361,6 +361,7 @@ def __init__(self, collector: MeteringCollector, key: UsageKey, profile: str): self.upstream_done = False self.finished = False self.usage: TokenUsage | None = None + self.partial_usage: TokenUsage | None = None self._finish_task: asyncio.Task[None] | None = None def observe_usage(self, usage: Any) -> None: @@ -368,6 +369,9 @@ def observe_usage(self, usage: Any) -> None: if confirmed is not None: self.usage = confirmed + def observe_partial_usage(self, usage: TokenUsage | None) -> None: + self.partial_usage = usage + def mark_dispatched(self) -> None: self.dispatched = True diff --git a/src/dstack/_internal/proxy/lib/routers/model_proxy.py b/src/dstack/_internal/proxy/lib/routers/model_proxy.py index f53f65fcbb..93e843f10d 100644 --- a/src/dstack/_internal/proxy/lib/routers/model_proxy.py +++ b/src/dstack/_internal/proxy/lib/routers/model_proxy.py @@ -88,7 +88,12 @@ async def post_chat_completions( return await client.generate(body) return await client.generate(body, attempt=attempt) source = client.stream(body) if attempt is None else client.stream(body, attempt=attempt) - adaptor = StreamingAdaptor(source, attempt=attempt) + include_usage = ( + attempt is not None + and body.stream_options is not None + and body.stream_options.include_usage + ) + adaptor = StreamingAdaptor(source, attempt=attempt, include_usage=include_usage) stream = await adaptor.get_stream() response = MeteredStreamingResponse( stream, @@ -112,10 +117,15 @@ class StreamingAdaptor: """ def __init__( - self, stream: AsyncIterator[ChatCompletionsChunk], attempt: UsageAttempt | None = None + self, + stream: AsyncIterator[ChatCompletionsChunk], + attempt: UsageAttempt | None = None, + *, + include_usage: bool = False, ) -> None: self._stream = stream self._attempt = attempt + self._include_usage = include_usage self._close_task: asyncio.Task | None = None async def get_stream(self) -> AsyncIterator[bytes]: @@ -153,9 +163,9 @@ async def _close(self) -> None: if self._attempt is not None: await self._attempt.finish() - @staticmethod - def _encode_chunk(chunk: ChatCompletionsChunk) -> bytes: - encoded = chunk.model_dump_json(exclude={"usage"} if chunk.usage is None else None) + def _encode_chunk(self, chunk: ChatCompletionsChunk) -> bytes: + exclude = {"usage"} if chunk.usage is None and not self._include_usage else None + encoded = chunk.model_dump_json(exclude=exclude) return f"data:{encoded}\n\n".encode() diff --git a/src/dstack/_internal/proxy/lib/services/model_proxy/clients/openai.py b/src/dstack/_internal/proxy/lib/services/model_proxy/clients/openai.py index 796fac8eb4..d492455ca4 100644 --- a/src/dstack/_internal/proxy/lib/services/model_proxy/clients/openai.py +++ b/src/dstack/_internal/proxy/lib/services/model_proxy/clients/openai.py @@ -5,7 +5,7 @@ from fastapi import status from pydantic import ValidationError -from dstack._internal.core.models.common import validate_json_extra_ignore +from dstack._internal.core.models.common import validate_extra_ignore, validate_json_extra_ignore from dstack._internal.proxy.lib.errors import ProxyError from dstack._internal.proxy.lib.schemas.model_proxy import ( ChatCompletionsChunk, @@ -14,6 +14,7 @@ ) from dstack._internal.proxy.lib.services.model_proxy.clients.base import ChatCompletionsClient from dstack._internal.proxy.lib.services.model_proxy.sse import SSEDecoder +from dstack._internal.proxy.lib.services.model_proxy.stream_usage import StreamUsage from dstack._internal.proxy.lib.services.usage import MAX_JSON_RESPONSE_BYTES, UsageAttempt @@ -38,10 +39,11 @@ async def generate( data = json.loads(raw) if not isinstance(data, dict): raise ValueError("Expected a response object") + response = validate_json_extra_ignore(ChatCompletionsResponse, raw) if attempt is not None: attempt.observe_usage(data.get("usage")) attempt.mark_upstream_done() - return validate_json_extra_ignore(ChatCompletionsResponse, raw) + return response except httpx.RequestError as exc: raise ProxyError( f"Error requesting model: {exc!r}", status.HTTP_502_BAD_GATEWAY @@ -54,11 +56,12 @@ async def stream( ) -> AsyncIterator[ChatCompletionsChunk]: payload = request.model_dump(exclude_unset=True) include_usage = request.stream_options is not None and request.stream_options.include_usage - if attempt is not None: - payload["stream_options"] = { - **(payload.get("stream_options") or {}), - "include_usage": True, - } + stream_usage = StreamUsage(attempt, request.n) if attempt is not None else None + if stream_usage is not None: + stream_options = {**(payload.get("stream_options") or {}), "include_usage": True} + if stream_usage.request_progress: + stream_options["continuous_usage_stats"] = True + payload["stream_options"] = stream_options try: if attempt is not None: attempt.mark_dispatched() @@ -72,24 +75,25 @@ async def stream( if data.strip() == "[DONE]": if attempt is not None: attempt.mark_upstream_done() + if stream_usage is not None: + final = stream_usage.complete() + if include_usage and final is not None: + yield final return + if stream_usage is None: + yield self._parse_chunk_data(data) + continue raw = json.loads(data) if not isinstance(raw, dict): raise ValueError("Expected an SSE response object") - # The supported vLLM profile emits final usage in a usage-only event. - # Cumulative values on content/finish chunks are not final observations. - if ( - attempt is not None - and raw.get("choices") == [] - and raw.get("usage") is not None - ): - attempt.observe_usage(raw["usage"]) - chunk = self._parse_chunk_data(data) - if attempt is not None and not include_usage and chunk.usage is not None: - if not chunk.choices: - continue - chunk = chunk.model_copy(update={"usage": None}) - yield chunk + # Usage validation must not discard a choice containing text. + usage = raw.pop("usage", None) + chunk = validate_extra_ignore(ChatCompletionsChunk, raw) + final = stream_usage.observe(chunk, usage) + if chunk.choices or usage is None: + yield chunk + elif include_usage and final is not None: + yield final decoder.finish() raise ProxyError( "Model stream ended before upstream [DONE]", status.HTTP_502_BAD_GATEWAY diff --git a/src/dstack/_internal/proxy/lib/services/model_proxy/stream_usage.py b/src/dstack/_internal/proxy/lib/services/model_proxy/stream_usage.py new file mode 100644 index 0000000000..1de7e4836f --- /dev/null +++ b/src/dstack/_internal/proxy/lib/services/model_proxy/stream_usage.py @@ -0,0 +1,156 @@ +from typing import Any + +from dstack._internal.core.models.common import validate_extra_ignore +from dstack._internal.proxy.lib.schemas.model_proxy import ( + ChatCompletionsChunk, + ChatCompletionsUsage, + PromptTokensDetails, +) +from dstack._internal.proxy.lib.schemas.usage import TokenUsage +from dstack._internal.proxy.lib.services.usage import VLLM_PROFILE, UsageAttempt, normalize_usage +from dstack._internal.utils.logging import get_logger + +logger = get_logger(__name__) +_FINISH_REASONS = {"stop", "length", "tool_calls", "content_filter", "function_call"} + + +class StreamUsage: + def __init__(self, attempt: UsageAttempt, n: int): + self._attempt = attempt + self._n = n + self._per_choice = attempt.profile == "vllm-0.19.1-per-choice" + self.request_progress = attempt.profile != VLLM_PROFILE + self._final = False + self._finished_choices: set[int] = set() + self._finish_usage: dict[int, TokenUsage] = {} + self._outputs: dict[int, int] = {} + self._completion = 0 + self._prompt = 0 + self._confirmed_input: tuple[int, int] | None = None + self._invalid_progress = False + self._terminal: ChatCompletionsChunk | None = None + + def observe(self, chunk: ChatCompletionsChunk, raw_usage: Any) -> ChatCompletionsChunk | None: + if self._final: + return None + usage = normalize_usage(raw_usage, self._attempt.profile) + if not chunk.choices: + if usage is None: + return None + self._confirm(usage, raw_usage) + public_usage = validate_extra_ignore(ChatCompletionsUsage, raw_usage) + return chunk.model_copy(update={"usage": public_usage}) + if self.request_progress and not self._invalid_progress: + self._observe_progress(chunk, usage, raw_usage) + return None + + def complete(self) -> ChatCompletionsChunk | None: + if self._final or self._terminal is None or self._invalid_progress: + return None + self._attempt.observe_usage(self._terminal.usage) + return self._terminal + + def _confirm(self, usage: TokenUsage, raw_usage: Any) -> None: + cached = ( + self._confirmed_input[1] + if self._confirmed_input is not None and self._confirmed_input[0] == self._prompt + else None + ) + if self._outputs and ( + usage.completion_tokens != self._completion + or usage.prompt_tokens != self._prompt + or (cached is not None and usage.cached_prompt_tokens != cached) + ): + logger.debug( + "Upstream final usage differs from streaming progress: " + "prompt %d -> %d, cached %s -> %d, completion %d -> %d", + self._prompt, + usage.prompt_tokens, + cached, + usage.cached_prompt_tokens, + self._completion, + usage.completion_tokens, + ) + self._attempt.observe_usage(raw_usage) + self._final = True + + def _observe_progress( + self, chunk: ChatCompletionsChunk, usage: TokenUsage | None, raw_usage: Any + ) -> None: + indices = {choice.index for choice in chunk.choices} + finishes = { + choice.index for choice in chunk.choices if choice.finish_reason in _FINISH_REASONS + } + if ( + any(index < 0 or index >= self._n for index in indices) + or len(indices) != len(chunk.choices) + or (indices - finishes) & self._finished_choices + or (self._per_choice and usage is not None and len(indices) != 1) + ): + self._invalid_progress = True + return + + new_finishes = finishes - self._finished_choices + self._finished_choices.update(finishes) + if usage is None: + return + if indices == finishes and finishes <= self._finish_usage.keys(): + # A delayed replay may precede the latest request-wide count. + if any(self._finish_usage[index] != usage for index in finishes): + self._invalid_progress = True + return + + key = next(iter(indices)) if self._per_choice else 0 + previous = self._outputs.get(key, 0) + has_cache = raw_usage.get("prompt_tokens_details") is not None + if ( + usage.completion_tokens < previous + or usage.prompt_tokens < self._prompt + or ( + has_cache + and self._confirmed_input is not None + and usage.cached_prompt_tokens < self._confirmed_input[1] + ) + or self._terminal is not None + ): + self._invalid_progress = True + return + + self._outputs[key] = usage.completion_tokens + self._completion += usage.completion_tokens - previous + self._prompt = usage.prompt_tokens + if has_cache: + self._confirmed_input = (usage.prompt_tokens, usage.cached_prompt_tokens) + + # Cache details can first arrive in the final event. Until observed, + # charge only output on an incomplete request. + prompt, cached = self._confirmed_input or (0, 0) + self._attempt.observe_partial_usage( + TokenUsage( + prompt_tokens=prompt, + cached_prompt_tokens=cached, + completion_tokens=self._completion, + total_tokens=prompt + self._completion, + ) + ) + + for index in finishes: + self._finish_usage.setdefault(index, usage) + if self._per_choice: + complete = bool(finishes) and len(self._finish_usage) == self._n + else: + complete = bool(new_finishes) and len(self._finished_choices) == self._n + # A snapshot must accompany the last finish. For per-choice counts, + # every choice also needs its own terminal snapshot. + if complete: + public_usage = ChatCompletionsUsage( + prompt_tokens=self._prompt, + completion_tokens=self._completion, + total_tokens=self._prompt + self._completion, + prompt_tokens_details=( + PromptTokensDetails(cached_tokens=cached) + if self._confirmed_input is not None and prompt == self._prompt + else None + ), + ) + self._terminal = chunk.model_copy(update={"choices": [], "usage": public_usage}) diff --git a/src/dstack/_internal/proxy/lib/services/usage.py b/src/dstack/_internal/proxy/lib/services/usage.py index 6d7dc2d7db..f84c8e0a7e 100644 --- a/src/dstack/_internal/proxy/lib/services/usage.py +++ b/src/dstack/_internal/proxy/lib/services/usage.py @@ -1,19 +1,26 @@ """Usage observation is optional for shared proxy consumers.""" from collections.abc import Mapping -from typing import Any +from typing import Any, Literal, get_args from pydantic import BaseModel, ValidationError from dstack._internal.proxy.lib.schemas.usage import TokenUsage, UsageKey VLLM_PROFILE = "vllm-0.19.1-prompt-details" +MeteringProfile = Literal[ + "vllm-0.19.1-prompt-details", + "vllm-0.19.1-per-choice", + "dynamo-1.6.2-rust", + "dynamo-1.6.2-vllm", +] +METERING_PROFILES = frozenset(get_args(MeteringProfile)) MAX_JSON_RESPONSE_BYTES = 16 * 1024 * 1024 MAX_SSE_EVENT_BYTES = 1024 * 1024 def normalize_usage(usage: Any, profile: str) -> TokenUsage | None: - if profile != VLLM_PROFILE: + if profile not in METERING_PROFILES: return None if isinstance(usage, BaseModel): usage = usage.model_dump() @@ -42,9 +49,14 @@ def normalize_usage(usage: Any, profile: str) -> TokenUsage | None: class UsageAttempt: """No-op default; Gateway supplies a concrete per-attempt observer.""" + profile: str = VLLM_PROFILE + def observe_usage(self, usage: Any) -> None: pass + def observe_partial_usage(self, usage: TokenUsage | None) -> None: + pass + def mark_dispatched(self) -> None: pass diff --git a/src/tests/_internal/proxy/gateway/metering/backend.py b/src/tests/_internal/proxy/gateway/metering/backend.py index 51c1d97f4c..565a059bcc 100644 --- a/src/tests/_internal/proxy/gateway/metering/backend.py +++ b/src/tests/_internal/proxy/gateway/metering/backend.py @@ -83,6 +83,12 @@ async def events(): } ], } + if (body.get("stream_options") or {}).get("continuous_usage_stats"): + content["usage"] = { + "prompt_tokens": expected["prompt_tokens"], + "completion_tokens": 1, + "total_tokens": expected["prompt_tokens"] + 1, + } raw = ("data: " + json.dumps(content, ensure_ascii=False) + "\r\n\r\n").encode() for offset in range(0, len(raw), 3): yield raw[offset : offset + 3] diff --git a/src/tests/_internal/proxy/gateway/metering/test_scenarios.py b/src/tests/_internal/proxy/gateway/metering/test_scenarios.py index 63e8b3195f..799221a89d 100644 --- a/src/tests/_internal/proxy/gateway/metering/test_scenarios.py +++ b/src/tests/_internal/proxy/gateway/metering/test_scenarios.py @@ -215,8 +215,12 @@ async def test_json_and_streaming_usage(harness, stream, case): @pytest.mark.asyncio -@pytest.mark.parametrize("after_usage", [False, True]) -async def test_stream_disconnect(harness, after_usage): +@pytest.mark.parametrize( + "after_usage,progressive", + [(False, False), (True, False), (False, True)], + ids=["before-usage", "after-final", "after-progress"], +) +async def test_stream_disconnect(harness, after_usage, progressive): h = harness await h.backend_control(hold=["disconnect"], after_usage=after_usage) body = { @@ -227,6 +231,11 @@ async def test_stream_disconnect(harness, after_usage): "stream_options": {"include_usage": True}, } async with httpx.AsyncClient(base_url=h.gateway_url, timeout=10) as client: + if progressive: + config = await client.post( + "/api/config", json={"usage_metering_profiles": {PAIR[1]: "dynamo-1.6.2-rust"}} + ) + config.raise_for_status() async with client.stream( "POST", "/api/models/p/chat/completions", @@ -243,9 +252,31 @@ async def test_stream_disconnect(harness, after_usage): if (not after_usage and saw_content) or (after_usage and event.get("usage")): break assert saw_content # Content arrives while final usage / DONE is still held. + if progressive: + assert event["usage"] is None + await close_minute(h) + assert (await h.batches())["batches"] == [] await h.wait_finalized("disconnect") await close_minute(h) - assert totals((await h.batches())["batches"][0]) == expected("A" if after_usage else "cut") + wanted = expected("A" if after_usage else "cut") + if progressive: + wanted.update(completion_tokens=1, total_tokens=1) + (batch,) = (await h.batches())["batches"] + assert totals(batch) == wanted + if progressive: + receiver = MockReceiver( + h.gateway_url, + h.state / "partial.sqlite", + gateway_replica_id="replica-a", + gateway_id="gateway-a", + ) + try: + receipt = await receiver.collect_once() + assert receipt.acked_ids == [batch["batch_id"]] + assert receiver.totals() == {PAIR: wanted} + assert (await h.batches())["batches"] == [] + finally: + await receiver.close() await h.backend_control(release=["disconnect"]) diff --git a/src/tests/_internal/proxy/lib/services/test_openai_usage.py b/src/tests/_internal/proxy/lib/services/test_openai_usage.py index 80533f407a..06e2157ef5 100644 --- a/src/tests/_internal/proxy/lib/services/test_openai_usage.py +++ b/src/tests/_internal/proxy/lib/services/test_openai_usage.py @@ -1,10 +1,13 @@ import json +from contextlib import asynccontextmanager import httpx import pytest from fastapi import FastAPI +from dstack._internal.proxy.gateway.deps import get_metering from dstack._internal.proxy.gateway.repo.repo import GatewayProxyRepo +from dstack._internal.proxy.gateway.routers.usage import router as usage_router from dstack._internal.proxy.gateway.services.metering import MeteringCollector from dstack._internal.proxy.gateway.services.metering_store import MeteringStore from dstack._internal.proxy.lib.auth import BaseProxyAuthProvider @@ -89,7 +92,7 @@ def backend(request): assert requests[0]["stream_options"]["include_usage"] is True assert request.stream_options is not None assert request.stream_options.include_usage is include_usage - assert len(chunks) == (3 if include_usage else 1) + assert len(chunks) == (2 if include_usage else 1) if include_usage: usage = chunks[-1].usage assert usage is not None and usage.prompt_tokens_details is not None @@ -161,6 +164,275 @@ def get_usage_observer(self): return self.collector +@asynccontextmanager +async def metered_endpoint(tmp_path, monkeypatch, profile, backend_handler): + clock = FakeClock() + collector = MeteringCollector(MeteringStore(tmp_path / "usage.json"), clock=clock) + await collector.configure_profiles({"s": profile}) + try: + repo = GatewayProxyRepo() + await repo.set_service(make_service("p", "run", run_id="s")) + await repo.set_model( + ChatModel( + project_name="p", + name="test", + run_name="run", + created_at=clock.utc_now(), + format_spec=OpenAIChatModelFormat(format="openai", prefix="/v1"), + ) + ) + app = FastAPI() + app.state.proxy_dependency_injector = MeteredInjector(repo, collector) + app.include_router(model_router, prefix="/models") + app.dependency_overrides[get_metering] = lambda: collector + app.include_router(usage_router, prefix="/api/usage") + async with ( + httpx.AsyncClient( + transport=httpx.MockTransport(backend_handler), base_url="http://backend" + ) as backend, + httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), + base_url="http://gateway", + headers={"Authorization": "Bearer token"}, + ) as client, + ): + + async def connection(*args, **kwargs): + return backend + + monkeypatch.setattr( + "dstack._internal.proxy.lib.routers.model_proxy.get_service_replica_client", + connection, + ) + yield client, collector, clock + finally: + await collector.close() + + +def sse_choice(index, *, content="", finish_reason=None, usage=None): + return { + "id": "answer", + "model": "test", + "created": 17, + "choices": [ + {"index": index, "delta": {"content": content}, "finish_reason": finish_reason} + ], + **({"usage": usage} if usage is not None else {}), + } + + +def token_counts(prompt, completion, *, cached=None): + return { + "prompt_tokens": prompt, + "completion_tokens": completion, + "total_tokens": prompt + completion, + **({"prompt_tokens_details": {"cached_tokens": cached}} if cached is not None else {}), + } + + +def sse_reply(events, *, done=True): + wire = "".join("data: " + json.dumps(event) + "\n\n" for event in events) + return httpx.Response( + 200, stream=FragmentedStream((wire + ("data: [DONE]\n\n" if done else "")).encode()) + ) + + +async def public_chat(client, **options): + return await client.post( + "/models/p/chat/completions", json={"model": "test", "messages": [], **options} + ) + + +def public_events(response): + assert response.status_code == 200 + data = [line[5:].strip() for line in response.text.splitlines() if line.startswith("data:")] + assert data[-1] == "[DONE]" + return [json.loads(event) for event in data[:-1]] + + +async def close_minute(collector, clock): + clock.advance() + await collector.rotate_if_due() + (batch,) = (await collector.get_batches()).batches + (entry,) = batch.entries + return entry + + +@pytest.mark.asyncio +@pytest.mark.parametrize("include", [False, True]) +async def test_dynamo_inline_usage_preserves_last_text_and_settles_once( + tmp_path, monkeypatch, include +): + # Live client-option matrix, Dynamo 1.6.2 with the Python vLLM processor. + measured = token_counts(57, 32, cached=48) + requests = [] + + def backend(request): + requests.append(json.loads(request.content)) + return sse_reply( + [ + sse_choice(0, content="Okay", usage=token_counts(57, 1)), + sse_choice(0, content=" the", finish_reason="length", usage=measured), + ] + ) + + async with metered_endpoint(tmp_path, monkeypatch, "dynamo-1.6.2-vllm", backend) as ( + client, + collector, + clock, + ): + response = await public_chat( + client, stream=True, **({"stream_options": {"include_usage": True}} if include else {}) + ) + events = public_events(response) + assert [e["choices"][0]["delta"]["content"] for e in events if e["choices"]] == [ + "Okay", + " the", + ] + assert events[1]["choices"][0]["finish_reason"] == "length" + if include: + assert [e["usage"] for e in events] == [None, None, measured] + assert events[2]["choices"] == [] + assert events[2]["id"] == "answer" and events[2]["created"] == 17 + else: + assert len(events) == 2 and all("usage" not in e for e in events) + (request,) = requests + assert request["stream_options"] == {"include_usage": True, "continuous_usage_stats": True} + entry = await close_minute(collector, clock) + assert (entry.prompt_tokens, entry.cached_prompt_tokens, entry.completion_tokens) == ( + 57, + 48, + 32, + ) + assert (entry.total_tokens, entry.unknown_usage_attempts) == (89, 0) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("per_choice", [False, True]) +@pytest.mark.parametrize("done", [False, True]) +async def test_stream_counts_interleaved_choices_using_profile( + tmp_path, monkeypatch, per_choice, done +): + first_finish = sse_choice( + 1, finish_reason="stop", usage=token_counts(10, 5 if per_choice else 6) + ) + events = [sse_choice(0, content="Hi", usage=token_counts(10, 1)), first_finish, first_finish] + if done: + events.extend( + [ + sse_choice(0, content=" last", usage=token_counts(10, 2 if per_choice else 7)), + first_finish, + sse_choice( + 0, finish_reason="stop", usage=token_counts(10, 3 if per_choice else 8) + ), + ] + ) + profile = "vllm-0.19.1-per-choice" if per_choice else "dynamo-1.6.2-vllm" + async with metered_endpoint( + tmp_path, monkeypatch, profile, lambda request: sse_reply(events, done=done) + ) as (client, collector, clock): + reply = await public_chat(client, stream=True, n=2, stream_options={"include_usage": True}) + if done: + assert public_events(reply)[-1]["usage"] == { + **token_counts(10, 8), + "prompt_tokens_details": None, + } + else: + assert reply.status_code == 200 + assert "data: [DONE]" not in reply.text and '"choices":[]' not in reply.text + entry = await close_minute(collector, clock) + assert (entry.prompt_tokens, entry.completion_tokens, entry.total_tokens) == ( + (10, 8, 18) if done else (0, 6, 6) + ) + assert entry.unknown_usage_attempts == int(not done) + + +@pytest.mark.asyncio +async def test_replayed_earlier_finish_cannot_supply_missing_final_total(tmp_path, monkeypatch): + first_finish = sse_choice(0, finish_reason="stop", usage=token_counts(10, 6)) + events = [ + first_finish, + sse_choice(1, content="last", finish_reason="stop"), + first_finish, + ] + async with metered_endpoint( + tmp_path, monkeypatch, "dynamo-1.6.2-vllm", lambda request: sse_reply(events) + ) as (client, collector, clock): + reply = await public_chat(client, stream=True, n=2, stream_options={"include_usage": True}) + assert all(event["choices"] and event["usage"] is None for event in public_events(reply)) + entry = await close_minute(collector, clock) + assert (entry.total_tokens, entry.unknown_usage_attempts) == (6, 1) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("regression", ["prompt", "cache", "conflicting-finish"]) +async def test_inconsistent_progress_does_not_displace_last_verified_prefix( + tmp_path, monkeypatch, regression +): + if regression == "conflicting-finish": + events = [ + sse_choice(0, finish_reason="stop", usage=token_counts(10, 2, cached=5)), + sse_choice(0, finish_reason="stop", usage=token_counts(10, 3, cached=5)), + ] + else: + events = [ + sse_choice(0, usage=token_counts(10, 2, cached=5)), + sse_choice(0, usage=token_counts(8 if regression == "prompt" else 10, 3, cached=4)), + sse_choice(0, finish_reason="stop", usage=token_counts(10, 4, cached=5)), + ] + async with metered_endpoint( + tmp_path, monkeypatch, "vllm-0.19.1-per-choice", lambda request: sse_reply(events) + ) as (client, collector, clock): + reply = await public_chat(client, stream=True, stream_options={"include_usage": True}) + assert all(event["choices"] and event["usage"] is None for event in public_events(reply)) + entry = await close_minute(collector, clock) + assert ( + entry.prompt_tokens, + entry.cached_prompt_tokens, + entry.completion_tokens, + entry.unknown_usage_attempts, + ) == (10, 5, 2, 1) + + +@pytest.mark.asyncio +async def test_final_usage_supersedes_progress_and_public_extension_is_rejected( + tmp_path, monkeypatch +): + requests = [] + final = token_counts(10, 28, cached=2) + + def backend(request): + requests.append(json.loads(request.content)) + return sse_reply( + [ + sse_choice(0, content="Hi", usage=token_counts(10, 30)), + sse_choice(0, finish_reason="stop", usage=token_counts(10, 30)), + {**sse_choice(0), "choices": [], "usage": final}, + ] + ) + + async with metered_endpoint(tmp_path, monkeypatch, "dynamo-1.6.2-rust", backend) as ( + client, + collector, + clock, + ): + denied = await public_chat( + client, + stream=True, + stream_options={"include_usage": True, "continuous_usage_stats": True}, + ) + assert denied.status_code == 422 + assert requests == [] + reply = await public_chat(client, stream=True, stream_options={"include_usage": True}) + assert [e["usage"] for e in public_events(reply)] == [None, None, final] + entry = await close_minute(collector, clock) + assert (entry.total_tokens, entry.cached_prompt_tokens, entry.unknown_usage_attempts) == ( + 38, + 2, + 0, + ) + + @pytest.mark.asyncio @pytest.mark.parametrize( "stream,metadata", From 7d5551cfad9b3c8eb89216012dacfdc69ebebc8b Mon Sep 17 00:00:00 2001 From: Igx22 Date: Mon, 23 Nov 2026 15:16:41 +0700 Subject: [PATCH 7/7] Run Gateway usage migration after upstream migrations --- .../2026/11_16_1201_9a2e8f1f3c37_add_gateway_usage_batches.py | 4 ++-- src/tests/_internal/server/test_usage_migration.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/dstack/_internal/server/migrations/versions/2026/11_16_1201_9a2e8f1f3c37_add_gateway_usage_batches.py b/src/dstack/_internal/server/migrations/versions/2026/11_16_1201_9a2e8f1f3c37_add_gateway_usage_batches.py index a54c49492d..2ca87e4dbc 100644 --- a/src/dstack/_internal/server/migrations/versions/2026/11_16_1201_9a2e8f1f3c37_add_gateway_usage_batches.py +++ b/src/dstack/_internal/server/migrations/versions/2026/11_16_1201_9a2e8f1f3c37_add_gateway_usage_batches.py @@ -1,7 +1,7 @@ """Add Gateway usage batches with one row per user and run Revision ID: 9a2e8f1f3c37 -Revises: 6b5610ff36c1 +Revises: 2d2692d5b3c2 Create Date: 2026-11-16 12:01:47.939623+00:00 """ @@ -14,7 +14,7 @@ # revision identifiers, used by Alembic. revision = "9a2e8f1f3c37" -down_revision = "6b5610ff36c1" +down_revision = "2d2692d5b3c2" branch_labels = None depends_on = None diff --git a/src/tests/_internal/server/test_usage_migration.py b/src/tests/_internal/server/test_usage_migration.py index 1a7a1cc881..cc0dfff682 100644 --- a/src/tests/_internal/server/test_usage_migration.py +++ b/src/tests/_internal/server/test_usage_migration.py @@ -30,7 +30,7 @@ def run_case(conn, populated): for table, id_ in zip(parents, (user, run, gateway, replica)): conn.execute(table.insert().values(id=id_)) migration = importlib.import_module(MIGRATION) - assert (migration.revision, migration.down_revision) == ("9a2e8f1f3c37", "6b5610ff36c1") + assert (migration.revision, migration.down_revision) == ("9a2e8f1f3c37", "2d2692d5b3c2") with Operations.context(MigrationContext.configure(conn)): migration.upgrade() inspector = sa.inspect(conn)