Skip to content

[Bug]: Run processing can postpone service readiness and registration after probes pass #4551

In progress

Description

@peterschmidt85

Steps to reproduce

The delay depends on worker scheduling. This controlled reproduction uses a running, single-replica service with a stored successful HTTP probe (ready_after: 1):

  1. Save the test below as src/tests/_internal/server/test_service_readiness_repro.py in an affected checkout.

  2. Run it from the repository root:

    uv run pytest src/tests/_internal/server/test_service_readiness_repro.py --runpostgres -q -s

    This runs SQLite and PostgreSQL; PostgreSQL requires Docker. Omit --runpostgres to run SQLite only. The test asserts the affected behaviour, so a passing result reproduces the bug.

  3. The test lets RunFetcher/RunWorker run before JobRunningFetcher at 0, 11, 22 and 33 seconds. At 44 seconds it lets the job fetcher run first, then processes the job.

Reproduction using the real fetchers, workers, locks and database

Runner polling and image lookup are stubbed, and the passing probe result is inserted directly. The test exercises readiness and registration flags; it does not start a workload or gateway.

import asyncio
from datetime import datetime, timedelta, timezone
from unittest.mock import Mock

import pytest
import time_machine

from dstack._internal.core.models.configurations import ProbeConfig, ServiceConfiguration
from dstack._internal.core.models.instances import InstanceStatus
from dstack._internal.core.models.runs import JobStatus, RunStatus
from dstack._internal.server.background.pipeline_tasks import jobs_running, runs
from dstack._internal.server.testing.common import (
    create_instance,
    create_job,
    create_probe,
    create_project,
    create_repo,
    create_run,
    create_user,
    get_job_provisioning_data,
    get_job_runtime_data,
    get_run_spec,
)


@pytest.mark.asyncio
@pytest.mark.parametrize("test_db", ["sqlite", "postgres"], indirect=True)
@pytest.mark.usefixtures("image_config_mock")
async def test_run_processing_postpones_registration(test_db, session, monkeypatch):
    # Stub runner polling; use the real fetchers, workers, locks and database.
    monkeypatch.setattr(
        jobs_running,
        "_process_running",
        Mock(return_value=jobs_running._ProcessRunningResult()),
    )
    t0 = datetime(2026, 11, 27, 11, 33, 54, tzinfo=timezone.utc)
    with time_machine.travel(t0, tick=False) as clock:
        project = await create_project(session=session)
        user = await create_user(session=session)
        repo = await create_repo(session=session, project_id=project.id)
        instance = await create_instance(
            session=session,
            project=project,
            status=InstanceStatus.BUSY,
        )
        run = await create_run(
            session=session,
            project=project,
            repo=repo,
            user=user,
            status=RunStatus.RUNNING,
            last_processed_at=t0 - timedelta(seconds=20),
            run_spec=get_run_spec(
                repo_id=repo.name,
                configuration=ServiceConfiguration(
                    port=8080,
                    commands=["serve"],
                    probes=[ProbeConfig(type="http", url="/healthz", ready_after=1)],
                ),
            ),
        )
        job = await create_job(
            session=session,
            run=run,
            status=JobStatus.RUNNING,
            instance=instance,
            instance_assigned=True,
            job_provisioning_data=get_job_provisioning_data(),
            job_runtime_data=get_job_runtime_data(),
            last_processed_at=t0 - timedelta(seconds=20),
        )
        probe = await create_probe(session=session, job=job, success_streak=1)
        await session.commit()
        options = dict(
            queue_desired_minsize=1,
            min_processing_interval=timedelta(seconds=5),
            lock_timeout=timedelta(seconds=30),
            heartbeater=Mock(),
        )
        run_fetcher = runs.RunFetcher(queue=asyncio.Queue(), **options)
        job_fetcher = jobs_running.JobRunningFetcher(queue=asyncio.Queue(), **options)
        run_worker = runs.RunWorker(queue=Mock(), heartbeater=Mock(), pipeline_hinter=Mock())
        job_worker = jobs_running.JobRunningWorker(
            queue=Mock(),
            heartbeater=Mock(),
            pipeline_hinter=Mock(),
        )

        for seconds in (0, 11, 22, 33):
            clock.move_to(t0 + timedelta(seconds=seconds))
            run_items = await run_fetcher.fetch(1)
            assert len(run_items) == 1
            await run_worker.process(run_items[0])
            job_items = await job_fetcher.fetch(1)
            await session.refresh(job)
            await session.refresh(probe)
            assert probe.success_streak == 1
            print(
                f"{seconds=}: fetched_jobs={len(job_items)}, ready={job.ready}, registered={job.registered}"
            )
            assert job_items == []
            assert not job.ready and not job.registered

        # Let the job worker run before run processing on the next eligible tick.
        clock.move_to(t0 + timedelta(seconds=44))
        job_items = await job_fetcher.fetch(1)
        assert len(job_items) == 1
        await job_worker.process(job_items[0])
        await session.refresh(job)
        assert job.ready and job.registered
        print(f"seconds=44: ready={job.ready}, registered={job.registered}")

Actual behaviour

Both SQLite and PostgreSQL produce:

seconds=0: fetched_jobs=0, ready=False, registered=False
seconds=11: fetched_jobs=0, ready=False, registered=False
seconds=22: fetched_jobs=0, ready=False, registered=False
seconds=33: fetched_jobs=0, ready=False, registered=False
seconds=44: ready=True, registered=True

The probe remains successful throughout. Each run-worker pass refreshes the job's last_processed_at without processing the job, so the job fetcher keeps excluding it. Changing the worker order allows readiness and registration to proceed.

Observed on Sky on 27 November 2026 with a code-server service on port 8080 and an HTTP /healthz probe (ready_after: 1, interval: 15s):

Time (UTC) Observation
11:33:23 code-server starts listening on 0.0.0.0:8080.
11:34:15 Public / and /healthz return nginx 503. Earlier API snapshots already showed probe success_streak increasing from 1 to 2.
11:34:27 Service replica ready to receive requests.
11:34:30 Service replica registered.

After registration, /healthz returned 200 and / redirected to the code-server login page. No restart or configuration change was made. The first successful probe's exact completion time was not recorded; the live observations do not establish how much of the total startup delay this scheduling defect caused.

Expected behaviour

Releasing an unchanged job's lock does not reset its processing timestamp. Once probes pass, the next eligible job-worker pass can update readiness and, for replicas exposed through the proxy, request registration without run processing repeatedly postponing it.

dstack version

0.22.9, deployed commit d79b42604. The controlled reproduction above was confirmed with SQLite and PostgreSQL against the same affected pipeline code.

Additional information

_build_active_job_update_rows() calls set_processed_update_map_fields() even when a job is only being unlocked. JobRunningFetcher excludes running jobs processed within the last 10 seconds by default. Repeated run processing can therefore keep moving the job's eligibility time forward.

Probes update their results independently, but the job worker updates ready and sets registered for replicas exposed through the proxy. Until a replica is registered with the gateway, nginx returns 503 when there are no replicas. A passing probe alone therefore does not mean the public endpoint is serving requests.

The timestamp reset is in the shared active-run apply path: it does not depend on the application, backend, replica count, or replica group. The same scheduling defect affects services with generated model probes, custom probes, or no probes, and also task and dev-environment jobs. Its visible effect depends on the configuration:

  • For a gateway service with no registered replicas, requests return 503. If existing replicas remain available, the symptom can instead be delayed additional capacity or rolling deployment. The in-server proxy also selects replicas by registered; nginx 503 is specific to the gateway path.
  • With a router, only router replicas are registered with the proxy. Worker replicas become ready without registered; that readiness is used by rolling deployment. SMG worker synchronization has its own readiness checks and deliberately does not wait for JobModel.ready.
  • Probe configuration still determines when readiness is satisfied. Generated model probes, explicit probes and an empty probe list retain their existing semantics; this fix addresses scheduling, not application health or gateway connectivity.

Suggested fix: preserve JobModel.last_processed_at when active-run processing only unlocks the job; continue updating it when run processing changes the job. Draft PR #4550 contains this change.

Activity

  1. added
    bug
    on Nov 27, 2026
  2. peterschmidt85 commented on Nov 27, 2026

    @peterschmidt85
    ContributorAuthor

    Implementation notes

    Some additional processing is unavoidable: the existing bug skips necessary work. That does not mean additional scaling latency is unavoidable.

    Restoring job processing can expose the following existing constraints as jobs, runs and fleets grow per server, and services and replicas grow per gateway:

    • Job-worker saturation and shared resource contention. The job pipeline has 20 workers per server process. Readiness processing follows runner status/log retrieval. Slow calls and additional polling can delay readiness and failure detection, and compete with run, fleet and instance processing for CPU and database capacity.
    • Delayed autoscaling and rolling replacement through run/job lock contention. Run processing needs all related active job locks. A conflict resets the run's processing timestamp, normally adding another ten-second eligibility interval for active runs. Larger runs and slower job processing increase this risk. Retained run ownership prevents fresh ordinary job polls from continually overtaking the run; an alternative must preserve that protection without introducing repeated immediate retries.
    • Gateway registration backlog. Replica registration is serialized, with a changed Nginx configuration/reload and state save per successful addition. Readiness bursts can therefore delay usable capacity. Additional gateway replicas repeat registration work rather than partition it; replacement availability requires confirmation from all running gateway replicas.
    • Request latency during gateway state writes. Gateway state is saved under a writer lock. Model-proxy requests need the corresponding reader lock for model lookup, so registration bursts can also delay those requests.

    These are constraints to account for, not confirmed production regressions from the timestamp correction. A fix should preserve probe and router semantics and multi-server coordination. A readiness-only workaround must not leave the underlying job-processing starvation unresolved.

    PR #4550 is closed; this issue remains open for an implementation that accounts for these constraints.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions