Skip to content

enhance: resolve global cluster topology via DNS SRV records - #3753

Merged
sre-ci-robot merged 8 commits into
milvus-io:masterfrom
huanghaoyuanhhy:srv-topology-resolution
Nov 24, 2026
Merged

sre-ci-robot merged 8 commits into
milvus-io:masterfrom
huanghaoyuanhhy:srv-topology-resolution

Conversation

@huanghaoyuanhhy

@huanghaoyuanhhy huanghaoyuanhhy commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Why

Global cluster connections previously fetched topology by hitting the global endpoint directly. This PR switches the SDK to discover ha-manager seed servers through the _grpc._tcp.<host> SRV record set, verify target domain authorization before sending credentials, probe seeds concurrently, and adopt the highest topology version with strict no-rollback semantics across every refresh and recovery path.

What changed

  • SRV discovery & domain verification:
    • Resolve _grpc._tcp.<endpoint hostname> to ha-manager seeds, ordered by priority ascending and weight descending (filtering RFC 2782 . targets). Endpoints without SRV records (NXDOMAIN, NoAnswer, or .) raise immediately instead of falling back to the legacy direct-endpoint path.
    • Verify resolved SRV target hostnames belong to the global endpoint's authorized delegated domain (global-cluster.<base> when present, with a parent-domain fallback) before sending bearer tokens over HTTPS. Untrusted targets are dropped, and if all targets fail verification SrvTargetValidationError is raised without retry.
  • Seed selection & concurrent probing:
    • Initial fetch (no cached version): select DEFAULT_PROBE_COUNT = 2 seeds spanning priorities (weighted by SRV weight, or uniformly when all weights are zero) and return the first healthy answer immediately while a daemon watcher drains remaining probes and applies strictly higher versions. If initial channel readiness fails on a stale primary after the watcher advances the cached primary, retry once against the updated primary and clean up TopologyRefresher if setup still fails.
    • Cached refresh (TopologyRefresher & on_unavailable): poll every seed concurrently, bound the extra foreground wait after the first healthy answer to PROBE_GRACE_PERIOD = 1.0s so blackholed seeds cannot stall RPC recovery, and hand still-pending probes to the background watcher.
  • Version monotonicity & recovery:
    • Funnel all writes to the connection strategy's shared topology (initial connect, watcher, TopologyRefresher, and on_unavailable) through a lock-guarded compare-and-set (_accept_topology), removing the refresher's private snapshot so no interleaving can regress the version.
    • Normalize primary addresses (host:port with scheme-aware default ports and preserved IPv6 brackets) across handler creation, get_recovery_address, and on_unavailable (primary_address != handler.server_address), and re-check recovery_gen on sync handle_error so concurrent callers still retry after another thread recovers the connection.
  • Retry & fast-fail semantics:
    • Retry transient DNS errors and unreachable/non-200 seeds with jittered exponential backoff (MAX_RETRIES = 3), keeping the last seed error on final failure.
    • Fail fast without retry on deterministic errors: missing SRV records, SRV domain validation failure, HTTP 401/403 (SeedAuthError, aborting stalled waits when no seed has succeeded yet), and server API code != 0.
  • Pass the bare endpoint hostname verbatim via ?endpoint= (server derives the global cluster id; no client-side gcid parsing).
  • Add dnspython>=2.0.0 dependency for SRV resolution.

Tests

  • Unit tests covering endpoint hostname extraction, SRV resolution & domain validation (SaaS, BYOC, multi-label suffixes, label-boundary bypasses), priority-spanning weighted selection, concurrent probing (first-answer fast path, bounded grace period, late background delivery), initial-connect readiness retry & cleanup, IPv6 normalization, concurrent recovery retry preservation, and fast-fail vs. retry semantics.
  • 277 passed

Deployment note

HA manager SRV records must be in place before this SDK version ships — endpoints without SRV records will raise instead of falling back to the legacy path.

@mergify

mergify Bot commented Aug 10, 2026 •

Copy link
Copy Markdown

This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again.

@codecov

codecov Bot commented Aug 10, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.36964% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 94.89%. Comparing base (eeb76a1) to head (54efcc6).
⚠️ Report is 7 commits behind head on master.

Files with missing lines Patch % Lines
pymilvus/client/global_topology.py 96.01% 8 Missing ⚠️
pymilvus/client/connection_manager.py 97.05% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3753      +/-   ##
==========================================
+ Coverage   94.73%   94.89%   +0.16%     
==========================================
  Files          81       81              
  Lines       17102    17784     +682     
==========================================
+ Hits        16201    16877     +676     
- Misses        901      907       +6     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@huanghaoyuanhhy
huanghaoyuanhhy force-pushed the srv-topology-resolution branch from bff88a1 to cee8d91 Compare August 10, 2026 08:25
@mergify mergify Bot added the ci-passed label Aug 10, 2026
@mergify mergify Bot added ci-passed and removed ci-passed labels Sep 14, 2026
@mergify mergify Bot added ci-passed and removed ci-passed labels Sep 14, 2026

@bigsheeper bigsheeper left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code review of the SRV topology resolution change. 10 findings, ranked most severe first as inline comments (1 = most severe). Findings 1-5 are correctness issues; 6-10 are diagnostics and cleanup.

Comment thread pymilvus/client/connection_manager.py Resolved
Comment thread pymilvus/client/connection_manager.py Resolved
Comment thread pymilvus/client/global_topology.py Resolved
Comment thread pymilvus/client/global_topology.py Resolved
Comment thread tests/unit/test_global_topology.py Resolved
Comment thread pymilvus/client/global_topology.py Resolved
Comment thread pymilvus/client/global_topology.py Resolved
Comment thread pymilvus/client/global_topology.py Resolved
Comment thread pymilvus/client/global_topology.py Resolved
Comment thread pymilvus/client/global_topology.py Resolved
@bigsheeper

Copy link
Copy Markdown
Contributor

Must-fix issues introduced by this PR: 1
Merge recommendation: Mergeable after the 1 must-fix item below is fixed in this PR.

Adversarial review found one high-severity address-normalization bug in the new on_unavailable primary check, plus two medium issues with how the SRV seed probe behaves during error recovery and the initial connect.

High

pymilvus/client/connection_manager.py:377: on_unavailable compares a port-normalized address with the handler's un-normalized netloc

  • Problem: The comparison value is built as parsed.port or DEFAULT_PORT (:377-383). However, GlobalStrategy.create_handler (:465) and AsyncGlobalStrategy.create_handler (:878) build the handler as GrpcHandler(uri=primary.endpoint) and never pass address. So _address falls back to parsed_uri.netloc (grpc_handler.py:215, async_grpc_handler.py:130). The new check primary_address != managed.handler.server_address (:422-423) therefore never matches for port-less endpoints such as https://in01-xxx.example.com, which the PR's own fixtures use (tests/unit/test_global_topology.py:38).
  • Failure: primary endpoint has no explicit port and the healthy primary returns one UNAVAILABLE / REPLICATE_VIOLATION → in01-xxx.example.com ≠ in01-xxx.example.com:19530. _recover (:724-725) tears down a healthy channel and reconnects to host:19530 instead of the port gRPC actually resolved (443). After that, requests fail or keep reconnecting.
  • Test gap: The connection-manager tests hard-code server_address = "...:19530" (tests/unit/test_connection_manager.py:637,664,695,721), so they don't catch this.
  • Suggestion: In both create_handler implementations, pass address=self._primary_host_port(topology). Then the connection, the comparison and the reconnect all use one normalized form. Choose the default port by scheme (443 for https) instead of always using DEFAULT_PORT. Add a test with a port-less endpoint.

(raised by xiaocai2333, tinswzy)

Medium

pymilvus/client/global_topology.py:299: _probe_candidates wait-all has no overall deadline and runs on the failing RPC's retry path

  • Problem: When a topology version is cached, fetch_topology probes every SRV seed (count=len(targets), :391). _probe_candidates then loops while pending > 0: results.get() with no timeout (:298-300). This runs synchronously inside handle_error → on_unavailable (connection_manager.py:771), and on the sync path nothing debounces it, so each concurrent failing RPC starts its own full fan-out. On the async path it runs in run_in_executor (:1163-1165) while the manager's async lock is held (:1153).
  • Failure: one SRV seed is blackholed while the others are healthy, and an RPC gets UNAVAILABLE / REPLICATE_VIOLATION → on_unavailable stalls about 10s (up to about 20s with connect plus read timeouts) after the healthy seeds have already answered. The failing request's retry is delayed by that much. On the async client, every other connection's error handling queued behind the lock waits too.
  • Suggestion: Add a short grace deadline after the first successful answer, or switch this path to trigger_refresh() plus a first-answer probe. The compare-and-set in _accept_topology already makes a stale first answer harmless.

(raised by xiaocai2333)

pymilvus/client/connection_manager.py:357: initial connect can get stuck on an unreachable first-answer primary

  • Problem: On the first fetch, _probe_candidates returns the first seed answer (break), even though the PR notes that nearby seeds may lag under partial replication. _fetch_and_start_refresher snapshots accepted = self.get_topology() (:356-357), and create_handler builds the handler on that snapshot's primary (:463-466). _create_shared then blocks on handler._wait_for_channel_ready(timeout) (:579), so a newer topology the background watcher installs afterwards doesn't help this attempt.
  • Failure: during a failover the fastest seed returns v8 (primary P1, now down) and a slower seed returns v9 (primary P2) just after → readiness on P1 raises MilvusException ("Fail connecting to server on ..."). Client construction fails even though the cache already holds v9 pointing to a healthy P2.
  • Scope: This only happens when P1 is completely unreachable. If P1 is demoted but still alive, the first write gets REPLICATE_VIOLATION and on_unavailable recovers to P2.
  • Suggestion: When readiness fails and get_topology().primary differs from the handler's address, retry once against the new primary before raising.

(raised by tinswzy, xiaocai2333)

@mergify mergify Bot added ci-passed and removed ci-passed labels Oct 30, 2026
@bigsheeper

Copy link
Copy Markdown
Contributor

Must-fix issues introduced by this PR: 1
Merge recommendation: Mergeable after the 1 must-fix item below is fixed in this PR.

This review found one concurrency regression in the recovery path and one correctness issue in the new bounded topology refresh.

High

pymilvus/client/connection_manager.py:423: a concurrent recovery can stop a required REPLICATE_VIOLATION write retry

  • Problem: GlobalStrategy.on_unavailable now compares the cached primary with managed.handler.server_address (:423-425). Before this PR it compared the primary captured on entry with the fetched primary. In the sync handle_error, on_unavailable runs outside the lock (:773), and the recovery_gen != saved_gen check (:779) only runs inside if should_recover:.
  • Failure: two threads on the same MilvusClient both get STREAMING_CODE_REPLICATE_VIOLATION during a global-cluster failover. Thread B finishes on_unavailable + _recover, and reconnect sets self._address to the new primary P2 (grpc_handler.py:347). Only then does thread A read server_address. A sees the cached primary equal to P2, so on_unavailable returns False and handle_error returns False (:783). decorators.py:450-456 then re-raises the original REPLICATE_VIOLATION, so A's write fails even though the connection already points at P2 and a retry would succeed. With the old logic, A compared P1 with P2 and got True. The generation check then saw B's recovery and returned True, so the write was retried.
  • Suggestion: in the sync handle_error, when the strategy returns False, take the lock and re-check managed.recovery_gen != saved_gen. Return True if the generation changed. Add a test that reproduces this two-thread interleaving.
  • Note: the async handle_error (:1159-1170) has the same outcome for every coroutine queued behind the recovering one. That path was not changed by this PR and returned False before it as well, so it can be handled as separate follow-up work.

(raised by chyezh, bigsheeper)

Medium

pymilvus/client/global_topology.py:331: a bounded refresh discards topology answers that arrive after the grace period

  • Problem: this comes from the PROBE_GRACE_PERIOD cutoff added in this revision. With cached_version set, _probe_candidates starts a 1.0s deadline after the first healthy answer (:326-327) and breaks on timeout (:310-315). Answers still pending are handed to _watch_remaining only when not bounded_refresh (:331-333), and fetch_topology passes on_higher_version=None for every cached refresh (:418). As a result, any answer that arrives after the deadline is dropped. Both callers use the bounded path: TopologyRefresher._try_refresh and GlobalStrategy.on_unavailable.
  • Failure: after a failover, nearby seeds keep answering quickly with a lagging v9, and the seed that already holds v10 keeps answering more than 1s after the first answer. Every refresh then returns None and the cache stays on v9 with the demoted primary. on_unavailable returns False, and writes keep failing with REPLICATE_VIOLATION or UNAVAILABLE until the nearby seeds catch up.
  • Why the slow seed is realistic: _probe_seed uses a bare requests.get (:203) with no shared session, so every probe pays DNS + TCP + TLS setup. A cross-region seed can easily pass 1s. The comment at :404-408 gives "the nearest seeds may lag" as the reason for probing every seed, but timing the grace period from the fastest answer works against that.
  • Impact: lagging seeds normally catch up, so the realistic effect is slower failover convergence rather than a permanent stall.
  • Suggestion: keep the bounded foreground wait, but hand the still-pending results to a background watcher. Each late answer should then go through the strategy's version-guarded _accept_topology compare-and-set. Add a test asserting that a newer version arriving after the grace period is eventually accepted. The existing test at tests/unit/test_global_topology.py:373 only checks that the call returns promptly.

(raised by chyezh, bigsheeper)

@mergify mergify Bot added ci-passed and removed ci-passed labels Oct 30, 2026
@bigsheeper

Copy link
Copy Markdown
Contributor

Must-fix issues introduced by this PR: 0
Merge recommendation: Mergeable as-is — this review found no must-fix issue introduced by this PR.

Adversarial review found no issues requiring changes.

Verified:

  • pymilvus/client/connection_manager.py:332: _accept_topology checks and replaces the topology under the same _lock, so an older or equal version cannot overwrite newer state. All four write paths use it: initial connect, watcher, refresher and on_unavailable.
  • pymilvus/client/connection_manager.py:378: _primary_host_port is used for the handler address=, for get_recovery_address and for the on_unavailable comparison. Both sides of the comparison therefore use the same normalized host:port with the scheme-specific default port.
  • pymilvus/client/connection_manager.py:781: the recovery_gen != saved_gen check is outside if should_recover. If another thread has already recovered the connection, the original RPC still retries.
  • pymilvus/client/global_topology.py:329: after the first successful answer, a PROBE_GRACE_PERIOD deadline limits how long the foreground probe waits. When answers are still pending (:334), _watch_remaining collects them and passes on each answer with a higher version.
  • pymilvus/client/global_topology.py:426: fetch_topology returns None only when a cached version exists and the best answer is not newer than it. Both callers handle None (connection_manager.py:401 and the refresher at :533).
  • pymilvus/client/global_topology.py:401: when no SRV records exist (NXDOMAIN, NoAnswer, or an RFC 2782 . target), the call fails immediately. Transient DNS errors are retried with backoff, and the final exception includes the last seed error.

Tests were read but not run in this round. The relevant ones are the event-gated concurrent-recovery and late-delivery tests in tests/unit/test_connection_manager.py:2281 and tests/unit/test_global_topology.py:418.

Discover ha-manager seed servers through the _grpc._tcp.<host> SRV record
set instead of hitting the global endpoint directly, then concurrently
probe the nearest seeds (spanning priorities) and use the topology with
the highest version.

The topology request now carries the raw endpoint hostname verbatim via
the ?endpoint= query parameter; the server derives the global cluster id
from it (its first DNS label), so the SDK does no gcid parsing. Endpoints
without SRV records raise instead of falling back to the legacy beta path.

Adds a dnspython dependency for SRV resolution.

Signed-off-by: huanghaoyuanhhy <haoyuan.huang@zilliz.com>
All writes to the connection strategy's shared topology now funnel through
a lock-guarded compare-and-set (_accept_topology), so a stale answer can
no longer regress the version however threads interleave:

- initial connect: a background watcher answer arriving before the main
  thread installs the first answer is no longer overwritten by it
- on_unavailable: a wait-all answer at or behind the cached version is
  rejected instead of being assigned unconditionally
- _on_topology_change: late callbacks from older watchers/refreshes are
  ignored when they do not advance the version

fetch_topology now returns None when cached_version is set and no seed
reports a strictly higher version ("no update available"), and the
refresher's private-snapshot write is a compare-and-set under its lock
as well.

Adds tests for the initial-connect lost-update race, stale-answer
rejection on the callback and UNAVAILABLE paths, the None contract, and
the refresher's get_current (shared topology) comparison path.

Signed-off-by: huanghaoyuanhhy <haoyuan.huang@zilliz.com>
@bigsheeper

Copy link
Copy Markdown
Contributor

/lgtm

@huanghaoyuanhhy

Copy link
Copy Markdown
Contributor Author

/assign @XuanYang-cn

Hi @XuanYang-cn, this PR is ready for approval: all findings from bigsheeper's three adversarial reviews are fixed and verified (0 must-fix in the final pass), he has given /lgtm, all 10 review threads are resolved, CI/DCO/codecov are green, and it is mergeable with master. Could you please /approve when you have a moment? Thanks!

Comment thread pymilvus/client/global_topology.py Resolved
Comment thread pymilvus/client/connection_manager.py Resolved
Comment thread pymilvus/client/connection_manager.py Resolved
Comment thread pymilvus/client/global_topology.py Resolved
pymilvus-bot review follow-ups:

- _primary_host_port re-adds the brackets urlparse().hostname strips from
  an IPv6 literal, so handlers and recovery reconnect build valid gRPC
  targets like [2001:db8::5]:443; on_unavailable still compares the same
  normalized form on both sides.

- _probe_seed now raises SeedAuthError (a MilvusException subclass) for
  HTTP 401/403. _probe_candidates aborts the wait as soon as one seed
  rejects the token and no seed has answered yet: the same token goes to
  every seed, so waiting out a stalled probe cannot change the outcome.
  A rejection arriving after a successful answer is kept as before and
  never discards the answer.

Covered by IPv6 normalization/handler/on_unavailable tests and two-seed
fail-fast and answer-preservation regression tests.

Signed-off-by: huanghaoyuanhhy <haoyuan.huang@zilliz.com>
@sre-ci-robot sre-ci-robot removed the lgtm label Nov 6, 2026
@mergify mergify Bot added ci-passed and removed ci-passed labels Nov 6, 2026
…ange

Address remaining pymilvus-bot review findings:

- Verify resolved SRV seed hostnames belong to the global endpoint's
  authorized delegated domain before sending bearer tokens over HTTPS.
  Anchors at the global-cluster subzone label when present (covering SaaS,
  BYOC, and multi-label public suffixes like .com.cn) with a parent-domain
  fallback, rejecting untrusted targets on a label boundary without retry.

- Retry initial sync/async connection once against the updated primary if
  readiness fails after the background watcher installs a newer topology.
  Clean up the strategy (stopping TopologyRefresher and closing the
  handler) when initial handler creation or readiness fails.

- Normalize scheme-less primary endpoints in _primary_host_port.

Signed-off-by: huanghaoyuanhhy <haoyuan.huang@zilliz.com>
@mergify mergify Bot removed the ci-passed label Nov 20, 2026
@mergify

mergify Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

This pull request is merged.

@mergify mergify Bot added ci-passed and removed ci-passed labels Nov 20, 2026
Signed-off-by: huanghaoyuanhhy <haoyuan.huang@zilliz.com>
@mergify mergify Bot added the ci-passed label Nov 23, 2026
@XuanYang-cn

Copy link
Copy Markdown
Contributor

/lgtm
/approve

@sre-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: huanghaoyuanhhy, XuanYang-cn

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@sre-ci-robot
sre-ci-robot merged commit ff967fd into milvus-io:master Nov 24, 2026
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants