Skip to content

refactor: unify provider discovery contract for PR A - #48

Open
NeverENG wants to merge 11 commits into
apache:mainfrom
NeverENG:refactor/metadata-registry-ownership
Open

NeverENG wants to merge 11 commits into
apache:mainfrom
NeverENG:refactor/metadata-registry-ownership

Conversation

@NeverENG

@NeverENG NeverENG commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

PR A for #42 establishes a backend-neutral provider discovery contract and migrates ZooKeeper/Nacos discovery behind it. Typed snapshots distinguish available providers, confirmed empty results, transient failures, invalid requests, and permission errors. The public invocation API remains compatible.

The current implementation also protects endpoint freshness during overlapping calls and notifications, restores watches after transient reads fail, and bounds recovery work. PR B will add etcd v3 interface-level discovery on this contract. This PR does not include an etcd SDK, metadata publication, application-level discovery, or .NET Provider export.

Snapshot application and recovery

  • Notifications refresh services whose first snapshot application is still active, even before a driver exists. This prevents a delayed first snapshot from installing superseded endpoints. Synchronous subscription callbacks are queued outside the lookup factory, and invalidations still refresh after an overlapping lookup faults.
  • Completed snapshots receive a local sequence, separate from optional backend revisions. Delayed Available/Empty results cannot replace or clear newer endpoints.
  • Sequence comparison and driver updates are serialized per service. The global application-state map is used only to register/release overlapping callers, never held through driver creation or disposal. Its entries are removed when the last caller finishes, including cancellation/failure, and cleared on client disposal.
  • Query recovery uses a loop with at most three discoveries. After an older result is rejected, selection uses the latest applied endpoints. Exhaustion returns an error rather than applying the older snapshot.
  • Registry reload uses an atomic guard released in finally. One service refresh throwing is logged without preventing the remaining services from refreshing.
  • Identical provider configuration does not trigger metadata reload. Configuration changes at the same address, including metadata-relevant fields, still count as changes. Metadata-center subscriptions independently handle metadata-only changes.

ZooKeeper watches and Empty semantics

  • A missing service node (/dubbo/<service> with the default root) is intentionally Empty, as is a providers node with zero usable children. Existing driver endpoints are cleared; existence/children watches detect recreation.
  • Malformed ZooKeeper URLs with missing or zero ports are ignored individually. Healthy sibling registrations remain usable; a directory with no usable registrations is Empty.
  • Unavailable and permanent failures retain existing endpoints. Transient discovery failures retry; permanent failures and Empty do not.
  • When an unavailable lookup may have consumed a one-shot watch, the adapter attempts one best-effort watched Exists/children repair. It preserves the original failure result and does not add SDK retries. A watched Exists alone would not cover provider child-list changes.
  • Pending repairs also subscribe to the shared ZooKeeper client's default session notifications, so recovery can proceed after SyncConnected even when no node watch remains. Adapter disposal removes only its own connection listener. An unreachable ZooKeeper cannot accept a watch; repair also runs on subsequent discovery.
  • Metadata discovery requires a nonempty Available result. Temporary Empty results do not poison the permanent Telnet negative cache or incorrectly report that all Provider releases are too old.
  • For compatibility, business calls with Empty retain the existing GetSeviceProviderEndPoints fail / no provider error wording, although discovery itself succeeded with no providers.

Retry configuration and cost

DubboClientConf now exposes:

Setting Default
ProviderDiscoveryMaxAttempts 3 snapshot attempts, including the first
ProviderDiscoveryBaseDelay 100 ms
ProviderDiscoveryMaxDelay 2 s before jitter
ProviderDiscoveryJitterRatio 0.2 (±20%; 0 disables jitter)

Only Unavailable snapshots retry. Default waits are 80–120 ms and 160–240 ms. ZooKeeper adapter reads pass retryTime: 0 to avoid stacking MyZookeeper retries. Watch repair adds a separate best-effort subscription sequence per unavailable lookup; it is not another snapshot attempt.

Each of the query's three discoveries has the configured snapshot budget: repeated superseding notifications can therefore lead to at most nine snapshot attempts by default. One snapshot can contain several SDK reads, whose timeouts still apply. Binary Triple retains its whole-call deadline including discovery. These retries do not replay business requests. Details are in the English/Chinese registry architecture docs.

ProviderRegistrySnapshot.Revision remains optional for backends with a reliable revision. Current adapters leave it unset: the narrow ZooKeeper reader does not return an atomic children-list revision, and this Naming path provides no equivalent version. Local application ordering never depends on that field.

Verification

On the current implementation:

  • .NET 10 library unit suite: 877 passed, 0 failed.
  • netstandard2.0 library under the .NET 10 test host: 877 passed, 0 failed.
  • Library builds: netstandard2.0, net8.0, and net10.0 succeeded.
  • End-to-end project builds: net6.0 and net10.0 succeeded.
  • Real ZooKeeper lifecycle test passed with both net10.0 and netstandard2.0 assets under .NET 10. It covers missing-service creation, empty providers, deletion, and recreation, using separate publisher/consumer sessions and a unique subtree. The temporary server was stopped after validation.
  • 21 additional cases in e38c0bb cover per-service locking, default session listener lifetime, failed watch repair and recovery, configurable retry parameters and validation, unchanged-provider metadata behavior, and continuation after a service refresh throws.
  • Mutation checks fail when global locking is restored, watch repair or default session notifications are removed, unchanged-provider metadata refreshes are re-enabled, or per-service recovery continuation is removed. Updated deterministic stale-snapshot tests also fail if ordering protection is removed.
  • Eight additional cases in b9dce71 cover notifications before first-driver creation (replacement/Empty), synchronous subscription callbacks, failed lookup notification handoff, and missing/zero provider ports (with/without healthy siblings). All eight fail before the corresponding fixes and pass afterward.
  • The preceding ten review regression cases cover Empty metadata recovery, dynamic missing services, success/failure/cancellation/disposal cleanup, and bounded query rediscovery.
  • Local .NET 6/8 runtime execution and the full Java Provider/Nacos matrix were not rerun. They remain CI validation. The c636d08 CI runs passed build/test, license checks, and the full registry/provider matrix; those results do not validate later commits.

main@b4b4500 (#47) was merged in 2dd4007. Recovery fixes are in c636d08; the first three review fixes are in 5488612; watch/locking/configuration hardening is in e38c0bb; first-discovery notification and malformed-port fixes are in b9dce71.

Related

Part of #42
Related to #36

Comment thread Registry/ProviderDiscovery.cs Resolved
@AlexStocks

Copy link
Copy Markdown
Contributor

审查结论(源码级)

以 base 4e3741e、head 74b65d88 为基准读完 48 个变更文件,未发现阻断缺陷。

关键链路已核对:watch 重新武装(Registry/ProviderRegistryAdapter.cs 注册 Exists + GetChildren 双 watch → Clients/DubboClient.cs#ReflushProviderAsync → 再走 GetSnapshotAsync 重注册)不存"一次性 watch 用完即永久失聪";元数据刷新用的是独立的 MetadataWatcher(Metadata/DubboMetadataManager.cs),不受 DubboClientZookeeperWatcher 对 NodeChildrenChanged 直接 return 的影响;Metadata/DubboInvocationMetadataResolver.cs 与删除的 CreateMetadataInvocationAsync 逐段比对无逻辑丢失;MyNacos / MyZookeeper / ZNode 等文件虽搬到 Registry/,namespace 未变,公开 API 兼容。

[P2] 服务节点整体消失时会清空端点,行为变更需确认是否有意

  • 位置:Registry/ProviderRegistryAdapter.cs:206-213
  • 触发条件:ZK 中该服务的 provider 父节点根本不存在(Exists 返回 false),而非"节点存在但子节点为空"。
  • 实际影响:旧实现对缺失节点返回 serviceName [x] is error,不匹配 IsNoProviderError,因此只 LogError 并保留现有端点;新实现统一归入 Empty,而 Clients/DubboClient.cs:1088-1101 对 Empty 会调用 AddDubboServiceDriver(serviceName, 空列表),DubboDriverCollection 会真的清空该服务端点并丢弃元数据缓存。结果:服务在 ZK 中被整体删除(下线、测试环境清理、误删)时,客户端立即清空全部端点、下一次调用直接 no provider;旧版会保留旧端点继续尝试。
  • 修复方向:若"服务消失即无 provider"是刻意语义,建议在 PR 描述中写明;否则应把"节点不存在"与"节点存在但无子节点"区分开,前者沿用保留端点的旧行为。

(Registry/ProviderDiscovery.cs:216 那条重试叠加的评论已存在,不重复。)

状态

当前 mergeable=false / dirty,与 main@4e3741e 冲突,需先 rebase。另外 #47 也重写了 Clients/DubboClient.cs,两者合并顺序会互相冲突。

未覆盖范围

本机无 dotnet SDK,未编译、未运行测试,全部结论来自源码推导。

@AlexStocks

Copy link
Copy Markdown
Contributor

@NeverENG plz fix the file confiction.

@NeverENG
NeverENG force-pushed the refactor/metadata-registry-ownership branch from 5ce65db to 91036c1 Compare November 30, 2026 08:04
@NeverENG

Copy link
Copy Markdown
Contributor Author

@AlexStocks 两件事都处理了。

1. 冲突:分支已 rebase 到 main@4e3741e,PR 现在是 MERGEABLE(之前 10 个与 #36 重复的提交已不在分支上,只保留 4 个发现契约提交)。本地验证:

  • dotnet test Tests/UnitTestForDubboNet/UnitTestForDubboNet.csproj -f net10.0 -p:GeneratePackageOnBuild=false → 686 passed
  • netstandard2.0 / net8.0 / net10.0 构建通过
  • Tests/DubboNetEndToEndTests 构建通过(真实注册中心环境未配置,E2E 用例未执行)

2. [P2] 服务节点整体消失时会清空端点:确认是刻意语义,已写进 PR 描述 Behavior notes。状态划分如下:

  • 服务节点不存在(/.../services/<service> 缺失)→ Empty:客户端清空该服务端点,同时在服务节点上重装 Exists watch,节点重建后会自动触发刷新;
  • 注册中心断开 / 读取失败 → Unavailable:客户端只记录错误并保留现有端点,行为与旧版一致。

理由:能确认节点真实不存在时,继续保留旧端点只会把请求继续打到已下线实例;而瞬时故障仍然走 Unavailable 保留端点的路径。对应覆盖:ZooKeeperRegistryPathContractTest.ZooKeeperDiscovery_MissingServiceIsEmptyAndWatchedForCreation 与 ..._MissingServiceCreationInvalidatesEmptySnapshot。

另外 #47 与 Clients/DubboClient.cs 的合并顺序冲突,等它落地后我再跟一次 rebase。

@NeverENG
NeverENG force-pushed the refactor/metadata-registry-ownership branch from 8e92921 to 91036c1 Compare November 30, 2026 08:19
@AlexStocks

Copy link
Copy Markdown
Contributor

@NeverENG there are some github ci failures. plz fix them.

Merge main after apache#47 while retaining provider snapshots and cancellation in both discovery recovery paths. Add HTTP/2 regressions for independent cancellation during discovery and cancellation after dispatch.

Part of apache#42

Signed-off-by: bang <3656828039@qq.com>
Order completed discovery snapshots independently of backend revisions so delayed callers cannot replace newer providers. Release the atomic recovery guard after refresh failures.

Cover provider retention, empty snapshots, recreation, overlapping notifications, delayed callers and retryable recovery through real HTTP/2 calls. Add a real ZooKeeper watch lifecycle test with isolated publisher and consumer sessions.

Part of apache#42

Signed-off-by: bang <3656828039@qq.com>
@NeverENG

NeverENG commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

@AlexStocks,冲突和相关问题已修复,补充了恢复及并发场景测试,本地两组单元测试各 838 项通过,真实 ZooKeeper 生命周期测试也已通过。最新 CI 正在等待维护者批准,麻烦帮忙放行,我们再根据结果跟进。

Comment thread Clients/DubboClient.cs Resolved
Comment thread Clients/DubboClient.cs Resolved
Comment thread Clients/DubboClient.cs Resolved
Reject empty metadata discovery before Telnet probing and version checks. Track snapshot watermarks only while discovery/application operations overlap, with cleanup on completion, failure, cancellation and disposal. Replace recursive routing recovery with a three-attempt discovery budget.

Add ten regression cases for metadata recovery, dynamic missing services, state cleanup and repeated stale snapshots. Keep deterministic coverage for delayed snapshots preserving newer providers.

Part of apache#42

Signed-off-by: bang <3656828039@qq.com>

@NeverENG NeverENG left a comment

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.

审查结论:建议合并(LGTM with comments)

方向正确:把「读到哪里算哪里」的 ZK/Nacos 分支替换为后端无关的 snapshot 契约(5 种状态)+ 序号 watermark + 有界重试,并把 watch 生命周期收拢到一个 adapter 里。噪声最大的两处旧逻辑(IsNoProviderError 字符串匹配、路径反解析服务名)都被消掉了。

本地验证(head 5488612):

  • dotnet build DubboNet.csproj(net8.0 / net10.0 / netstandard2.0):0 error。
  • dotnet test Tests/UnitTestForDubboNet -f net10.0:848 passed, 0 failed。

写得好的地方:

  1. ProviderRegistrySnapshotState 让「确认没有 provider」与「后端暂时不可用」彻底分开,只有 Empty 才清空 driver 候选。
  2. watch 注册的丢事件窗口被显式关掉:无 watch 探测 → RegisterWatch → 再带 watcher 读一次;providers 节点不存在时退化为监听服务目录;children == null 时二次 Exists 区分「节点被删」与「后端抖动」。
  3. 序号 + 引用计数(LatestSequence / Readers)在取消、异常、Dispose 路径都由 finally 释放,且用 RemoveExact(KeyValuePair) 而不是 TryRemove(key),避免误删并发新建的 lookup。
  4. 通知与 in-flight 查询的竞态用 DispatchAfterLookupAsync(先等查询完成、精确摘除、再派发刷新)处理,不会被合并吞掉。
  5. ReLoadDubboDriverCollection 用 Interlocked.CompareExchange + finally 取代 volatile bool,修掉了异常路径永久卡死的可能。

下面 7 条行内评论是具体建议,都不阻塞合并;另外几条只能写在正文里:

  • Registry/ProviderRegistryAdapter.cs 的 ProviderRegistrySnapshot.Revision 目前所有 adapter 都传 null,只出现在一行诊断日志中:要么从 ZK Stat / Nacos 版本真正填上,要么删掉,避免读者以为存在 revision 语义。
  • Clients/DubboClient.cs:957 在 Empty 状态下仍返回 "[SendRequestAsync] GetSeviceProviderEndPoints fail ..."。语义上 discovery 已成功、只是没有 provider,保留旧文案对兼容性友好,建议在 PR 描述里点明这是有意为之(有调用方可能按该子串匹配)。
  • Registry/ProviderRegistryAdapter.cs:151 process(WatchedEvent @event) 没有 null 防护(MyWatcher 有),@event.getState() 会 NRE;ZKNetEx 正常不会传 null,属 nit。
  • _watchers 只在 Dispose 里 Clear(),服务名集合无限增长的场景下会有微小内存增长,可忽略。
  • 文档(Docs/en|zh/architecture/registry.md)里「Empty provider directories are watched too; if the directory does not exist, the service directory is watched」容易被读成「任何时候都有 watch」,与「刷新失败后 watch 不重挂」的实际行为有出入,建议随行内评论一并校准。

建议补充的测试:

  1. DiscoverAndApplyProvidersAsync 与 Dispose() 竞争:水印表被清空后 finally 里 --Readers 的路径。
  2. 连续通知风暴下 QueryInternalAsync 的 3 次预算不会被 Applied == false → continue 饿死。
  3. 刷新失败后 watch 的重挂(若采纳对应建议)。

Comment thread Clients/DubboClient.cs Resolved
Comment thread Registry/ProviderRegistryAdapter.cs Resolved
Comment thread Registry/ProviderRegistryRetryPolicy.cs Resolved
Comment thread Clients/DubboClient.cs Resolved
Comment thread Registry/ProviderRegistryAdapter.cs Resolved
Comment thread Clients/DubboClient.cs Resolved
Comment thread Clients/DubboClient.cs Resolved
Serialize snapshot application per service without holding the global state map through driver updates. Repair consumed ZooKeeper watches after unavailable reads and recover pending subscriptions from default session events, with listener cleanup on disposal.

Expose retry budgets, backoff delays and jitter through client configuration. Skip metadata refreshes for unchanged provider configuration, continue recovery after per-service failures, and document retry costs, optional backend revisions and Empty error compatibility.

Add 21 regression cases covering lock contention, watch repair and default connection notifications, configurable retries, and metadata refresh behavior. Preserve deterministic stale-snapshot coverage without synchronization-context capture.

Part of apache#42

Signed-off-by: bang <3656828039@qq.com>
Refresh notifications while the first snapshot application is still active, even before the service driver exists. This advances the shared sequence watermark so delayed initial snapshots cannot install superseded endpoints.

Queue notification dispatch outside the Lazy lookup factory and retain invalidations when the overlapping read faults. Ignore ZooKeeper provider URLs with missing or zero ports without discarding valid siblings.

Add eight regression cases for first-driver ordering, synchronous subscription callbacks, failed lookup handoff, and malformed provider ports. Update both registry architecture documents.

Part of apache#42

Signed-off-by: bang <3656828039@qq.com>
// Retain routing even if the very first network read fails.
string servicePath = $"{_rootPath}{serviceName}";
string providerPath = servicePath + ZooKeeperRegistryPaths.ProvidersSuffix;
RegisterWatch(servicePath, serviceName, onChanged);

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.

[P2] 释放已无消费者的服务 watch 路由,避免长期累积

这里为每个查询过的服务无条件写入 service/provider 两条 _watchers 记录,但 RegisterWatch 只有覆盖写入,唯一清理路径是 adapter 的 Dispose()。查询返回 Empty/失败、调用取消或服务驱动被 MaintainServiceNum 淘汰后,都不会移除对应记录。尤其是查询不存在的接口:调用完成后既无 driver、待完成的快照应用,也无缓存元数据,后续通知会被 HandleProviderRegistryChangedAsync 跳过,但映射仍然保留。

按当前源码,一个长期存活的客户端查询 N 个不同的不存在接口,就会保留约 2N 条路径记录;例如 10,000 个接口对应 20,000 条记录,与默认只缓存 20 个 driver 的上限无关。该新增持久状态在客户端销毁前无法回收。此处是源码级判断,本轮未执行运行时复现。

建议根据待完成查询、driver 和元数据缓存的实际使用状态,对 adapter 的路由及 _pendingWatchRecovery 做生命周期清理或有界淘汰,同时保留首次发现与通知交错时的保护;补充大量不存在服务查询及 driver 淘汰后的回归测试。

@NeverENG NeverENG left a comment

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.

Review summary

Thanks — the direction is right. Splitting "how to read a registry" from "what a snapshot means" (ProviderRegistrySnapshotState with Available / Empty / Unavailable / InvalidRequest / PermissionDenied) and deleting the string matching (IsNoProviderError and friends) is the most valuable part of this PR: "no providers" stops being indistinguishable from "the registry is down".

Verified on b9dce71 in a clean worktree (the pr-48-conflicts worktree is read-only for builds):

  • dotnet build Tests/UnitTestForDubboNet/UnitTestForDubboNet.csproj -c Release → 0 errors (14 pre-existing warnings).
  • dotnet test -f net10.0 → 877 passed, 0 failed, matching the PR description.

What I really liked: typed snapshots instead of error strings; an injectable, validated retry policy (ArgumentOutOfRangeException on nonpositive attempts / negative delays / non-finite or out-of-range jitter) with retryTime: 0 at the ZooKeeper layer so the two retry layers do not multiply; watch registration before the first read; the snapshot sequence watermark, including the "initial read completed but the driver is not created yet" window handled through metadata refresh; HasSameProviderConfiguration to stop metadata reload storms; Nacos subscription ownership moved into the adapter with correct disposal ordering.

Points raised inline, roughly by severity:

  1. ZooKeeperProviderRegistry only repairs watches on SyncConnected, so session expiry leaves most services unwatched while Docs/en/architecture/registry.md:26 says otherwise; the existing DubboClientZookeeperWatcher expiry path is not reachable in the current wiring.
  2. _onRegistryRecovered() still runs synchronously inside the Lazy factory, so the recovery callback can re-enter the in-flight lookup (repro included) — the same bug class this PR fixed for change notifications.
  3. The three-attempt discovery budget is also spent on NoActuatorInService (group/version/method mismatch), where a reread can never help, and then reports "discovery did not stabilize".
  4. NoNode now maps to Empty and clears the driver, while the old code deliberately preserved the last endpoints. Please confirm that is intended and pin it with a test.
  5. Nits: one redundant ExistsAsync in the empty-service path, adapter exceptions bypassing the retry budget, and the PR description could call out the removed internal members.

None of this questions the architecture — 1-4 all look like small, local fixes. Happy to re-review once they land.

await RecoverPendingWatchesAsync().ConfigureAwait(false);
}

private void OnDefaultConnectionEvent(WatchedEvent @event)

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.

Session expiry does not rebuild most watches.

_pendingWatchRecovery only receives services whose last snapshot was Unavailable (line 269), and this handler only reacts to SyncConnected. After KeeperState.Expired every node watch from the old session is gone, so:

  • a service that is currently Available keeps no watch until its next read, and
  • a service that is legitimately Empty with no driver is never re-read at all: HandleProviderRegistryChangedAsync (Clients/DubboClient.cs:1316) has nothing to do without a driver or cached metadata, so the pending entry stays forever without a watch being installed.

The existing safety net in Clients/DubboClientZookeeperWatcher.cs (Disconnected/Expired → StartConnecTaskAsync → ReLoadDubboDriverCollection) does not close this gap: MyZookeeper offers no way to plug in a connection watcher (Registry/MyZookeeper.cs:200 routes session events only to DefaultWatch), and _dubboClientZookeeperWatcher is invoked only from ForwardConnectionEventAsync, which needs a node watcher to receive a non-node event.

Suggestion: on Expired / AuthFailed, mark every service in _watchers as pending (or invoke all callbacks) so reconnection performs a real reload; alternatively wire ConnectionStateChanged into the existing connection watcher and let its reload path run. Until then Docs/en/architecture/registry.md:26 ("connection loss and session expiration ... after recovery, services are reread and watches reinstalled") promises more than the code does.

}

if (stat.getNumChildren() > 0)
_onRegistryRecovered();

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.

_onRegistryRecovered() still runs synchronously inside the Lazy<Task<ProviderRegistrySnapshot>> factory.

DubboClient's callback (Clients/DubboClient.cs:461-466) synchronously starts ReLoadDubboDriverCollection(), which reaches GetProviderEndPointsAsync for the same service and therefore hits the Lazy that is currently executing. Minimal repro with a fake IProviderZooKeeper and ForZooKeeper(..., onRegistryRecovered: () => _ = discovery.GetProviderEndPointsAsync(Service)):

InvalidOperationException: ValueFactory attempted to access the Value property of this instance.
inFlightContainsService=False   // checked from inside the callback, while the outer read is still running

Two consequences: the nested call always faults (swallowed by the per-driver catch in ReLoadDubboDriverCollection, so it only shows up as a misleading error log), and its finally executes _inFlight.RemoveExact(...) while the factory is still running. That breaks the one-read-per-service invariant: a concurrent notification or business call can GetOrAdd a second Lazy and run two overlapping reads, and since DiscoverySequence is assigned on completion (Registry/ProviderDiscovery.cs:225 and below), an older snapshot can be applied last — exactly the ordering the sequence watermark is there to prevent.

The change-notification path already solves this properly with the queued Task.Run in OnRegistryChangedAsync; please apply the same deferral here (or fire the callback after the Lazy completes). Same pattern exists in b4b4500, so this is not a regression — but it is the same bug class, and there is currently no test for the recovery callback (the analogous SynchronousNotificationDuringSubscriptionRefreshesAfterInitialRead exists for notifications).

Comment thread Registry/ProviderRegistryAdapter.cs Outdated
// can proceed through its children, while a missing service
// retains a NodeCreated watch for a later refresh.
await _zookeeper
.ExistsAsync(servicePathForLookup, retryTime: 0).ConfigureAwait(false);

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.

Nit: this ExistsAsync is a wasted round trip — the result is discarded and the very next call performs the same read with the watcher installed.

The race rationale in the comment does not hold either: exists(path, watcher) installs the watch atomically with the read, so there is no window between "check" and "install" to close. Dropping lines 336-337 and keeping RegisterWatch(...) + the watched ExistsAsync gives the same guarantees with one request fewer on every empty-service lookup.

Comment thread Clients/DubboClient.cs
string tempErrorMes = $"[SendRequestAsync] GetSeviceProviderEndPoints fail {nowServiceName} -> {serviceEndPointsInfo.ErrorInfo}";
MyLogger.LogWarning(tempErrorMes);
return new DubboRequestResult()
if (discoveryAttempts++ >= MaxDiscoveryAttempts)

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.

This budget is also spent where rereading cannot help.

NoActuatorInService covers group/version/method mismatches: the snapshot is already Available, the endpoints are fine, and no number of refreshes will produce a matching actuator. Each such call then pays up to 3 complete discoveries × ProviderDiscoveryMaxAttempts (9 ZooKeeper reads plus backoff sleeps with defaults) and finally reports "Provider discovery did not stabilize", which points at the wrong cause.

Two related nits: MaxDiscoveryAttempts (Clients/DubboClient.cs:251) is a hardcoded const that is easy to confuse with the configurable ProviderDiscoveryMaxAttempts, and Docs/en/architecture/registry.md:47 only documents the "newer snapshot keeps winning the race" trigger, not this one.

Suggestion: when the snapshot is Available and only NoActuatorInService remains, skip the refresh and return a deterministic configuration error (e.g. "endpoints exist but no actuator matches group/version/method"); otherwise rename the const to MaxDiscoveryRefreshes or reuse the configured budget, and document the product of the two limits.

Comment thread Clients/DubboClient.cs
if (snapshot.State == ProviderRegistrySnapshotState.Available)
changed = _dubboDriverCollection.AddDubboServiceDriver(
serviceName, new List<DubboServiceEndPointInfo>(snapshot.EndPoints));
else if (snapshot.State == ProviderRegistrySnapshotState.Empty

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.

Behaviour change worth confirming: a missing service node now clears routing state.

NoNode maps to Empty (Registry/ProviderRegistryAdapter.cs:346 and :361), and Empty clears the driver here. In b4b4500 the equivalent decision came from IsNoProviderError, which matched only no provider / no healthy provider, so serviceName [x] is error preserved the last known endpoints.

Consequences now: a mistyped DubboRootPath, a mistyped interface name, or the service node being briefly absent during re-registration tears down a driver that was working. If Empty is meant to mean "the providers path exists and is confirmed empty", then NoNode is arguably a different state (configuration/InvalidRequest), or should keep the previous snapshot.

Whichever semantics you pick, please pin it with a test — right now neither the old nor the new behaviour is locked, and this is the kind of change that shows up as a production incident when a root path is wrong.

/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
private async Task<DubboServiceEndPointInfos> DiscoverAsync(string serviceName ,bool isFullPath = false)
private async Task<ProviderRegistrySnapshot> DiscoverAsync(string serviceName)

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.

DiscoverAsync does not guard against an adapter that throws, so an exception bypasses the retry policy and escapes into the business call path: DiscoverAndApplyProvidersAsync (Clients/DubboClient.cs:1230) has no catch, so QueryInternalAsync throws instead of returning DubboRequestResult { QuerySuccess = false }.

The built-in adapters catch broadly today, but GetSnapshotAsync still throws ObjectDisposedException on a disposal race (Registry/ProviderRegistryAdapter.cs:269), and PR B's etcd adapter will add surface here. Suggest converting anything except ObjectDisposedException into an Unavailable snapshot around the adapter call, so the configured budget applies and callers keep getting a result object rather than an exception.

@CarolDestiny

Copy link
Copy Markdown
Contributor

@NeverENG Review of b9dce71
I reviewed this revision against b4b4500. The main repros ran on .NET 10 and on .NET 8 with the netstandard2.0 library. I'd address the five P1 findings before merging. I've separated the cases that still need a contract decision or real-session verification.

P1 — before merge
R01 · Recheck the overload restriction after discovery (DubboClient.cs:969). An explicit-signature call in HTTP/JSON mode can check metadata while no provider is available, then discover a tri:// provider that exposes multiple overloads. The loop reuses the earlier protocol decision: the fake handler received a JSON POST, whereas the old path rechecked metadata and would reject locally if no native provider was available. Please recheck the protocol restriction before selecting from the new snapshot.

R02 · Don't require listing the interface node to clear missing providers (ProviderRegistryAdapter.cs:351). A client may be allowed to read /providers but not list the interface node's children. When /providers disappeared in the ACL simulation, the parent lookup produced NoAuth. The PR returned PermissionDenied and kept one stale candidate, while the baseline cleared it. Could we watch for creation on /providers itself, without requiring the parent listing?

R03 · Refresh metadata even when the new driver is already in place (DubboClient.cs:1224). A metadata-only lookup cached application A's signature. A business call installed B's driver before the registry notification; when the callback re-read B, Changed == false skipped metadata refresh. A subsequent lookup still returned A's java.lang.String signature instead of B's java.lang.Long. Could metadata invalidation track the provider identity used to load it rather than whether this refresh changed the driver?

R05 · Avoid rooting unused clients through the shared connection event (ProviderRegistryAdapter.cs:158). The shared connection now retains the adapter, whose watcher retains the client. A weak-reference test collected a never-queried client on the baseline but not on the PR. Without explicit Dispose, the existing finalizer can't run while the subscription keeps the client reachable. Could the connection observer avoid strongly holding the client while still unregistering on disposal?

R06 · Clean up local watch routes when service interest ends (ProviderRegistryAdapter.cs:260). With MaintainServiceNum = 1, the first driver was evicted but its provider path remained in _watchers. The driver cap therefore doesn't bound watch-route records for previously queried services. Could we clear records that no longer have a driver, cached metadata, or an in-flight consumer, or otherwise bound their lifetime?

Questions to resolve
R04 · P1 candidate: can watch repair leave stale routes in place? (ProviderRegistryAdapter.cs:298). After a one-shot notification and a failed final read, the fake reader let repair successfully read replacement B and re-arm the watch, but the returned snapshot was still Unavailable. If no new node change or reconnect follows, what triggers reconciliation? The unit test confirms the read is discarded, not that this event order occurs on a real session.

R09 · Should an unsuccessful refresh supersede a success that hasn't been applied yet? (DubboClient.cs:1285). A gated test let a newer Unavailable advance the sequence before the initial Available was applied. The success was rejected and no driver was installed. Is that intentional, or should only Available and Empty advance the sequence used to apply routes? A test for the intended contract would help.

P2 — non-blocking behavior issues
R07 · Classify invalid paths before retrying (ProviderRegistryAdapter.cs:445). Injecting the ArgumentException that the SDK documents for local validation returned Unavailable and incurred two backoffs and six read attempts including repair. An invalid composed path should return InvalidRequest without registering a watch or retrying.

R10 · Cancel retry backoff on discovery disposal (ProviderDiscovery.cs:249). In the gated test, the waiter remained pending after Dispose until the delay gate was released. Could the delay observe a discovery-lifetime token without letting an individual caller cancel the shared lookup?

P3 — configuration edge case and test coverage
R08 · Validate retry delays before use (ProviderRegistryRetryPolicy.cs:79). With two attempts, 60-day base and maximum delays, and jitter disabled, configuration succeeds but the first Task.Delay throws ArgumentOutOfRangeException. Please reject delays beyond the supported timer range up front, accounting for jitter, or support them explicitly.

R13 · Match the empty snapshot to the directory-deletion step (ZooKeeperProviderDiscoveryEndToEndTests.cs:114). With an extra Empty queued from the preceding step, the helper returned that snapshot instead of the one for the deletion under test. This is an in-memory check of the helper, not real-session evidence. Can the assertion wait for the deletion's corresponding notification or refresh rather than matching on state alone?

@NeverENG

NeverENG commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

@CarolDestiny Thanks for the detailed repro scenarios. I checked the relevant paths at b9dce719ba3f2a6f2a0fac847aeb50476586bdbf against b4b4500. This is a source-level triage; I have not independently rerun your repro suite.

  • R01 / R02 / R03: Agreed, these are correctness regressions to address before merging. The selection loop retains the protocol decision made before discovery; the missing-provider branch adds a parent GetChildren permission requirement; and discovery.Changed describes the driver update, not whether cached metadata came from the current provider identity. The baseline re-entered the protocol check after discovery and refreshed metadata even when updating the driver reported no change. Rechecking protocol constraints, watching the provider path directly, and separating metadata invalidation from driver-change detection are the appropriate directions.
  • R05: Agreed on the retention chain: shared connection → event delegate → adapter → client callbacks/watcher. Unsubscribing in Dispose does not help a client that cannot become eligible for finalization. A weak connection observer needs to avoid capturing the adapter/client strongly and still support explicit unsubscription.
  • R06: Confirmed; this is also the issue in the existing inline thread. There is a local, unpushed patch that releases local routing/recovery records when there is no pending lookup/application, driver, or metadata interest. Its six regression cases cover unused lookups, eviction, cancellation and overlapping callers, and retaining metadata-only interest. They fail on the current PR Head and pass with the patch. This is not fixed in the published Head yet, and the patch does not claim to remove outstanding SDK/server one-shot watches.
  • R04: The source supports the reconciliation concern: watch repair can successfully read/re-arm B while the final snapshot remains Unavailable; adding the service to the recovery set does not itself schedule another refresh. Re-arming alone does not apply B. I agree this needs follow-up, while keeping the real-session event sequence explicitly unverified rather than calling it an independently reproduced production failure.
  • R09: Confirmed that LatestSequence advances before checking the snapshot state, so a newer failure can suppress an older successful snapshot that has not been applied. I lean toward failures preserving the last usable routing result without advancing its application watermark, while keeping Empty authoritative. That behavior should be pinned with the overlapping-application test.
  • R07 / R10: Agreed on the code paths. Local ArgumentException currently falls into the retryable catch, and the retry delay has no discovery-lifetime cancellation. Path validation should precede watch registration/retries; disposal cancellation should remain separate from an individual caller's cancellation of a shared lookup.
  • R08 / R13: Agreed as configuration-validation and test-reliability issues. Validate the effective delay, including jitter, against the supported timer range. The E2E helper currently matches only State, so an earlier queued Empty can satisfy the later deletion assertion; that step needs an event/refresh boundary tied to the mutation being tested.

The current Head should not be treated as merge-ready based on the existing passing tests. R06's local fix covers one of these findings; it does not resolve the other scenarios above.

Recheck protocol restrictions after discovery, remove the parent ACL requirement for missing providers, and refresh cached metadata independently of driver changes. Apply successful watch repair reads and prevent failed snapshots from superseding usable results.

Use a weak shared connection observer, release unused local watch routes, validate paths and retry delays, and cancel backoff on discovery disposal. Add regression coverage and make the ZooKeeper deletion assertion reject snapshots from earlier phases.

Validation: 899 tests passed each on .NET 10, .NET 8, and the netstandard2.0 asset under .NET 8. The E2E helper regression passed; real ZooKeeper sessions were not rerun because the Docker daemon was unavailable.

Part of apache#42

Signed-off-by: bang <3656828039@qq.com>
@CarolDestiny

Copy link
Copy Markdown
Contributor

@NeverENG review of 31042a7
I reran the original R01–R10 repros, and all ten now pass. The follow-up tests found one remaining case of R01 and two watch lifecycle regressions. I'd fix the P1 before merging.

P1 — Recheck the overload restriction when a newer refresh wins (DubboClient.cs:967)

The patch rechecks the protocol when the caller applies its own Available snapshot, but !discovery.Applied skips that check. In a gated test, the initial metadata lookup found no providers. A concurrent refresh then installed a Triple-only provider with two overloads before the caller could apply its older snapshot. The caller discarded the old snapshot but kept its earlier protocol decision, and the recording handler received a JSON POST instead of a local rejection. This reproduced on both tested framework combinations; it does not establish which overload a Java server would select.

Could we recheck the protocol before selecting from the newer route as well?

P2 — Don't remove a watch route acquired during cleanup (DubboClient.cs:1293)

A metadata-only lookup can register a watch after cleanup has checked that the service has no remaining consumers, but before it removes the local route. In the gated test, the metadata lookup cached provider A's signature, cleanup removed its newly registered route, and a later notification for provider B was ignored. The cache still returned java.lang.String instead of B's java.lang.Long.

Could metadata-only acquisition and cleanup share the same per-service guard, or could cleanup verify that the registration hasn't changed before removing it?

P2 — Keep reconnect recovery pending when watch repair fails (ProviderRegistryAdapter.cs:328)

After a child watch is consumed, the initial read can fail transiently and the repair's GetChildren can return NoAuth. PermissionDenied correctly stops immediate retries, but it also clears pending watch recovery even though no child watch was installed. After access was restored, the same simulated SyncConnected event triggered one refresh on b9dce71 and none on 31042a7. This verifies the recovery branch with a fake reader, not real ZooKeeper session ordering.

Could we keep the service pending for reconnect recovery when repair fails to install the watch, independently of whether the snapshot is retryable?

Recheck protocol restrictions when a newer discovery supersedes a business
lookup, and refresh metadata even when a notification loses snapshot application.
Serialize metadata lookup startup with unused-subscription cleanup so a stale
interest check cannot delete a newly acquired subscription.

Keep watch recovery pending after unusable reads, including permission failures
on the initial refresh or its repair, without retrying them immediately. Add five
regression cases and align the English and Chinese registry architecture docs.

Validation: 904 tests passed each on .NET 10, .NET 8, and the netstandard2.0
asset under .NET 8. The original four cases failed before the fixes; a fifth
case exposed direct NoAuth recovery. Real ZooKeeper E2E remains unrun because
the Docker daemon socket is unavailable.

Part of apache#42

Signed-off-by: bang <3656828039@qq.com>
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.

3 participants