Skip to content

Reuse fleet offer queries in preset previews - #4542

Open
pinggaozhanshi wants to merge 2 commits into
dstackai:masterfrom
pinggaozhanshi:issue_4531_preset_offer_preview
Open

pinggaozhanshi wants to merge 2 commits into
dstackai:masterfrom
pinggaozhanshi:issue_4531_preset_offer_preview

Conversation

@pinggaozhanshi

Copy link
Copy Markdown

Fixes #4531

When a preset leaves fleets unset, the preview requests offers across all active fleets. The planner could query the same backend project repeatedly with identical constraints, then deduplicate each full result on the server event loop.

Reuse results per job plan for fleets with the same backend project, effective profile, requirements, and cluster placement constraints. Deduplicate and merge the offers in a worker thread. The response still contains the exact total and maximum price before the displayed list is truncated, including for dstack offer --fleet.

Reproduction

Use a project with several active fleets that share the same backend and constraints. Run dstack apply -f preset.dstack.yml with a valid preset configuration that omits fleets. Inspect the offer preview before confirming creation. On the base revision, the planner runs a backend offer query for each fleet while the preview shows at most ten offers. The test and benchmark below reproduce the query count without provisioning cloud instances.

Validation

  • Added regressions for query reuse, separate regional and imported-fleet queries, fresh queries on successive requests, and exact offer totals. A second test checks that deduplication runs off the event loop and preserves distinct offers.
  • Both regressions fail on the base revision at the intended assertions. The related server planning, offer collection, and CLI tests pass on the patch (55 tests, including SQLite and PostgreSQL 16.15). The local PostgreSQL run used the same database fixtures with a locally started server.
  • A local HTTP check used the CLI preview helper, the dstack API client, and a simulated backend. Two previews across three equivalent fleets made six backend queries on the base and two on the patch. Each preview returned the same ten cheapest offers, an exact count of 14, and a maximum price of $14.00 per hour.
  • The pre-commit checks passed for the changed files. Pyright reported zero diagnostics for both files.
  • The existing Test Build workflow runs lint, Pyright, and the Python suite for PRs targeting master.

Run the regressions on Linux or macOS with the standard test runner. The PostgreSQL variant uses Docker.

uv sync --all-extras
uv run pytest src/tests/_internal/server/services/runs/test_plan.py -k "reuses_identical_queries or deduplicates_offers_off_the_event_loop" --runpostgres

Local benchmark

The benchmark ran the preset preview code against a simulated backend on Windows with Python 3.13.2. Both cases used 40 fleets and a total of 2,000 distinct offers. Each revision was measured three times, with d79b426 as the base and 6c85b19 as the patch. The final column is the median of each trial’s maximum delay for a 10 ms event-loop heartbeat.

Distinct queries Backend queries, base / patch Median preview time, base / patch Heartbeat delay, base / patch
1 40 / 1 4.16 / 0.15 s 312.7 / 23.7 ms
4 40 / 4 1.08 / 0.14 s 75.8 / 21.2 ms

Both revisions returned the same first 10 offers, total of 2,000, and maximum price of $20.00 per hour in every trial.

Reproduce the benchmark

Save the script as benchmark_preset_offers.py. In each checkout, run uv sync --all-extras followed by uv run python /path/to/benchmark_preset_offers.py. The script uses the real preview and planner with a synthetic catalog and checks the output in each trial.

"""Measure the preset preview with a synthetic catalog and no cloud credentials."""

import asyncio
import json
import statistics
import uuid
from contextlib import redirect_stdout, suppress
from io import StringIO
from time import perf_counter
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock, patch

from dstack._internal.cli.services.presets.create import plan_preset
from dstack._internal.core.models.backends.base import BackendType
from dstack._internal.core.models.configurations import PresetConfiguration
from dstack._internal.core.models.fleets import FleetStatus
from dstack._internal.core.models.profiles import Profile
from dstack._internal.server.services.runs import plan
from dstack._internal.server.testing.common import (
    get_fleet_spec,
    get_instance_offer_with_availability,
    get_run_spec,
    mock_lease,
)

FLEET_COUNT = 40
OFFER_COUNT = 2000
HEARTBEAT_INTERVAL = 0.01


async def measure(group_count: int) -> dict[str, int | float]:
    loop = asyncio.get_running_loop()
    project = SimpleNamespace(id=uuid.uuid4(), name="main")
    backend = Mock(TYPE=BackendType.AWS)
    regions = [f"test-region-{index}" for index in range(group_count)]
    fleet_specs = [
        get_fleet_spec(profile=Profile(regions=[region])).model_dump_json() for region in regions
    ]
    fleets = [
        SimpleNamespace(
            name=f"fleet-{index}",
            status=FleetStatus.ACTIVE,
            project_name=project.name,
            project_id=project.id,
            project=project,
            spec=fleet_specs[index % group_count],
            instances=[],
        )
        for index in range(FLEET_COUNT)
    ]
    catalog = [
        get_instance_offer_with_availability(
            price=index / 100,
            region=regions[(index - 1) % group_count],
            instance_type=f"gpu-{index}",
            gpu_count=1,
        )
        for index in range(1, OFFER_COUNT + 1)
    ]
    offers_by_region = {
        region: [(backend, offer) for offer in catalog if offer.region == region]
        for region in regions
    }
    captured = []
    heartbeat_delays = []

    async def fetch(profile: Profile, **kwargs):
        await asyncio.sleep(0)
        [region] = profile.regions or []
        return offers_by_region[region]

    def get_plan(project_name, run_spec, **kwargs):
        request = get_run_spec(repo_id="mock", configuration=run_spec.configuration, profile=None)
        job_plans = asyncio.run_coroutine_threadsafe(
            plan.get_job_plans(
                session=Mock(),
                project=project,
                run_spec=request,
                full_offers=False,
                unallocated_resources=False,
                **kwargs,
            ),
            loop,
        ).result(timeout=60)
        captured.append(job_plans[0])
        return SimpleNamespace(project_name=project_name, user="local", job_plans=job_plans)

    async def heartbeat():
        while True:
            start = loop.time()
            await asyncio.sleep(HEARTBEAT_INTERVAL)
            heartbeat_delays.append(max(0, loop.time() - start - HEARTBEAT_INTERVAL))

    api = SimpleNamespace(
        project=project.name,
        client=SimpleNamespace(
            fleets=SimpleNamespace(list=Mock(return_value=fleets)),
            runs=SimpleNamespace(get_plan=get_plan),
        ),
    )
    configuration = PresetConfiguration(repo="Qwen/Qwen2.5-0.5B-Instruct")
    fetch_mock = AsyncMock(side_effect=fetch)
    with (
        patch.object(plan, "get_project_secrets_mapping", AsyncMock(return_value={})),
        patch.object(plan, "get_job_configured_volumes", AsyncMock(return_value=[])),
        patch.object(plan, "_select_candidate_fleet_models", AsyncMock(return_value=fleets)),
        patch.object(plan, "get_offers_by_requirements", fetch_mock),
        patch.object(plan.backends_cache, "lease_project_backends", mock_lease([backend])),
        redirect_stdout(StringIO()),
    ):
        probe = asyncio.create_task(heartbeat())
        await asyncio.sleep(0)
        start = perf_counter()
        try:
            names = await asyncio.to_thread(plan_preset, api=api, configuration=configuration)
        finally:
            seconds = perf_counter() - start
            probe.cancel()
            with suppress(asyncio.CancelledError):
                await probe

    assert len(names) == FLEET_COUNT
    [job_plan] = captured
    assert job_plan.offers == catalog[:10]
    assert job_plan.total_offers == OFFER_COUNT
    assert job_plan.max_price == 20.0
    return {
        "queries": fetch_mock.await_count,
        "seconds": round(seconds, 4),
        "max_heartbeat_delay_ms": round(max(heartbeat_delays, default=0) * 1000, 1),
        "displayed": len(job_plan.offers),
        "total": job_plan.total_offers,
        "max_price": job_plan.max_price,
    }


async def main() -> None:
    for group_count in (1, 4):
        trials = [await measure(group_count) for _ in range(3)]
        print(
            json.dumps(
                {
                    "fleets": FLEET_COUNT,
                    "query_groups": group_count,
                    "trials": trials,
                    "median_seconds": statistics.median(trial["seconds"] for trial in trials),
                    "median_max_heartbeat_delay_ms": statistics.median(
                        trial["max_heartbeat_delay_ms"] for trial in trials
                    ),
                }
            )
        )


if __name__ == "__main__":
    asyncio.run(main())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Preset creation's offer preview fetches uncapped offers for every fleet and blocks the event loop

1 participant