Skip to content

fix(gateway): reconcile k8s service discovery with periodic full LIST - #32322

Closed
Juhyun-Kim-Memphis wants to merge 4 commits into
sgl-project:mainfrom
vessl-ai:inf-sd-relist-reconcile
Closed

Juhyun-Kim-Memphis wants to merge 4 commits into
sgl-project:mainfrom
vessl-ai:inf-sd-relist-reconcile

Conversation

@Juhyun-Kim-Memphis

@Juhyun-Kim-Memphis Juhyun-Kim-Memphis commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

Kubernetes service discovery cannot converge to the true pod set when the watch stream is unreliable, which is the normal operating condition on some managed providers: long-lived watches are dropped every few minutes and sometimes go silently stale, yielding neither events nor errors.

Three coupled defects in service_discovery.rs:

  1. Delete events are structurally lost. The watch consumes watcher(...).applied_objects(), which yields only Apply/InitApply and discards Delete. A removal is caught only opportunistically, via an Apply carrying a deletion_timestamp during graceful termination. A pod that disappears while the watch is down, or is force-deleted, stays a registered worker forever — nothing reconciles against a fresh LIST, and the registry health checker only marks workers unhealthy, never deregisters.
  2. A silently stale watch disables the restart path. When the stream neither yields nor errors (observed: 20+ minutes, zero watcher-error lines), try_for_each never returns, so the outer loop — the only place a fresh watcher() re-LIST could happen — never runs.
  3. The error-restart path stalls 60–360 s per reconnect, sleeping retry_delay plus an unconditional check_interval every iteration.

Change

reconcile_from_list(): a paged full LIST that feeds every selector-matching, non-terminating pod through the existing handle_pod_event, and removes every tracked pod no longer present via handle_pod_deletion. A pod with a deletion_timestamp counts as absent, mirroring the watch path watch-independently, so a draining pod stops receiving traffic even when the watch is dead. Any page failing aborts the pass before the removal phase, so a partial view can never drive removals.

Driven from a periodic timer (--service-discovery-resync-secs, default 30) and at the top of each watch (re)start; the redundant unconditional sleep is dropped so reconnects are prompt.

The tracked set is keyed by pod.metadata.uid, not by name. Under Api::all — the default, and what gateway-cluster-scoped.yaml ships — names are unique only per namespace, so a dead ns-a/engine-0 stays tracked while ns-b/engine-0 lives; and a pod replaced under one name is tracked alongside its predecessor instead of evicting it. The UID is stable across the status/readiness flips that make full-struct equality unusable, so it also lets handle_pod_deletion resolve by identity rather than exact-struct HashSet::remove (the fragility noted in #26842).

Two cases handled explicitly:

  • A departed pod whose worker URL is claimed by a live healthy pod in the same LIST is a same-URL replacement (hostNetwork gives a pod its node's IP), so it is forgotten rather than deregistered.
  • Membership in tracked_pods records that an AddWorker was submitted, not that it succeeded, and the add path short-circuits on tracked pods forever. A listed healthy pod that is tracked but absent from the registry is therefore forgotten so it is submitted again — via find_workers_by_url, since dp-aware workers register as <url>@<rank>, and gated on a per-URL in-flight check because submit() does not dedup.

Relationship to #30270 and #26842

Both diagnose the same root causes and fix the event handling; this is complementary, adding the watch-independent periodic LIST that neither covers. When the watch is dead or silently stale — our dominant failure mode — better event handling has no events to handle.

Split out of this PR, independently reviewable: #38523 (worker registry re-registration) and #38524 (add/remove handoff race).

Verification

cargo test --lib 410/410 (service_discovery 33 → 48); cargo +nightly fmt --check clean; cargo clippy --all-targets adds no new warnings. Every new test was confirmed to fail against the code it replaces.

Live on a 2-replica colocated cell behind 2 router replicas (managed k8s with frequent watch drops), steady 0.6 rps, isl 512 / osl 1200, full 2-pod rolling update with two cold starts, no external remediation:

client failures
stock router 26 (12× 503, 4× 500, 10× connection errors)
this patch, resync 10 s 0 across 2,156 requests

Captured router logs show the reconcile doing what the watch could not: a dead pod removed on the periodic tick while that replica's watch was silently stale, and replacement pods registered on the tick boundary on both replicas (the stock router left a Ready pod unregistered for 12+ minutes in the same environment).

Checklist


CI States

Latest PR Test (Base): ✅ Run #37558371667
Latest PR Test (Extra): ❌ Run #37558371484
Latest PR Test (AMD ROCm 10): ➖ No AMD PR run found for this commit.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

@Juhyun-Kim-Memphis

Copy link
Copy Markdown
Contributor Author

This PR is ready for review. The pr-gate checks are failing only because the run-ci label is missing (external contributors cannot add labels) — could a maintainer add run-ci / run-ci-extra to trigger the full CI? All gateway-relevant checks that did run (lint, build-wheel, benchmark compilation) are green. Thanks!

@ShangmingCai ShangmingCai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two notes on reconcile_from_list -- both about cases where the resync doesn't converge, left inline at the relevant lines. The overall direction (watch-independent periodic LIST) looks right to me, and the failure handling in particular (bail before the removal pass on any page error, snapshot tracked_before ahead of the LIST, MissedTickBehavior::Delay) is careful work.

Comment on lines +881 to +889
/// Selection is by pod NAME (the stable key), never by full `PodInfo`
/// equality: a tracked pod whose status/readiness has flipped since it was
/// added must still be treated as present. The returned values are the
/// stored `PodInfo` structs so the caller's `HashSet::remove` matches
/// exactly.
fn stale_tracked_pods(tracked: &HashSet<PodInfo>, present: &HashSet<String>) -> Vec<PodInfo> {
tracked
.iter()
.filter(|pod_info| !present.contains(&pod_info.name))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

present is keyed on the bare pod name, but with no --service-discovery-namespace this is Api::all, where pod names are only unique per namespace. So ns-a/engine-0 being deleted while ns-b/engine-0 is alive leaves "engine-0" in present, and the tracked entry for the dead pod is never returned by this filter. Nothing else deregisters it -- the registry health checker (worker_registry.rs:646) only calls check_health_async(), it never removes -- so that worker stays registered for the life of the process. gateway-cluster-scoped.yaml ships this configuration; test_cross_namespace.py uses distinct pod names (cross-ns-worker-a/-b), so it doesn't surface.

Same shape without namespaces involved: a pod replaced under the same name (StatefulSet / LeaderWorkerSet, or force-delete + recreate) with a new IP. The name is present, so the new PodInfo is added alongside the old one and the old one is never removed. It converges only if a tick happens to land in the window where the name is absent-or-terminating.

Worth flagging that test_pd_type_change.py is already written against exactly this scenario, and its docstring says it "covers the UID-based eviction path in handle_pod_event (same name, different UID) and the reconciliation diff (stale uid-A, missing uid-B)". But grep uid src/service_discovery.rs is empty on this branch and on main -- there is no uid anywhere. That test passes because step 3 waits for worker_count == 0 before recreating the pod, which manufactures the empty window the name key needs.

The doc comment above is right that full-PodInfo equality is too strict. Name is just too loose in the other direction. pod.metadata.uid has both properties you want: stable across the status/readiness flips this comment is protecting against, and different for a recreated pod. Carrying a uid on PodInfo and building present from uids would also let handle_pod_deletion resolve the tracked entry by identity instead of exact-struct HashSet::remove, fixing the watch path's removal at the same time.

The new fake_pod_api scaffolding makes the regression test cheap: track {name: p, ip: A}, have the LIST return {name: p, ip: B}, assert A is gone.

@Juhyun-Kim-Memphis Juhyun-Kim-Memphis Aug 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed and fixed — PodInfo now carries the UID and the tracked set is keyed by it, which also lets handle_pod_deletion resolve by identity. Your test_pd_type_change.py pointer caught a same-URL hostNetwork replacement that a plain UID key would have deregistered; that case is now treated as a handover.

Comment on lines +832 to +841
// handle_pod_event dedups via tracked_pods and gates on
// is_healthy(), so re-adds are cheap no-ops.
handle_pod_event(
&pod_info,
Arc::clone(&tracked_pods),
Arc::clone(&app_context),
port,
config.pd_mode,
)
.await;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This dedup assumption holds only if membership in tracked_pods implies the worker actually reached the registry, and there's a path where it doesn't.

handle_pod_event inserts into tracked_pods and rolls back only when submit() itself fails (the tracker.remove(pod_info) at ~L613, i.e. channel closed/full). If the job fails afterwards -- wait_for_completion timing out (worker_startup_timeout_secs defaults to 1800s, config/types.rs:514), a failing activation step, a workflow-start error -- record_job_completion writes JobStatus::failed (job_queue.rs:878) and nothing else happens. tracked_pods is private to this file, so no other code can untrack it.

From then on this call is a permanent no-op: the pod is in tracked_pods, so tracker.contains(pod_info) short-circuits at L520 and the reconcile never retries. The pod stays absent from the registry while the reconcile believes it is registered -- the same unrecoverable state this PR closes on the delete side, still open on the add side. (Pre-existing, but this pass is the natural place to repair it, and the "authoritative resync" framing invites the assumption that it already does.)

Since the pass is already paying for a full LIST, it seems worth reconciling against the registry rather than only the shadow set: treat "tracked but absent from worker_registry" as missing and resubmit. Use find_workers_by_url(registry, url, dp_aware) rather than get_by_url -- in dp-aware mode workers are registered as <url>@<rank>, so an exact-URL lookup never matches (same reason the new handoff guard reaches for it in job_queue.rs).

@Juhyun-Kim-Memphis Juhyun-Kim-Memphis Aug 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed and fixed — a tracked pod with no registered worker is now resubmitted, via find_workers_by_url as you said, gated on a per-URL in-flight check since submit() does not dedup. One limit: registration is step 5 of 8, so a failure after it would not be caught — happy to widen the check to "registered and healthy" if you'd prefer.

@Juhyun-Kim-Memphis

Juhyun-Kim-Memphis commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor Author

@ShangmingCai both notes addressed, plus one more the second note led into. Three commits:

  • key discovery's tracked pods by UID, not name — PodInfo carries the UID and the tracked set is keyed by it, so handle_pod_deletion resolves by identity instead of exact-struct removal. One case your test_pd_type_change.py pointer exposed: a hostNetwork replacement inherits the old pod's address, so the removal pass would deregister the worker the add pass had just registered. That is now treated as a handover.
  • reconcile the SD add path against the worker registry — a tracked pod with no registered worker is resubmitted, via find_workers_by_url for the dp-aware <url>@<rank> reason you gave, gated on a new per-URL in-flight check since submit() does not dedup.
  • replace, don't accumulate, when a worker URL is re-registered — register() appended to the secondary indexes, so a re-registered URL left the old worker routable in model_index, and its reused id in the old type bucket made get_by_type(Prefill) return the decode worker. The handover above is incomplete without it. Reachable via POST /workers alone, so it is an independent bug — trivially split out if you'd rather it went separately.

cargo test --lib 415/415, fmt and clippy clean. Every new test was confirmed to fail against the code it replaces. Unit level only — the live rolling-update numbers in the description predate these commits.

pr-gate is still only the missing run-ci label.

@petrpan26

Copy link
Copy Markdown

Thank you for Attention on this !

@Juhyun-Kim-Memphis

Copy link
Copy Markdown
Contributor Author

Cross-reference: I opened #37249, which removes one of the concrete causes of the state forget_lost_registration in this PR exists to recover.

sgl-model-gateway pins wfaas = "=1.0.0", and in wfaas 1.0.0/1.0.1 a step that fails with FailureAction::ContinueNextStep is recorded in the tracker as skipped but signals StepResult::Failure to the scheduler. The scheduler enqueues a step's dependents only on Success | Skip, so nothing downstream ever runs and the workflow ends in the deadlock branch as Failed. In create_local_worker_workflow() that is discover_metadata, with discover_dp_info → create_worker → register_workers hanging off it — so one failing optional metadata fetch means the worker is never registered, while handle_pod_event has already inserted the pod into tracked_pods and only rolls that back when submit() itself fails.

That is exactly the class this PR's doc comment describes:

Membership in tracked_pods records that an AddWorker job was SUBMITTED, not that it succeeded […] A job that fails after that […] only records a failed JobStatus, and nothing untracks the pod.

The causes named there (detect_connection_mode exhausting worker_startup_timeout_secs, a failing DP discovery, a workflow that never starts) are all comparatively rare. The wfaas one is not: a transient hiccup on a single optional HTTP call to a pod that has just started is enough to trigger it, so in practice it is a frequent producer of tracked-but-unregistered pods rather than an exotic one.

The two changes are complementary and independent, and can land in either order:

If it would be useful to reviewers, I am happy to extend forget_lost_registration's doc comment here to name the wfaas case alongside the others once #37249's disposition is clear.

@ShangmingCai

Copy link
Copy Markdown
Collaborator

/tag-and-rerun-ci

@Juhyun-Kim-Memphis

Copy link
Copy Markdown
Contributor Author

The four red test jobs are main's, not this PR's

PR Test (SMG) fails the same four jobs on main, in the same two places.

this PR (33580768883) main (33585286354)
Install SGLang dependencies chat-completions, chat-completions-4gpu, e2e e2e, benchmarks, chat-completions-4gpu
Run E2E tests benchmarks chat-completions

The install-step failure is the editable install compiling sglang-radix-tree and failing to link libtorch:

rust-lld: error: unable to find library -ltorch_cuda
rust-lld: error: unable to find library -ltorch_python
rust-lld: error: unable to find library -ltorch_cpu
rust-lld: error: unable to find library -ltorch
rust-lld: error: unable to find library -lc10
error: could not compile `sglang-radix-tree` (lib)

require_prebuilt_rust_exts returns in 0 s — no prebuilt module for the new crate — so uv pip install -e python[...] builds it from source, and the linker search path is uv's isolated build environment (/root/.cache/uv/builds-v0/.tmp*/lib/python3.10/site-packages/torch/lib), where those libraries are not found. The first main run showing this is 33414097466 at 9cf157c (#32710, 2026-08-31), and every main run since has failed the same way.

This PR is confined to sgl-model-gateway and does not reach that path. The other four red checks are the call-gate / pr-gate and pr-test-*-extra-finish aggregators.

The reconcile path has now been needed in production

@ShangmingCai — your 08-24 note, that membership in tracked_pods implies registry membership only if nothing fails in between, is the hole we hit for real on 2026-09-01. During a rolling restart /model_info and /server_info timed out on pods that had just started, create_worker fell back to UNKNOWN_MODEL_ID, and under IGW those workers are healthy, listed, and unroutable for the life of the router process — a registered worker is never revisited by discovery. Part of the fleet was silently out of rotation until we deleted the workers by hand. Filed as #37554.

#37555 is the fix for that fallback, and it depends on this PR: refusing to register is only safe if something re-submits the pod afterwards, which is forget_lost_registration here and does not exist on main. It stays in draft until this merges.

In our fork, which carries this PR, a canary ran both arms against stub workers with metadata hanging from boot. With today's code the workers stay model_id: "unknown" even after they begin answering; with the refusal they register under their real model name within 18 s — one --service-discovery-resync-secs 10 tick plus the AddWorker that follows it.

The wfaas half of the same story, #37249, is already merged.

Kubernetes service discovery cannot converge to the true pod set when the watch
stream is unreliable, which is the normal operating condition on some managed
providers: long-lived watches are dropped every few minutes and sometimes go
silently stale, yielding neither events nor errors.

Three coupled defects:

- **Delete events are structurally lost.** The watch consumes
  `watcher(...).applied_objects()`, which yields only `Apply`/`InitApply` and
  discards `Delete`. A pod removal is caught only opportunistically, via an
  `Apply` carrying a `deletion_timestamp` during graceful termination. A pod
  that disappears while the watch is down, or is force-deleted, stays a
  registered worker forever — nothing reconciles against a fresh LIST, and the
  registry health checker only marks workers unhealthy, never deregisters.
- **A silently stale watch disables the restart path.** When the stream neither
  yields nor errors, `try_for_each` never returns, so the outer loop — the only
  place a fresh `watcher()` re-LIST could happen — never runs.
- **The error-restart path stalls 60-360 s per reconnect**, sleeping
  `retry_delay` plus an unconditional `check_interval` on every iteration.

Add `reconcile_from_list()`: a paged full LIST that feeds every selector-
matching, non-terminating pod through the existing `handle_pod_event`, and
removes every tracked pod no longer present via `handle_pod_deletion`. A pod
with a `deletion_timestamp` counts as absent, mirroring the watch path's
handling watch-independently, so a draining pod stops receiving traffic even
when the watch is dead. Any page failing aborts the pass before the removal
phase, so a partial view can never drive removals.

Drive it from a periodic timer (`--service-discovery-resync-secs`, default 30)
and at the top of each watch (re)start, and drop the redundant unconditional
sleep so reconnects are prompt.

The tracked set is keyed by `pod.metadata.uid` rather than by name. Under
`Api::all` — the default, and what `gateway-cluster-scoped.yaml` ships — names
are unique only per namespace, so a dead `ns-a/engine-0` stays tracked while
`ns-b/engine-0` lives; and a pod replaced under one name is tracked alongside
its predecessor instead of evicting it. The UID is stable across the status and
readiness flips that make full-struct equality unusable, and differs for a
recreated pod, so it also lets `handle_pod_deletion` resolve by identity
instead of an exact-struct `HashSet::remove`.

Two cases the reconcile handles explicitly:

- A departed pod whose worker URL is claimed by a live healthy pod in the same
  LIST is a same-URL replacement, not a worker to deregister: with hostNetwork
  a pod's IP is its node's, so a rollout brings up a new pod at the old
  address. It is forgotten rather than deregistered.
- Membership in `tracked_pods` records that an AddWorker was submitted, not
  that it succeeded. A job failing after submission leaves the pod tracked with
  nothing registered, and the add path then short-circuits on it forever. A
  listed healthy pod that is tracked but absent from the registry is therefore
  forgotten so it is submitted again — looked up with `find_workers_by_url`,
  since dp-aware workers register as `<url>@<rank>`, and gated on a new
  per-URL `JobQueue::has_add_worker_in_flight_for` because `submit()` does not
  dedup by URL.

Verified live on a 2-replica colocated cell behind 2 router replicas under
steady load: a rolling update that produced 26 client-visible failures on the
stock router completed with 0 across 2,156 requests with this patch, with no
external remediation.
@Juhyun-Kim-Memphis

Copy link
Copy Markdown
Contributor Author

Split this into three to make it reviewable, and rebased onto current main. This PR is now one production file (service_discovery.rs) plus its tests, squashed to a single commit.

The two parts that reached shared subsystems are out, each independently reachable without service discovery at all:

Keeping those here meant one 20-commit PR touching three subsystems, where two of them changed behaviour for users not on k8s discovery.

Checks: the four red PR Test (SMG) jobs fail identically on main (every run since #32710) — sglang-radix-tree fails to link libtorch, a path this PR does not touch. The rest are the extra gate reporting Missing required label 'run-ci-extra'.

@Juhyun-Kim-Memphis

Copy link
Copy Markdown
Contributor Author

@ShangmingCai Gentle ping when you have a chance — would appreciate another look. Thanks!

@Juhyun-Kim-Memphis

Copy link
Copy Markdown
Contributor Author

Closing this for now. Our production router has since moved to the standalone SMG (smg-project/smg), so we no longer run sgl-model-gateway and this fix isn't urgent for us. The gap it targets is that discovery never does a full LIST, so a missed watch event can leave a worker unregistered. If that gap turns out to need a code fix, we'll open a new issue or PR against SMG, shaped for that codebase. The split-out pieces (#38523, #38524) and the follow-up #37555 are closed along with this one. Thanks @ShangmingCai and @petrpan26 for the reviews.

@ShangmingCai

Copy link
Copy Markdown
Collaborator

Closing this for now. Our production router has since moved to the standalone SMG (smg-project/smg), so we no longer run sgl-model-gateway and this fix isn't urgent for us. The gap it targets is that discovery never does a full LIST, so a missed watch event can leave a worker unregistered. If that gap turns out to need a code fix, we'll open a new issue or PR against SMG, shaped for that codebase. The split-out pieces (#38523, #38524) and the follow-up #37555 are closed along with this one. Thanks @ShangmingCai and @petrpan26 for the reviews.

@Juhyun-Kim-Memphis, sorry for the late reply and for the CI stalling the merge process for this PR. I haven't been checking my GitHub messages box much lately because there are too many messages. Just noticed a "closed" notification on another PR, which reminded me that this PR hasn't been merged yet. You could ping me on Slack next time. Also, we are developing the new sgl-router, which will have many designs that integrate better with SGLang for agentic workloads; feel free to try that as well. The review and merging process will be fast for the new router since we have built a faster and better CI pipeline for it.

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

Labels

model-gateway run-ci CI: run the baseline test suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants