Repository navigation
fix(gateway): reconcile k8s service discovery with periodic full LIST - #32322
Juhyun-Kim-Memphis wants to merge 4 commits into
Conversation
|
Caution The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased. |
|
This PR is ready for review. The |
ShangmingCai
left a comment
There was a problem hiding this comment.
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.
| /// 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)) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| // 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; |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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.
|
@ShangmingCai both notes addressed, plus one more the second note led into. Three commits:
|
|
Thank you for Attention on this ! |
|
Cross-reference: I opened #37249, which removes one of the concrete causes of the state
That is exactly the class this PR's doc comment describes:
The causes named there ( 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 |
|
/tag-and-rerun-ci |
The four red test jobs are
|
| 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.
f1af058 to
a3d51c0
Compare
|
Split this into three to make it reviewable, and rebased onto current 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 |
|
@ShangmingCai Gentle ping when you have a chance — would appreciate another look. Thanks! |
|
Closing this for now. Our production router has since moved to the standalone SMG (smg-project/smg), so we no longer run |
@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. |
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:watcher(...).applied_objects(), which yields onlyApply/InitApplyand discardsDelete. A removal is caught only opportunistically, via anApplycarrying adeletion_timestampduring 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.try_for_eachnever returns, so the outer loop — the only place a freshwatcher()re-LIST could happen — never runs.retry_delayplus an unconditionalcheck_intervalevery iteration.Change
reconcile_from_list(): a paged full LIST that feeds every selector-matching, non-terminating pod through the existinghandle_pod_event, and removes every tracked pod no longer present viahandle_pod_deletion. A pod with adeletion_timestampcounts 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. UnderApi::all— the default, and whatgateway-cluster-scoped.yamlships — names are unique only per namespace, so a deadns-a/engine-0stays tracked whilens-b/engine-0lives; 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 letshandle_pod_deletionresolve by identity rather than exact-structHashSet::remove(the fragility noted in #26842).Two cases handled explicitly:
tracked_podsrecords 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 — viafind_workers_by_url, since dp-aware workers register as<url>@<rank>, and gated on a per-URL in-flight check becausesubmit()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 --lib410/410 (service_discovery33 → 48);cargo +nightly fmt --checkclean;cargo clippy --all-targetsadds 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:
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.