Repository navigation
fix(android): make unreachable gateway retries battery-safe - #127873
masatohoshino wants to merge 11 commits into
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs real behavior proof before merge. Reviewed September 4, 2026, 6:07 PM ET / 22:07 UTC. ClawSweeper reviewWhat this changesThe PR slows persistent Android Gateway reconnects, wakes all saved sessions after route changes, and adds a lightweight authenticated WebSocket liveness acknowledgement. Regression provenancePossible regression — probable (reproduction; reviewed change). No predecessor PR is attributed. Merge readiness⛔ Blocked before merge - 6 items remain Keep this PR open: it remains the linked fix for the Android reconnect bug, but it introduces a P1 Gateway protocol compatibility regression and still lacks sufficient exact-head physical private-route recovery proof. Priority: P1 Review scores
Verification
How this fits togetherThe Android node maintains WebSocket sessions to a configured Gateway. Network callbacks wake those sessions after route changes, while the Gateway dispatcher confirms whether a ready socket can still carry traffic. flowchart LR
Route[Android route change] --> Monitor[Network monitor]
Monitor --> Runtime[Android session coordinator]
Runtime --> Session[Gateway reconnect session]
Session --> Socket[Ready WebSocket]
Socket --> Ack[Gateway liveness acknowledgement]
Ack --> Outcome[Keep socket or reconnect]
Before merge
Findings
Agent review detailsSecurityNone. PR surfaceSource +37, Tests +993, Docs +16, Other +230. Total +1276 across 18 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Append gateway.ping after the existing advertised-method tail with a regression that preserves every prior index, then attach redacted exact-head physical private-route recovery evidence before merge. Do we have a high-confidence way to reproduce the issue? Yes for the original bug: the source showed a permanent 8-second retry cap and the linked report supplies a physical-device scenario. The exact final-head private-route recovery case is not sufficiently demonstrated in the available evidence. Is this the best way to solve the issue? No, not yet: the Android ownership split is appropriate and the ACK avoids a slow health call, but the method must be appended rather than inserted into a stable ordered discovery surface. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 8918e743cdf8. LabelsLabel justifications:
EvidenceAcceptance criteria:
What I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (21 earlier review cycles; latest 8 shown)
|
|
Accepted — the finding is right, and it was a regression this PR introduced. Repaired in Root cause. Repair. The wake now goes to the operator, the node, and a snapshot of every live secondary session. The selection is a pure function beside Coverage. Scope of the change since your scan (the second commit on this PR). The diff from The 150–300s band is left as proposed, per your recommendation; the body keeps that tradeoff explicit for you to accept. D6 and D7 remain out of scope and unclaimed. |
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
I noticed the latest ClawSweeper verdict is already clean/ready-for-maintainer-review, but the managed PR labels are still showing the prior |
|
I’m treating this as a ClawSweeper status-label reconciliation issue, not a code issue: the latest durable verdict says |
|
@clawsweeper re-run |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
No further contributor code action is pending; this re-run is only to let ClawSweeper reconcile its own managed status/rating labels to the current clean verdict. |
|
Correction to my prior note: the code/review state is already clean; the visibility problem is specifically that ClawSweeper's managed labels did not reconcile to its own latest verdict. I’m not changing code or the 150–300s policy. |
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
I’ll stop adding comments here; the requested re-review is already queued. |
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
`awaitReconnectWake` decided on delivery alone. A receive cancelled by the timeout it is racing can take the element out of the conflated channel and hand it to nobody, so a wake landing at that boundary was read as a plain timeout and the retry ladder kept the long wait it had climbed to. That mattered only once the ceiling grew: at 8 s the lost reset cost 8 s, at 300 s it costs minutes. Count wakes instead of relying on delivery. Every producer bumps the count under the lock that already guards the signal — a network restore, a manual reconnect, a cleared auth pause, and a replaced desired endpoint — and the wait reports a wake when the element arrived or the count moved. The new condition is true wherever the old one was, so no delivered wake changes meaning. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01XNgcUeSczPZ9AEtdJi5Wqc
…y sessions alone ValidatedNetworkState only signalled on the aggregate validated-network set going from empty to non-empty, so a Wi-Fi/LAN route returning while cellular stayed validated produced no wake at all. With the retry ceiling now minutes instead of seconds, that swallowed wake can cost minutes instead of at most 8s. update() now reports each network's own offline->online edge instead of the aggregate state, so a returning route wakes reconnection regardless of what else is already validated; a network already known validated still reports no change, which is what keeps capability churn (signal-strength updates) from re-firing. retryAfterNetworkRestore() also unconditionally closed currentConnection before signalling, and the fleet fan-out calls it on every secondary session on every restore, so a healthy secondary already connected over a different route got disconnected for no benefit. It now returns immediately when the session is already ready; reconnect() (a deliberate manual retry) is unaffected and still forces a fresh connection. Both were review findings on openclaw#127873 against the earlier fan-out; the PR body previously named them as deliberately not taken because reversing the aggregate suppression looked like it crossed into NetworkMonitor's existing detection contract. It does not: the contract that matters (churn on an already-validated network reports no change) is preserved and pinned by NetworkMonitorTest; only the aggregate-vs-per-network granularity changes.
… a repeated-interruption case Three more review findings against the previous commit's two fixes. retryAfterNetworkRestore() read isReady() before acquiring lifecycleLock, then signalReconnect() unconditionally closed currentConnection under that lock. A session could finish its handshake and become ready in the window between the read and the lock, and would still get closed. The readiness check moves inside signalReconnect's lock, at the same point connectOnce's own markReady() transition uses, so the two can no longer interleave that way. reconnect() (manual retry) keeps forcing a fresh connection regardless of readiness. seedActiveValidatedNetwork() seeds only the single active network (the one synchronous read available without the deprecated getAllNetworks()), so on a device that already has a second network validated at registration time, registerNetworkCallback's own replay of that second network's state looked exactly like a fresh restore, firing the reconnect fan-out at every cold start on such a device. A short grace window after registration (500ms, sized to how fast a cached-state replay resolves, not to any real elapsed time) now absorbs a just-validated network's first observation without notifying. Removing the aggregate validated-network check's incidental coalescing (the previous commit's own fix) had a side effect: several networks validating close together (Wi-Fi and cellular both reactivating from doze at once) now each produce their own restore notification, and each one reaches the full fan-out -- so a session's just-started reconnect attempt from the first notification could be closed again by the second, before its handshake finishes. Notifications now debounce within a short window after the first one in a burst; nothing about which network caused the wake is lost, because the fan-out was never per-network to begin with. Two narrower gaps remain, disclosed in the PR body rather than fixed here, because closing either needs Android Network identity threaded through NetworkMonitor/NodeRuntime/GatewaySession -- a new piece of cross-file state this repair-scoped PR's guards do not carry today: a socket that stays app-level READY after its own route already failed (bounded to about one OkHttp ping interval, not indefinite), and the bootstrap-grace window itself absorbing a network that genuinely finishes validating inside it rather than only a registration replay (bounded by each session's own independent backoff retry, the same interval this PR's body already asks acceptance of elsewhere).
…d ones isTransportValidated() only reports NET_CAPABILITY_VALIDATED, a general-internet probe. A saved Gateway on a private LAN or a split-tunnel VPN route can be reachable without that route ever validating, so a restore over such a route produced no wake at all -- the same swallowed-wake pattern the two earlier fixes in this branch already close for routes that do validate, now costing minutes instead of seconds because of the raised ceiling. The callback now also wakes on plain network attach, which Android delivers before validation resolves, gated by the same registration-replay bootstrap grace the validated-network path already uses. A wake that turns out wrong just costs one failed connect attempt, the same cost this branch already accepts for every other wake producer. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Keep healthy ready sockets while retiring silent or one-way broken transports. Correlate replies with requests enqueued after the restore-check baseline, preserving generation ownership, auth pauses and Disconnect. Add real TCP failure controls and healthy/late-reply regressions; keep the passive timer at 30-60 seconds plus connection time.
8e36d6b to
d7d5c4e
Compare
|
@clawsweeper re-review Please review exact head |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
Replace slow health-based liveness checks with advertised same-WebSocket gateway.ping responses while preserving authenticated connection ownership. Retire current sockets when ACK enqueue fails and wake on existing-network link-property changes without changing the 30-60 second steady retry timer. Cover queue overflow, mutable DNS snapshots, authorization and advertisement. Co-authored-by: IWhatsskill <[email protected]>
|
Thanks @masatohoshino for the work on this, including the follow-up fixes and regression tests. We’ve decided to take a different approach to the Android gateway reconnect and battery-drain issue, so we’re closing this PR rather than continuing to expand its scope. Your investigation and test coverage have helped clarify the problem and the trade-offs involved. We appreciate the time and care you put into this contribution. Thank you! |
Keep transient retries fast, then use a finite 30–60s jittered retry timer. Wake the existing ladder on manual or independent LAN/VPN attachment events, without retiring healthy READY sockets or resuming auth-paused sessions. Include desired secondary sessions in the same recovery path. Related: #127872 Prior investigation: #127873 (closed; no prior proof reused). AI-assisted implementation and validation. Worked on by: - @IWhatsskill Co-authored-by: IWhatsskill <[email protected]>
Keep transient retries fast, then use a finite 30–60s jittered retry timer. Wake the existing ladder on manual or independent LAN/VPN attachment events, without retiring healthy READY sockets or resuming auth-paused sessions. Include desired secondary sessions in the same recovery path. Related: #127872 Prior investigation: #127873 (closed; no prior proof reused). AI-assisted implementation and validation. Worked on by: - @IWhatsskill Co-authored-by: IWhatsskill <[email protected]>
Keep transient retries fast, then use a finite 30–60s jittered retry timer. Wake the existing ladder on manual or independent LAN/VPN attachment events, without retiring healthy READY sockets or resuming auth-paused sessions. Include desired secondary sessions in the same recovery path. Related: #127872 Prior investigation: #127873 (closed; no prior proof reused). AI-assisted implementation and validation. Worked on by: - @IWhatsskill Co-authored-by: IWhatsskill <[email protected]>
Keep transient retries fast, then use a finite 30–60s jittered retry timer. Wake the existing ladder on manual or independent LAN/VPN attachment events, without retiring healthy READY sockets or resuming auth-paused sessions. Include desired secondary sessions in the same recovery path. Related: #127872 Prior investigation: #127873 (closed; no prior proof reused). AI-assisted implementation and validation. Worked on by: - @IWhatsskill Co-authored-by: IWhatsskill <[email protected]>
…aw#138732) Keep transient retries fast, then use a finite 30–60s jittered retry timer. Wake the existing ladder on manual or independent LAN/VPN attachment events, without retiring healthy READY sockets or resuming auth-paused sessions. Include desired secondary sessions in the same recovery path. Related: openclaw#127872 Prior investigation: openclaw#127873 (closed; no prior proof reused). AI-assisted implementation and validation. Worked on by: - @IWhatsskill Co-authored-by: IWhatsskill <[email protected]>
Fixes #127872
What Problem This Solves
Fixes an issue where the Android node keeps attempting to reconnect every few seconds, indefinitely, for as long as a saved Gateway stays unreachable, and keeps doing so after the app is dismissed from Android Recents. This sustained background reconnect activity is what was reported as causing severe battery drain; a normal user has no obvious way to stop it and no explanation for it. Severe battery drain is the reported motivation, not a demonstrated outcome: what is measured here is the reconnect workload itself, on a real device, before and after. No battery percentage or mAh improvement is claimed anywhere in this PR.
The production diff keeps retry timing in GatewaySession.runLoop(), ready-socket verification in the connection/pending-RPC owner, live-session fan-out in NodeRuntime, and route observation in NetworkMonitor/GatewayDiscovery. One registered gateway.ping handler supplies a lightweight authenticated transport ACK. The foreground service keeps its existing lifecycle; the remaining changes are tests and protocol documentation.
Why This Change Was Made
The reconnect loop already backed off exponentially, but it stopped growing at 8 seconds and then held that cadence for the whole outage — reaching the cap at attempt 6, after about 11 s of accumulated backoff — nearer a minute of wall clock once each failed attempt's own connect timeout is counted. Persistent failure never reduced the amount of work being done. Android's guidance on background network use warns that frequent recurring network activity can keep the mobile radio active and consume battery quickly, which is the region this loop settles into and stays in.
This PR changes
gatewayReconnectDelayMsand the three wake sites inrunLoop()so the ladder keeps growing to a bounded ceiling instead of flattening, and extends the existing network-restore wake to every live session. The delay is not simply made larger; growth is restored for the region where it had stopped. Before and after, wherenis the count of consecutive failures so far (n = 1for the first retry after a drop, so the old cap first binds atn = 6):uis drawn once per retry fromRandom.nextDouble(), so the interval is half-open at the top; the result is truncated to whole milliseconds. Attempts 1-5 are the same expression as today, the old 8 s cap becomes the floor of the jittered range instead of the ladder ceiling, and oncerawsaturates at 60 s the steady band is 30 s to just under 60 s.transientReconnectDelaysAreUnchangedasserts this against the previous formula for every jitter input. (The measured values are deltas between notification posts, so they carry scheduling and post latency and are not expected to match the computed values digit for digit. What is identical between the two builds is the formula and its constants.)nup to 256 against the previous formula byreconnectDelayIsNeverShorterThanBeforeThisChange. Beyond the tested range the old policy is the constant 8 s and the new one is clamped at or above 8 s, so the inequality cannot turn over. That is a comparison of the two delay policies at the samen, evaluated on the computed values. Wake handling is a different axis: it lowersnitself, so it shortens real-world recovery latency without ever making the delay for a givennshorter than before. The two claims never apply to the same quantity.Design note
The retry policy stays inside
GatewaySession.runLoop(), the live-session fan-out stays withNodeRuntime, and route restoration stays withNetworkMonitor.GatewayDiscoveryandNetworkMonitornow share one request that preserves Android's normal app-visible-network constraints while removing the defaultNET_CAPABILITY_NOT_VPNexclusion. That is the smallest owner-level repair: both consumers that claim to observe VPN/split-DNS routes use the same request.The retry ladder remains in the per-desired-connection
attemptcounter owned byrunLoop(). The monotonic wake count closes the channel-timeout race without adding persisted lifecycle state.NetworkRestoreStateis process-local callback state: it records each network's availability episode soonAvailableand that same network's first capability snapshot coalesce, while an unrelated route can never be suppressed by another network's timestamp. Ready sessions are checked for a fresh round trip without disturbing healthy unrelated-route sessions; non-ready sessions are woken immediately.Why these pieces land together
Raising the ceiling is the fix; the wake resets are what make raising it safe. With an 8 s ceiling a stale ladder cost at most 8 s, so nothing had to reset it. At 60 s the same staleness can become a one-minute silence, so every path that consumes a wake has to restart the ladder or the ceiling introduces a regression: the backoff wait, the auth-pause wait, the drain immediately before a connect attempt, and the network-restore fan-out. These are call sites of one invariant, not separate features: timer-driven work becomes materially less frequent while explicit network and user recovery stays immediate.
Review findings resolved
VPN/private-route matching. Android adds
NET_CAPABILITY_NOT_VPNto a defaultNetworkRequest, so the prior empty builder excluded the split-tunnel/VPN route the callback was meant to observe.appUsableNetworkRequest()now removes that default capability and is shared byNetworkMonitorandGatewayDiscovery.callbackRequestIncludesVpnRoutesasserts the built request contract directly.Cross-route wake isolation. The process-global two-second debounce could discard a different network's only attach event. It has been removed.
NetworkRestoreStatecoalesces onlyonAvailablewith the immediately following capability snapshot for the same network and availability episode.differentNetworkAttachesEachWakeTheFleetproves that two distinct networks both wake the fleet, whileinitialCapabilitiesAfterAvailabilityDoNotWakeTwicepreserves same-network callback-pair coalescing.Healthy-session preservation and stale-READY repair. The connection-owned pending-RPC map correlates a fresh lightweight gateway.ping response on the same socket. The registered handler is advertised by the attached method registry and shared with early authenticated dispatch, behind socket/runtime authority and credential-mutation ordering. This removes health-collection latency and the old sequence-counter wrapper from liveness decisions. Tests cover healthy slow-health traffic, error replies, blackholes, one-way failure, replacement, Disconnect and old-server capability negotiation.
Failed ACK enqueue. Real OkHttp queue overflow can refuse send without immediately notifying onFailure. The probe now retires a still-current READY socket instead of swallowing that failure.
Existing-network link changes. NetworkMonitor now observes onLinkPropertiesChanged, compares owned Parcelable snapshots, coalesces initial/duplicate snapshots, ignores lost-network updates, and detects mutable DNS/route changes without requiring a validation transition.
Non-scope
The change is limited to retry timing, route/fleet wakes, and the advertised same-WebSocket transport ACK; unrelated session behavior is unchanged. Two behaviours in the same loop keep their current semantics:
attemptis still reset wheneverconnectOncereturns normally, so a Gateway that accepts a socket and immediately closes it interacts with the reset exactly as it does today (bounding that needs a dwell clock and would change what "success" means), and the auth-pause branch keeps its existing 250 ms poll, which performs no network work and is not part of the reported drain.User Impact
An unreachable Gateway now settles into infrequent, timer-driven probing instead of retrying every few seconds for the whole outage. (This bounds the retries the loop schedules for itself; wakes driven by the user or by the network are unbounded by design and stay immediate.) Transient retry timing is unchanged and wake handling deliberately changes — a wake now also restarts the ladder, so for any given pending backoff the next attempt is never later than it would have been without the wake. The first retries after a drop are still sub-second-to-second (0.97 s and 1.70 s open the fixed build's outage ladder below, and a later induced outage restarted at 0.60 s), and rejoining the network or tapping reconnect still triggers an attempt immediately rather than waiting out the backoff.
Real behavior proof (progressive-backoff mechanics; intermediate 300 s candidate)
Behavior addressed: an unreachable Gateway is retried on a seconds-scale cadence for the entire outage, including after the app is dismissed from Android Recents. The device evidence below is app-level reconnect cadence; per-attempt policy values are covered by the unit tests.
Real environment tested: physical Xiaomi 2107113SR, Android 14 (SDK 34), attached over USB. Real OpenClaw Gateway on a private LAN, real pairing, real outage induced by turning Wi-Fi off while mobile data stayed on, so the Gateway address stops being routable while the phone is still online. Nothing was mocked or stubbed; both builds come from the same Gradle assemble task with identical applicationId, versionCode and signing certificate, swapped with
adb install -rso the app's pairing survives the swap.Exact steps run for the earlier progressive-backoff candidate: build both APKs with
./gradlew :app:assemblePlayDebugat baseff6db34233dand at candidatecc3460fcbd2e; install the base build, pair it and confirmConnected; turn Wi-Fi off with mobile data on; sample Android notifications and record each app timestamp; repeat after installing the candidate build. These measurements establish the progressive-backoff and wake mechanics, not the final 60 s ceiling.What this capture measures: the app's own reconnect activity as a whole. The foreground-service notification is one merged surface for both gateway sessions the app runs, and the capture does not attribute a transition to a particular session. So the intervals below are the spacing between successive reconnect state changes of the app, not a reconstruction of one loop's timer. That is the right granularity for the reported problem — the concern is how often the app does reconnect work at all — but it means individual intervals should not be read as exact per-session policy values, and indeed one of them (7.975 s) sits just under the 8.0 s the policy computes for that step. The claims below are about the shape of that aggregate activity: 31 consecutive intervals pinned between 7.97 s and 8.06 s before, against a sequence that keeps growing after.
Two different things are established by two different means, and it matters which is which:
retry_delay) and from one attempt post to the next (cadence, which additionally contains the ~10 s connect timeout). Because the surface is merged, these are app-level event intervals — the next post may belong to either session — so they are evidence about the app's reconnect activity, not a reconstruction of one loop's timer.The claim this PR rests on needs both, and each is carried by the right one: the tests show the ladder now grows instead of flattening, and the device shows that this actually changes how often the app reconnects in the failure users hit.
Measurement note: the app re-posts its foreground-service notification on every reconnect state change (
Reconnecting…when an attempt starts,Gateway error: …when it fails) and each post carries the app's own device-sidewhentimestamp. Each session postsReconnecting…when one of its attempts starts andGateway error: …when it fails, from the twoonDisconnectedcalls in the retry loop; the surface the host samples is the merged result for both sessions, which is why the intervals are read as app-level rather than per-loop. All delays below are deltas between those device timestamps, so they do not depend on host sampling. No production instrumentation was added to either build; the proof deliberately reads the notification timestamps the app already posts. Because packets to the unreachable LAN address are dropped rather than refused, each attempt additionally spends a ~10 s socket connect timeout before failing; that constant is identical in both arms.retry_delaybelow is the failure-to-next-attempt interval;cadenceis attempt-to-attempt, i.e.retry_delayplus that timeout.Before evidence:
Evidence after fix:
Reading the tables: each arm's capture begins while the app is still connected, and the induced outage starts at the marker shown in each trace. The BEFORE excerpt is shown from before its marker, so its first row (0.324 s) is that pre-outage churn; the AFTER excerpt is shown from its marker onwards, so every row in it is inside the outage. In both arms the loop was already one failure into its ladder when Wi-Fi went off, so the first interval after the marker is the second step (computed 1.011 s), not the first (0.595 s). Through that region the two arms track the same values — 1.02, 1.76, 2.94, 4.95, 8.06 s before, against 0.97, 1.70, 2.97, 4.95, 7.98 s after — and they diverge at the next step, where the old build repeats 8 s and the new one goes to 12.39 s.
Counts:
retry_delayis measured from a failure to the next attempt, so an attempt that is not preceded by a failure has none. Exactly twoATTEMPTrows in the AFTER capture are immediately preceded by aCONNECTEDrow (17:30:53 and 17:55:35), each the first attempt of a fresh outage after a successful reconnection, which is why 49 attempts yield 47 delays. The BEFORE arm never reconnected, so all 36 of its attempts follow a failure.I am not quoting an attempts-per-minute comparison: the two windows differ in length by design (the AFTER ladder needs several minutes to climb, so a duration-matched window would truncate the behaviour under test), and while preparing this PR I found that the capture's own rate summaries were computed over a window that ended before the recovery tests were appended. The recomputation is written up in the corrections note of the linked artifact. It changes no claim here: the cadence claims rest on the per-interval delays, which are unaffected. The Recents and network-restore claims rest instead on recorded app-process state, Recents contents and event ordering, which the artifact keeps separately.
Observed result on the earlier 300 s candidate: the early transient ladder is unchanged, but at the attempt where the old build flattened to 7.97 s the candidate went to 12.39 s and kept climbing to 225.52 s. Over the whole BEFORE window no delay exceeded 8.056 s; in AFTER, 24 of 47 delays exceeded 9 s. Dismissal from Android Recents did not restore seconds-scale retry. This is historical progressive-backoff evidence, not final-head timing evidence.
After dismissal from Android Recents (the swipe is bracketed by Recents holding 10 entries at 17:54:24 and 0 at 17:54:50, process unchanged):
Recovery, on the same device:
What is not yet tested on a physical device: final head
d7d5c4e0ec166e1c0d776cc1217dfd073212f9cawith the 60 s ceiling and VPN/private-LAN restore path. The absolute policy bound is covered bysteadyReconnectTimerIsThirtyToSixtySecondsBeforeConnectionTime, which failed against the intermediate 300 s candidate (expected:<30000> but was:<150000>, that being its jitter-floor value, not main's 8 s ceiling) and passes after it;reconnectDelayStaysBoundedSoAnEndpointOnlyRestartIsStillFoundkeeps probing finite across 1024 attempts. Earlier hardware campaigns establish that endpoint-only Gateway restarts are rediscovered under progressive backoff, but they used the intermediate 300 s candidate and are not claimed as final-head timing proof. No battery benchmark was run.Proof limitations or environment constraints: the physical-device campaigns below establish the before/after retry workload and endpoint-only recovery mechanics, but they predate final head
d7d5c4e0ec166e1c0d776cc1217dfd073212f9caand used the intermediate 300 s policy. The final 30-60 s policy is pinned by a failing/passing absolute-bound regression and by both Android flavor suites in AWS Crabbox. No final-head physical VPN/private-LAN campaign, battery percentage, mAh improvement, or battery benchmark is claimed.Evidence
Current ACK candidate — September 4, 2026
Published head: 38acb9e. Reviewed/tested tree: 7146a0c416a38f88a7f55b367d9809c4a721002c. Original commits and hardware evidence are preserved; the new commit includes IWhatsskill's coauthor trailer.
The focused pair failed 2/2 before and passed 2/2 after. Final software validation: 120 Play + 120 ThirdParty tests (zero failures/errors/skips), all four Android modules' ktlintCheck, 111 Gateway tests across 10 files, all changed gates, and full pnpm build (4m 8.8s): exit 0. An earlier build topology-fence failure and an execution-context-loss interruption were diagnosed; neither is counted as a pass.
Toolchain: Gradle 9.7.1 and JDK 21. From apps/android:
From the repository root:
Native Codex: fresh full-PR local review against 0f429ce, scoped-clean through P2. Independent maintainer review: no remaining source-backed correctness finding; the bounded owner-level fix is appropriate, but this is not overall merge readiness. Full PR production +324/-57 (net +267), tests/test support +1013/-20, docs +16; growth implements retry/fleet/route ownership and an authenticated ACK, while removing the sequence-counter wrapper.
Exact-head CI: being watched; no green result claimed yet. ClawSweeper: the prior d7d5c4e review requires physical proof; a new-head verdict is not yet verified.
Unwaived proof gap: exact-final-head physical Android private-LAN/VPN restoration through NetworkMonitor → NodeRuntime → GatewaySession, automatic recovery without manual reconnect, build identity and elapsed time. Local ADB exposed no physical device. Earlier real-Gateway/Robolectric ACK timing retained the same socket beyond 9.5 s under 600 ms each-way delay, but predates the final two Android fixes and is not physical-device proof. No battery benchmark or improvement is claimed. Older sections below are historical evidence, not final-head proof.
Earlier d7d5c4e maintainer verification (superseded)
Candidate head:
d7d5c4e0ec166e1c0d776cc1217dfd073212f9ca, rebased onto0f429cef53d8d1dfbe5358b962f56c70c6db8153. The main branch already contains the central npm advisory/CI repairs; this PR does not add a security-audit bypass.Repair owner: GatewaySession's pending-RPC and connection lifecycle. A coalesced check accepts a response only when its matching request was enqueued after the restore baseline. That baseline and enqueue use the same write mutex. Replies settle the existing waiter and record their sequence at the response owner. Fully silent and one-way-broken flows are retired without invalidating a later connection or overriding an auth pause/Disconnect.
8e36d6b0496503c606a018199154c7b8e12b44f7plus the regression: the ordinary RPC timed out after 15,011 ms and the old lease was still current; a fresh TCP flow through the same listener succeeded.These are host-JVM/Robolectric tests using the production GatewaySession with real OkHttp WebSockets and a real loopback TCP forwarding proxy. Fault injection drops application bytes without EOF/reset, while new connections remain usable. This is deterministic transport-boundary proof, not a physical Android radio, private-LAN/VPN campaign, UI recording, or battery benchmark.
Executed pre-rebase validation: 117 tests per flavor (234 total), zero errors/failures/skips; app KtLint and the repository changed gate including all four Android KtLint modules passed. A fresh independent P0-P2 Codex review of the final repair reported no actionable findings. All four repair/test file hashes and the relevant unchanged callers/contracts were rechecked across the rebase.
Final-head local validation: Completed on d7d5c4e: 117 Play + 117 Third-Party tests, zero failures/errors/skips, followed by the complete changed gate over all eight PR paths including all Android KtLint modules. The worktree is clean; repaired source/test hashes match the independently reviewed candidate.
Reproduction commands from repository root (with the installed Android SDK selected normally):
Exact-head GitHub CI: run 33878942077, attempt 1 completed successfully on
d7d5c4e0ec166e1c0d776cc1217dfd073212f9ca.security-fast, all six Android lanes, andopenclaw/ci-gateare green. The npm bulk audit returned no matching high-or-higher production advisories; this is not comprehensive vulnerability clearance.Exact-head ClawSweeper status (reviewed September 4, 2026, 13:55 UTC): no actionable code or security findings, but still
needs-human/ blocked. Remaining gates are a redacted final-head real Android private-LAN/VPN restoration trace and explicit maintainer acceptance of the 30–60 s passive retry timer plus connection time. Neither gate is marked resolved here; no merge or formal review-status change has been made.Remaining real-device boundary: the gate named above stays open. What is new is a final-head emulator callback-boundary run, in the section below, which states its own limits there. The earlier physical campaigns further below used the intermediate 300 s policy and are not final-head measurements.
Production/test delta against the rebased main: production +259/-46 (net +213); tests/test support +745/-20 (net +725), across eight files. The new repair itself is production +65/-22 (net +43): the added state records a previously missing connection-owned, request-correlated liveness fact. It replaces the rejected inbound-traffic heuristic rather than layering both policies.
Earlier regression evidence retained as historical only: VPN matching/cross-route wake controls were red in AWS run
run_787f8457d0e8and green inrun_90d71d93ae8f; the one-minute policy was verified inrun_6e43f376aa60on an earlier head; startup suppression was red inrun_d7ad9197a7a6and green inrun_27cdafa16f4e. Their results are not relabeled as tests of this final SHA. The duplicate startup callback test was consolidated into the equivalent retained plain-attach boundary test.Tests
Tests, by file, at this head:
apps/android/app/src/test/java/ai/openclaw/app/gateway/GatewaySessionReconnectTest.kt— theretry-delay policy and the wake semantics: transient delays identical to the previous formula,
continued growth past the old ceiling, the steady band's absolute bounds, that no attempt retries
sooner than before, that probing stays bounded so an endpoint-only restart is still found, and
that a network restore, a manual reconnect and a cleared auth pause each interrupt a pending
backoff and resume in the fast band.
apps/android/app/src/test/java/ai/openclaw/app/gateway/NetworkMonitorTest.kt— the routecallback boundary: an attach edge is a restore on its own, a network's attach and its first
capability snapshot coalesce into one wake, two different networks each wake the fleet, and the
registered request no longer excludes VPN routes.
apps/android/app/src/test/java/ai/openclaw/app/GatewayFleetSelectionTest.kt— thenetwork-restore fan-out: operator, node and every live secondary are woken; a single secondary;
no secondaries at all; and a fleet cleared after the call, to show the wake acted on a snapshot.
Both Android flavours pass at this head (117 Play + 117 Third-Party on the focused selection above,
zero failures, errors or skips), with the changed gate and all four Android KtLint modules green.
The absolute policy bound is pinned by
steadyReconnectTimerIsThirtyToSixtySecondsBeforeConnectionTime, which fails when the ceiling moves(it failed against the intermediate 300 s candidate with
expected:<30000> but was:<150000>).Earlier d7d5c4e emulator evidence (not current physical-device proof)
This is a partial answer to the request on this PR for a run on exact head
d7d5c4e0ec166e1c0d776cc1217dfd073212f9cashowing a saved Gateway recovering, without a manualReconnect, when a route that never validates comes back.
What it is and is not, plainly. It is an Android emulator running the real app against a real
Gateway, so it is a live behavioural run rather than a host-JVM test. It is not a physical
handset, it carries no radio evidence, and the network it uses is an ordinary non-VPN one —
dumpsysreportsNOT_VPNthroughout — that was made unable to validate. What it reproduces is the"attaches but never validates" property a private LAN shares, not a VPN transport and not the
removal of the default
NOT_VPNrequest filter. The physical private-LAN/VPN gate therefore staysopen. What the run provides is controlled evidence consistent with the
attribution — which build shows an early, route-associated attempt and which does not.
Environment: headless emulator,
aosp_atdAPI 31 (Android 12),pixel_6profile, x86_64,software-rendered. Its only network is
eth0/10.0.2.15, reported asMOBILE, whose default routereaches the host at
10.0.2.2. A real OpenClaw Gateway built from this same head runs on the host,loopback-bound on its own port under its own profile with token auth; the app is really paired to it
(
devices approveandnodes approvewere run) and reachedConnectedbefore each run. The outageis that Gateway process being stopped. No instrumentation was added to either build — the observable
is the app's own foreground-service notification and its device-side
whentimestamp, sampled every250 ms.
Induced condition, stated plainly. The emulator's route validates normally because the host has
internet. To reproduce a private-LAN/split-tunnel capability state, Android's captive-portal probe
URLs were pointed at an unreachable address, so validation cannot succeed. The route then attaches
and carries traffic while never gaining
NET_CAPABILITY_VALIDATED, confirmed indumpsys connectivityat each step:Two builds, both from the same
:app:assemblePlayDebugon this head, installed into the same appslot with
adb install -rso the pairing survives the swap. A is this head unmodified; B is thishead with exactly this block deleted from
NetworkMonitor'sConnectivityManager.NetworkCallback,and nothing else changed:
APK sha256:
NetworkMonitorhas exactly two calls tonotifyNetworkAvailable(), one in each callback, so with that block gone B's only remaining wakepath in this class is the validated edge in
onCapabilitiesChanged— which this route neverproduces. That is a source-level property of the build, not something the trace shows.
Exact steps or command run after this patch: build both APKs from the repository root with
apps/android/gradlew -p apps/android :app:assemblePlayDebugon this head, deleting only theonAvailableoverride for B;adb install -reach into the same slot; stop the Gateway; wait for the retry ladder to reach itssteady band; restart the Gateway (which produces no Android network event); then
adb shell svc data disable, wait,adb shell svc data enable; sampleadb shell dumpsys notificationevery 250 ms and record each change with the app's ownwhentimestamp, and read
dumpsys connectivityat each step. Restarting the Gateway before touching theroute is what makes the timer excludable: an attempt that lands before the timer floor cannot be the
timer.
Observed result after fix: the callbacks themselves are not logged, so what follows is behavioural
evidence, not a direct observation of a callback firing.
One limit has to be stated before the numbers are read. This notification surface merges the
operator and node sessions, exactly as the earlier sections of this body say, so no row in the
stream can be attributed to a particular loop. The
-3.76 sfigure therefore excludes the timer ofthe session whose failure is the row above it; it only excludes the timer outright if that attempt
and that failure belong to the same session, which this capture cannot show. One observation points that way
without settling it: no attempt of any kind appears anywhere in the 26.24 s between them. A second
laddering session whose last failure was the earlier 14:42:55.253 row would have been due between
14:43:25.253 and 14:43:55.253, which overlaps that silence by only its final 13.40 s — so this is
partial support, not an argument that closes the question. It also assumes every attempt produces an
observable re-post, which this capture does not itself verify.
What does not depend on any of that is the contrast. Both runs share the same merged surface and
the same ambiguity. In A an attempt-start row appeared 5.80 s after the route-up command and
before the floor implied by the preceding row; in B, differing only by the quoted block, no
reconnect row of any kind appeared until 20.67 s past that floor. That difference is what the controlled comparison buys, and it is the claim
this section rests on. It supports the
onAvailableroute wake being what produced A's earlyattempt; with one run per build it does not exclude a wake path shared by both builds happening to
fire in A and not in B. The Gateway had been
listening for 15.40 s by then as a raw cross-clock subtraction, about 16.02 s once the measured
offset is applied. That interval is not endpoint-only evidence: it contains the deliberate route
cycle. The endpoint-only part of it is the 4.00 s between the Gateway starting to listen at
14:43:52.690 and the route going down at 14:43:56.692, during which no attempt appeared — too short
to say much on its own, and stated here only so the window is not read as more than it is. The route comes back unvalidated, an attempt follows, and
a merged
Connectedrow follows 6.14 s after that attempt on thedevice clock, 11.93 s after the route-up command. Because the surface merges the two sessions, that
row is an app-level status rather than a named session's recovery, and the capture does not tie it
to the attempt above it beyond their order.
In B, with only that override removed, the same route return produces nothing early. Its first reconnect-status
notification —
Connected (operator: Reconnecting…), not a standalone attempt-start row, which themerged surface does not give here — comes 50.67 s after the previous failure row. That interval is
the gap to the first visible reconnect status, not a measured retry delay: the row is a status, not
an attempt start, and the failure it is measured from may belong to a different session. It is
consistent with timer-driven recovery, and it sits past the 30 s floor implied by that preceding
row rather than provably past B's own. What the trace does establish is an absence: after the
14:51:58.974 failure row, no reconnect row of any kind appeared in B until 14:52:49.642 — nothing
showed up early after the route returned the way it did in A. (B's stream does contain earlier
Reconnecting…rows from before that failure; the claim is scoped to the window after it.) B's stream does reach a mergedConnectedrow either way, which is what the bounded ceiling is for; what it does not show is anything early
after the route returned, the way A's does.
The "route up" row is the host clock when
svc data enablewas issued, not a callback timestamp,so the 5.80 s in A would include the emulator re-attaching the interface, whatever callback delivery
occurred, and the loop starting a connect — it is not a measure of wake latency alone. The same marker definition and the same
procedure were used for both runs, but the two "vs route-up command" figures are not comparable
wake latencies: A's interval ends with an attempt-start row before the floor implied by the
preceding row, B's with a reconnect-status row after that floor, and each also carries its own interface re-attach time and cross-clock
offset. Do not read +5.80 s against
+28.05 s as one being a faster wake than the other. The evidence in this table is narrower and
harder: A's first reconnect row lands before the floor implied by the failure row above it,
and B's lands after the floor implied by its own preceding row. Because the surface is merged,
those are floors implied by the stream, not verified floors of a named session. In A that row is an attempt start (
Reconnecting…); in B the merged surface gives acombined
Connected (operator: Reconnecting…)row instead, so B's marker is the first reconnectstatus of any kind rather than a separately visible attempt start. Every delta above is computed from the millisecond timestamps shown and rounded to two
decimals.
Two clocks appear in that table, and it matters which claim rests on which. The
Gateway listening,route downandroute uprows are host-clock markers written when the command was issued; thelast failure,first attemptandConnectedrows are the app's own device-sidewhenvalues.Measured at capture time by comparing
date +%s%3Non both sides, the device clock ran about 620 msbehind the host, with roughly ±250 ms of uncertainty from the adb round trip, so the rows that cross
the two clocks — everything labelled "vs route-up command" — carry that much slack. The attribution
claim does not.
last failure,floor implied by that rowand the first reconnect row are alldevice-clock values, so A's 3.76 s margin before that floor is a within-clock comparison and no
offset can move it.
The two builds differ only by that override, which is what makes this a controlled comparison. It is
one run per build, with independently drawn jitter, so this is attribution from a controlled
difference rather than from a distribution.
Raw capture, run A (this head, unmodified) — every recorded notification change:
Raw capture, run B (control) — same:
These two blocks are the complete captures, not excerpts; the host-clock markers and the
dumpsys connectivityreads quoted above are retained alongside them.What was not tested: it is an emulator, not a physical handset, and carries no radio evidence; it reproduces the unvalidated-attach edge that the VPN case shares, not a VPN transport;
one run per build; and the fan-out to secondary sessions is still covered by tests rather than by a
device run, because this emulator had one saved Gateway — two sessions, operator and node, but no
secondary Gateway for the fan-out to reach.
Earlier physical-device campaign (intermediate 300 s policy)
An earlier candidate was measured on a physical handset against a live Gateway, with both builds made from that campaign base and candidate head. The campaign proves progressive backoff and endpoint-only rediscovery; it predates the final one-minute policy.
Real environment tested: a physical Xiaomi Redmi Note 11 (
2201117TL), Android 13(SDK 33), attached over USB to a separate machine that drives it. A real OpenClaw
Gateway on the LAN, in its own state directory on its own port; real pairing, a real
node session. The outage is that Gateway process being stopped and started again, so
the device is retrying an endpoint that genuinely is not answering and the recovery is
a real reconnect. Nothing is mocked or stubbed, and no instrumentation was added to
either build.
Both APKs are
./gradlew :app:assemblePlayDebugbuilds from the same toolchain withthe same pinned build stamps, installed by
adb install -rinto a single app slot —so package id, uid, data directory and node identity cannot differ between the two
groups:
Comparing the two archives entry by entry (name, uncompressed size, CRC): both hold
1,238 entries, 1,235 of them identical, and the three that differ are
classes5.dex,classes6.dexandclasses10.dex, 3,196 bytes of uncompressed content in total.gatewayReconnectDelayMs,awaitReconnectWake,reconnectWakeObserved,GATEWAY_RECONNECT_MAX_DELAY_MSandgatewaySessionsToWakeOnNetworkRestoreare in the AFTER dex and in no BEFORE dex, and each APK carries its own build commit, so areader can tell the two apart from the artifacts alone.
The Gateway runs the same revision as this PR's base, so the server side of the
experiment and the BEFORE build are one commit, not two.
What is measured: the interval from the restarted Gateway reporting itself ready to the
device's node session reappearing on it — read from the Gateway's own account of its
nodes, not from the app under test, and counted only for a session that started after
the one the repetition began with, so a stale reading cannot pass as an instant
recovery. Three repetitions per build per outage length, alternating between the builds
so session drift lands on both, medians compared. The measurement has a floor: a device
that reconnects before the readiness probe observes the Gateway as ready is recorded as
zero rather than as a negative interval. No repetition here hit that floor — every one
of the twelve has its reconnect after its readiness observation — but it is the reason
the BEFORE values are worth reading as real waits rather than as a clamp.
Two outage lengths were run, because the length of the outage is what decides whether
the changed region of the ladder is reached at all:
These historical comparisons describe the intermediate 300 s candidate. They remain evidence that progressive backoff reduces retry frequency and that endpoint-only restarts are rediscovered, but they are not evidence for the final 60 s ceiling.
This is the cost side of the trade, and it is the worst case for it: the Gateway here
comes back with no network change and no user action, the one path that has nothing but
the timer to find it. The recovery paths a user actually exercises keep firing
immediately and were measured separately in the capture under "Real behavior proof" — a
manual reconnect produced an attempt 0.51 s after the operator's tap rather than waiting
out the pending timer. Its timing afterwards does change, in the user's favour: the wake
resets the ladder, so the retries that follow one are back in the fast band (1.062 s and
1.034 s in that capture) rather than resuming the long wait the loop had climbed to. The benefit side, how often the device does reconnect work during the
outage, is what that capture measures.
Provenance of the tables above
The tables under "Real behavior proof" were captured on a build pair pinned to base
ff6db34233d(BEFORE) and headcc3460fcbd2e(AFTER). This branch has since beenrebased onto
28164d09349, and the reconnect behaviour was re-measured there, on adifferent physical handset, against a live Gateway — that is the campaign above. The
older tables are kept because they are the finer-grained record: per-attempt intervals
across a 42-minute outage, which the newer run does not reproduce.
Nothing the older capture measured moved between those two bases, and that is
checkable rather than asserted. In
git diff ff6db34233d 28164d09349 -- apps/android/app/src/main/java/ai/openclaw/app/gateway/GatewaySession.kt:runLoop()or the connect path it drives — the region fromprivate suspend fun runLoop()through the opening half ofconnectOnce()isbyte-identical across the two bases;
connect()toreadyConnection(), which holdsdisconnect(),reconnect(),retryAfterNetworkRestore(),signalReconnect()anddrainReconnectSignals()—every producer and consumer of
reconnectSignal. That block is byte-identical too.NodeForegroundService.kthas no commit inthat range and
gatewayConnectionStatusForDisplay()inNodeRuntime.ktisbyte-identical, so the two notification writes that capture times are still the
same two writes.
What upstream did change in that file over the range is the canvas surface URL
resolver, an event sequence-gap check and a TLS fingerprint helper. The reconnect
loop calls none of them.
The following source-equivalence discussion applies only to the earlier 300 s campaign candidates, not the current 60 s policy or round-trip repair. For that historical comparison, the patch was unchanged by the rebase:
gatewayReconnectDelayMs,drainReconnectSignalsand the threerunLoopcall sites are byte-identical between themeasured head
cc3460fcbd2eand this head.awaitReconnectWakeis the one piece that is not:it now also compares a wake count across the wait, so that a wake taken out of the channel by
the receive its own timeout cancels is still seen. That cannot move anything the older tables
measured, and the reason is structural rather than empirical — the new condition is
delivered || the count moved, which is true wherever the old conditiondeliveredwas true.It only adds a second way for a wake to be noticed; it can never make a delivered one
unnoticed. Every wake that capture does establish was delivered normally, which is visible in it:
the manual reconnect produced an attempt 0.51 s after the tap, followed by a fast-band
retry. The later
commit adds the network-restore fan-out described in "Why these pieces land
together"; it touches
NodeRuntime.ktonly, so the retry algorithm thosemeasurements exercise is unchanged by it. The fan-out itself is covered by the fleet
tests, not by a device run: a two-gateway physical scenario was not performed.
Full sanitized capture: the interval tables quoted above, the raw notification stream they are derived from, the recovery observations, a per-claim mapping giving each claim its result and the timestamp that shows it, the environment and limitations, and a corrections note for the summary aggregates.
https://gist.github.com/masatohoshino/97b35625a41c4610e323278519b14935
Historical campaign test inventory (not final-head test totals):
GatewaySessionReconnectTest— the earlier campaign grew from 30 to 42 tests; the earlier d7d5c4e validation included 54 reconnect tests per flavor.GatewayFleetSelectionTest— 4 to 8, covering the network-restore fan-out: one asserts operator, node and three secondaries are all woken; one covers a single secondary; one covers no secondaries at all, so the primary pair is still woken; and one clears the fleet after the call to show the wake acted on a snapshot. Supplemental (not the proof)::app:testPlayDebugUnitTest(2424 tests) and:app:testThirdPartyDebugUnitTest(2555 tests) pass,:app:ktlintCheckand:app:lintPlayDebugclean. The new tests cover the delay policy — transient delays identical to the previous formula, continued growth past the old ceiling, the sustained band, exact jitter bounds, that no attempt retries sooner than before, that probing stays bounded so an endpoint-only restart is still found, and that a network restore, a manual reconnect and a cleared auth pause each interrupt a pending backoff and resume in the fast band. Five negative controls were run against the retry policy, one per behaviour it introduces: removing the wake reset fails the network-restore and manual-reconnect tests (next retry waited 8013ms), restoring the 8 s ceiling fails the sustained-band tests (attempt 13 jitter 0.0 still probes every 8000ms), removing the auth-pause reset fails its own test (next retry waited 8025ms), dropping the wake-count term from the wait's decision failsaWakeTheChannelNeverDeliveredStillCountsAsAWake, and leaving the endpoint-replacement producer out of the count failseveryWakeProducerAdvancesTheWakeCount(replacing the desired endpoint did not advance the wake count). Each control was produced by reverting that one line in the working tree and running the same Gradle test task; the quoted strings are the resulting assertion messages. The fan-out has its own control: dropping the secondary fleet from the selection helper fails three of its four tests (expected:<5> but was:<2>). Passing an empty fleet at the call site does not fail anything, becauseNodeRuntimecannot be constructed in a unit test, so the call site is asserted by reading rather than by a test. The remaining tests were not individually mutation-checked.Verification boundary
The reported user impact is severe battery drain. This PR claims no measured percentage, mAh or battery-life improvement; no battery benchmark or usage attribution was used as evidence. It verifies the causal workload — sustained frequent reconnect attempts against a genuinely unreachable Gateway — and that it becomes low-duty while prompt recovery is preserved.
Worked on by:
Team session: https://team.openclaw.ai/chat/roboclaw/dashboard/75783fbd-fc4d-4efb-b241-e3ab44545dd7