Skip to content

fix(android): make unreachable gateway retries battery-safe - #127873

Closed
masatohoshino wants to merge 11 commits into
openclaw:mainfrom
masatohoshino:fix/android-gateway-reconnect-battery-backoff
Closed

masatohoshino wants to merge 11 commits into
openclaw:mainfrom
masatohoshino:fix/android-gateway-reconnect-battery-backoff

Conversation

@masatohoshino

@masatohoshino masatohoshino commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

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 gatewayReconnectDelayMs and the three wake sites in runLoop() 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, where n is the count of consecutive failures so far (n = 1 for the first retry after a drop, so the old cap first binds at n = 6):

before:  delay = min(8_000, 350 * 1.7^n)
after:   raw   = min(60_000, 350 * 1.7^n)
         delay = raw                                    if raw <= 8_000     # n <= 5, unchanged
                 max(raw/2 + raw/2 * u, 8_000)            otherwise, u ~ uniform [0,1)

u is drawn once per retry from Random.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 once raw saturates at 60 s the steady band is 30 s to just under 60 s.

  • Transient failures use the same formula as before. Base delay (350 ms) and growth factor (1.7) are unchanged, and the spread below applies only above the old cap, so attempts 1–5 compute exactly the values they compute today. transientReconnectDelaysAreUnchanged asserts 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.)
  • Prolonged failure keeps backing off instead of flattening, up to a one-minute ceiling.
  • Sustained probing is spread across the top of its window: the jittered value runs from half the window up to just under it, and is then clamped up to the old 8 s cap, so between 8 s and 16 s of raw delay the effective band is 8 s to just under the raw value, and from 16 s upward it is the window's upper half. This is two terms in the same delay expression rather than a separable mechanism, and it exists because of the ceiling: once every client converges on the same maximum, a Gateway that restarts is met by all of them at the same instant. It applies only above the old cap, so it cannot affect transient recovery.
  • The ceiling is one minute. Android guidance on regular updates warns that frequent recurring network activity keeps the mobile radio active; it does not define a numeric limit, and none is claimed here. The final steady retry band is 30-60 s: 3.75-7.5x wider than the previous fixed 8 s delay, with a 45 s mean timer delay (5.6x wider), while an endpoint-only Gateway restart is discovered within at most one steady interval plus the connection attempt itself. Network and manual wakes remain immediate and reset the ladder.
  • No attempt number retries sooner than it used to. This holds by construction — the jittered value is clamped up to the old cap — and is asserted for every n up to 256 against the previous formula by reconnectDelayIsNeverShorterThanBeforeThisChange. 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 same n, evaluated on the computed values. Wake handling is a different axis: it lowers n itself, so it shortens real-world recovery latency without ever making the delay for a given n shorter than before. The two claims never apply to the same quantity.
  • Event-driven recovery preserves healthy sockets and restarts failed ones. Network/manual wakes interrupt non-ready sessions and reset the retry ladder. Ready sessions use one coalesced gateway.ping request only when the same authenticated WebSocket advertises it. Only that request ID's response on that socket proves the round trip; events and old replies do not. Failed enqueue or an unanswered 8 s check retires only the still-current, desired, ready connection, preserving Disconnect and auth pauses. Older Gateways keep existing transport/ping detection, never a slow health fallback. The 30–60 s timer plus connection/scheduling time is not an end-to-end recovery SLA.
  • Probing is bounded, not stopped. Android reports no network change when only the Gateway process restarts, so a design that waits for a network callback would never recover. That the delay stays finite and capped is a unit-test invariant; that a real restart is then discovered is measured under "Evidence" — twelve Gateway process restarts across the two campaigns, twelve reconnections, no network event involved.

Design note

The retry policy stays inside GatewaySession.runLoop(), the live-session fan-out stays with NodeRuntime, and route restoration stays with NetworkMonitor. GatewayDiscovery and NetworkMonitor now share one request that preserves Android's normal app-visible-network constraints while removing the default NET_CAPABILITY_NOT_VPN exclusion. 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 attempt counter owned by runLoop(). The monotonic wake count closes the channel-timeout race without adding persisted lifecycle state. NetworkRestoreState is process-local callback state: it records each network's availability episode so onAvailable and 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_VPN to a default NetworkRequest, 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 by NetworkMonitor and GatewayDiscovery. callbackRequestIncludesVpnRoutes asserts 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. NetworkRestoreState coalesces only onAvailable with the immediately following capability snapshot for the same network and availability episode. differentNetworkAttachesEachWakeTheFleet proves that two distinct networks both wake the fleet, while initialCapabilitiesAfterAvailabilityDoNotWakeTwice preserves 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: attempt is still reset whenever connectOnce returns 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.

Behaviour (measured values are aggregate notification intervals, not computed delays) Before After
initial retry 0.32 s, 1.02 s, 1.76 s … 0.97 s, 1.70 s, 2.97 s … (same formula)
persistent retry delay flattens at ~8 s indefinitely keeps increasing beyond 8 s
long-failure steady band flattens at ~8 s indefinitely final policy is 30 to just under 60 s; the earlier 300 s candidate capture reached 115.52 s, 174.85 s, and 225.52 s
after dismissal from Recents ~8 s retry continues progressive backoff survives dismissal; the earlier 300 s candidate capture reached 87.06 s then 117.14 s
network restore reaches the operator and node sessions now observes app-visible VPN/private routes, preserves distinct route wakes, and reaches every live secondary session; final-head boundary proof is under Evidence
manual reconnect existing behaviour 0.51 s from tap to attempt
wake ladder reset n/a — old ceiling was 8 s next delays 1.062 s / 1.034 s
success reset fast ladder 0.60 s, 0.99 s, 1.75 s after the next outage

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 -r so the app's pairing survives the swap.

Exact steps run for the earlier progressive-backoff candidate: build both APKs with ./gradlew :app:assemblePlayDebug at base ff6db34233d and at candidate cc3460fcbd2e; install the base build, pair it and confirm Connected; 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:

  • What the device shows is how often the app does reconnect work: the gap from one failure post to the next attempt post (the captures label this column 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.
  • What the policy does per attempt — the exact ladder, the floor, the ceiling, the jitter bounds — is established by the unit tests against the computed values, which is where per-attempt precision belongs.

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-side when timestamp. Each session posts Reconnecting… when one of its attempts starts and Gateway error: … when it fails, from the two onDisconnected calls 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_delay below is the failure-to-next-attempt interval; cadence is attempt-to-attempt, i.e. retry_delay plus that timeout.

Before evidence:

# BEFORE — base ff6db34233dfa1540dcf18cadf5ba6d34727936c
# observed timing (notification-post deltas), not the policy's computed values
host_wall                device_when    kind      retry_delay   cadence  state
2026-08-22T17:04:34.625  17:04:34.554   ATTEMPT         0.324            Reconnecting…   <- pre-outage churn
2026-08-22T17:04:38.444                 MARKER                           >>> WIFI_OFF
2026-08-22T17:04:45.843  17:04:45.607   ATTEMPT         1.016    11.053  Reconnecting…   <- outage ladder starts
2026-08-22T17:04:57.641  17:04:57.394   ATTEMPT         1.757    11.787  Reconnecting…
2026-08-22T17:05:10.322  17:05:10.305   ATTEMPT         2.936    12.911  Reconnecting…
2026-08-22T17:05:25.482  17:05:25.317   ATTEMPT         4.948    15.012  Reconnecting…
2026-08-22T17:05:43.556  17:05:43.419   ATTEMPT         8.056    18.102  Reconnecting…
2026-08-22T17:06:01.396  17:06:01.420   ATTEMPT         7.973    18.001  Reconnecting…
...  31 consecutive intervals, every one between 7.97s and 8.06s  ...

retry_delay (FAIL -> next ATTEMPT)  (n=36)
  min 0.324s   max 8.056s   last 8.024s
  > 9s: 0    >= 150s: 0

# after the app was dismissed from Android Recents (verified absent; pid 22121 alive)
2026-08-22T17:12:28.795  17:12:28.763   ATTEMPT         8.024    18.059  Reconnecting…
2026-08-22T17:12:47.028  17:12:46.832   ATTEMPT         8.022    18.069  Reconnecting…
2026-08-22T17:13:04.962  17:13:04.889   ATTEMPT         8.018    18.057  Reconnecting…
2026-08-22T17:13:23.235  17:13:22.951   ATTEMPT         8.026    18.062  Reconnecting…

Evidence after fix:

# AFTER — head cc3460fcbd2e9cfc4b4f43f3787691f97271332b, same phone, same Gateway, same failure mode
# observed timing (notification-post deltas), not the policy's computed values
host_wall                device_when    kind      retry_delay   cadence  state
2026-08-22T17:17:21.075                 MARKER                           >>> WIFI_OFF_AFTER
2026-08-22T17:17:35.176  17:17:34.960   ATTEMPT         0.969    14.750  Reconnecting…   <- outage ladder starts
2026-08-22T17:17:46.800  17:17:46.755   ATTEMPT         1.698    11.795  Reconnecting…
2026-08-22T17:17:59.904  17:17:59.750   ATTEMPT         2.965    12.995  Reconnecting…
2026-08-22T17:18:15.001  17:18:14.721   ATTEMPT         4.946    14.971  Reconnecting…
2026-08-22T17:18:33.047  17:18:32.765   ATTEMPT         7.975    18.044  Reconnecting…   <- BEFORE flattened here
2026-08-22T17:18:55.229  17:18:55.196   ATTEMPT        12.388    22.431  Reconnecting…   <- AFTER keeps growing
2026-08-22T17:19:24.760  17:19:24.581   ATTEMPT        19.360    29.385  Reconnecting…
2026-08-22T17:20:00.698  17:20:00.439   ATTEMPT        25.794    35.858  Reconnecting…
2026-08-22T17:20:55.171  17:20:55.204   ATTEMPT        44.780    54.765  Reconnecting…
2026-08-22T17:23:00.880  17:23:00.753   ATTEMPT       115.516   125.549  Reconnecting…
2026-08-22T17:26:05.588  17:26:05.643   ATTEMPT       174.851   184.890  Reconnecting…
2026-08-22T17:34:49.207  ...            ATTEMPT       225.517   235.556  Reconnecting…

retry_delay (FAIL -> next ATTEMPT)  (n=47)
  min 0.504s   max 225.517s
  > 9s: 24    >= 150s: 2

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_delay is measured from a failure to the next attempt, so an attempt that is not preceded by a failure has none. Exactly two ATTEMPT rows in the AFTER capture are immediately preceded by a CONNECTED row (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):

2026-08-22T17:57:12.227  17:57:12.151   ATTEMPT        87.063    97.111  Reconnecting…
2026-08-22T17:59:19.373  17:59:19.326   ATTEMPT       117.138   127.175  Reconnecting…

Recovery, on the same device:

network restore   NOT ESTABLISHED by this capture, see below. An attempt did fire at
                  17:35:29.884, 30.649s after the failure at 17:34:59.235, and reached
                  Connected at 17:35:40.774 — but this capture cannot show that a restore
                  caused it
manual reconnect  operator tap 17:51:45.505 -> attempt 17:51:46.015  =  0.51s
wake resets       woken attempt failed 17:47:28.015 -> next delay 1.062s
                  woken attempt failed 17:51:56.263 -> next delay 1.034s
success resets    after the 17:35:40.774 success, the next induced outage restarted at
                  0.602, 0.994, 1.747, 2.894s

What is not yet tested on a physical device: final head d7d5c4e0ec166e1c0d776cc1217dfd073212f9ca with the 60 s ceiling and VPN/private-LAN restore path. The absolute policy bound is covered by steadyReconnectTimerIsThirtyToSixtySecondsBeforeConnectionTime, 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; reconnectDelayStaysBoundedSoAnEndpointOnlyRestartIsStillFound keeps 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 d7d5c4e0ec166e1c0d776cc1217dfd073212f9ca and 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.

Regression Runnable BEFORE Current AFTER
ACK cannot enqueue after real OkHttp >16 MiB overflow and dropped close exchange assertion fails: READY socket does not reconnect passes: current socket retires and reconnects
DNS-only change on the same mutable LinkProperties object assertion fails: no wake passes: one wake; duplicates/lost/reattach coalesce correctly

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:

./gradlew :app:testPlayDebugUnitTest --tests 'ai.openclaw.app.gateway.GatewaySession*' --tests 'ai.openclaw.app.gateway.NetworkMonitorTest' --tests 'ai.openclaw.app.GatewayFleetSelectionTest' :app:testThirdPartyDebugUnitTest --tests 'ai.openclaw.app.gateway.GatewaySession*' --tests 'ai.openclaw.app.gateway.NetworkMonitorTest' --tests 'ai.openclaw.app.GatewayFleetSelectionTest' ktlintCheck --max-workers=2 --no-daemon --console=plain

From the repository root:

OPENCLAW_VITEST_MAX_WORKERS=2 node scripts/run-vitest.mjs src/gateway/role-policy.test.ts src/gateway/server-methods-list.test.ts src/gateway/server-methods.authorization.test.ts src/gateway/server.preauth-hardening.test.ts src/gateway/server/ws-connection/authenticated-request-dispatch
node scripts/check-changed.mjs
pnpm build

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 onto 0f429cef53d8d1dfbe5358b962f56c70c6db8153. 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.

Scenario Before evidence After evidence
Silently broken READY socket Published head 8e36d6b0496503c606a018199154c7b8e12b44f7 plus 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. Both-flavor pre-rebase after proof retired the failed flow at approximately 8.0 s, reconnected, and completed a fresh RPC.
Slow health summary, healthy transport An intermediate health-only candidate closed a still-responsive socket; its dedicated negative control failed. A fresh non-health RPC while health remains pending preserves the same lease and unrelated work. An application-error health reply also proves liveness.
Broken outbound path with live inbound events The intermediate inbound-counter candidate still reached the 15,001 ms RPC timeout. The directional TCP test now retires the stale flow and reconnects. It also delivers a late reply to a pre-restore request, which must not count as new liveness.
Replacement, Disconnect, auth pause Existing lifecycle regression boundaries remain in scope. A late check cannot retire the replacement, undo Disconnect, or clear a deliberate auth pause; repeated callbacks coalesce per physical socket.

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):

apps/android/gradlew -p apps/android --no-daemon --max-workers=2 :app:testPlayDebugUnitTest --tests 'ai.openclaw.app.gateway.GatewaySession*Test' --tests ai.openclaw.app.gateway.NetworkMonitorTest --tests ai.openclaw.app.GatewayFleetSelectionTest
apps/android/gradlew -p apps/android --no-daemon --max-workers=2 :app:testThirdPartyDebugUnitTest --tests 'ai.openclaw.app.gateway.GatewaySession*Test' --tests ai.openclaw.app.gateway.NetworkMonitorTest --tests ai.openclaw.app.GatewayFleetSelectionTest
apps/android/gradlew -p apps/android :app:ktlintCheck :benchmark:ktlintCheck :wear:ktlintCheck :wear-shared:ktlintCheck

Exact-head GitHub CI: run 33878942077, attempt 1 completed successfully on d7d5c4e0ec166e1c0d776cc1217dfd073212f9ca. security-fast, all six Android lanes, and openclaw/ci-gate are 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_787f8457d0e8 and green in run_90d71d93ae8f; the one-minute policy was verified in run_6e43f376aa60 on an earlier head; startup suppression was red in run_d7ad9197a7a6 and green in run_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 — the
    retry-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 route
    callback 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 — the
    network-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
d7d5c4e0ec166e1c0d776cc1217dfd073212f9ca showing a saved Gateway recovering, without a manual
Reconnect, 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 —
dumpsys reports NOT_VPN throughout — 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_VPN request filter. The physical private-LAN/VPN gate therefore stays
open. 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_atd API 31 (Android 12), pixel_6 profile, x86_64,
software-rendered. Its only network is eth0/10.0.2.15, reported as MOBILE, whose default route
reaches 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 approve and nodes approve were run) and reached Connected before each run. The outage
is 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 when timestamp, sampled every
250 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 in
dumpsys connectivity at each step:

while down    Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED&NOT_VPN&NOT_VCN_MANAGED
after it returns
              Capabilities: MMS&SUPL&DUN&FOTA&IMS&CBS&INTERNET&NOT_RESTRICTED&TRUSTED&NOT_VPN
              &NOT_ROAMING&FOREGROUND&NOT_CONGESTED&NOT_SUSPENDED&NOT_VCN_MANAGED

Two builds, both from the same :app:assemblePlayDebug on this head, installed into the same app
slot with adb install -r so the pairing survives the swap. A is this head unmodified; B is this
head with exactly this block deleted from NetworkMonitor's ConnectivityManager.NetworkCallback,
and nothing else changed:

      override fun onAvailable(network: Network) {
        // Fires once per network attach, before validation resolves, so it also covers a
        // restored private LAN/VPN route that never reaches NET_CAPABILITY_VALIDATED.
        // Registration can replay an existing route, but session guards make that wake harmless;
        // dropping it here would also drop an indistinguishable genuine restore.
        val newlyAvailable = restoreState.onAvailable(network)
        if (newlyAvailable) {
          notifyNetworkAvailable()
        }
      }

APK sha256:

A  dc5e4e38bf097ad2a02afcb9a75cacc1de95d6c9f1986ee0b6015334a7e2b4c6
B  7213892037de3fe44478aec5695d0f649857d5715b25d0051ef9988254da6bc3

NetworkMonitor has exactly two calls to
notifyNetworkAvailable(), one in each callback, so with that block gone B's only remaining wake
path in this class is the validated edge in onCapabilitiesChanged — which this route never
produces. 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:assemblePlayDebug on this head, deleting only the
onAvailable override for B;
adb install -r each into the same slot; stop the Gateway; wait for the retry ladder to reach its
steady band; restart the Gateway (which produces no Android network event); then
adb shell svc data disable, wait, adb shell svc data enable; sample
adb shell dumpsys notification every 250 ms and record each change with the app's own when
timestamp, and read dumpsys connectivity at each step. Restarting the Gateway before touching the
route is what makes the timer excludable: an attempt that lands before the timer floor cannot be the
timer.

                                     A (this head)          B (onAvailable removed)
ladder before the sequence           …32.8  35.7  46.6      …40.5  43.2  39.8  39.9
last failure                         14:43:41.849           14:51:58.974
floor implied by that row            14:44:11.849           14:52:28.974   (that failure + the 30 s floor)
Gateway listening again              14:43:52.690           14:52:11.631
route down                           14:43:56.692           14:52:15.632
route up (command issued)            14:44:02.293           14:52:21.596
first reconnect-status row after it  14:44:08.088           14:52:49.642
   vs route-up command                +5.80 s                +28.05 s
   vs floor implied by that row       -3.76 s  (before it)   +20.67 s  (after it)
Connected                            14:44:14.227           14:53:02.451
   vs route-up command               +11.93 s               +40.86 s

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 s figure therefore excludes the timer of
the 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 onAvailable route wake being what produced A's early
attempt; 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 Connected row follows 6.14 s after that attempt on the
device 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 the
merged 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 merged Connected
row 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 enable was 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 a
combined Connected (operator: Reconnecting…) row instead, so B's marker is the first reconnect
status 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 down and route up rows are host-clock markers written when the command was issued; the
last failure, first attempt and Connected rows are the app's own device-side when values.
Measured at capture time by comparing date +%s%3N on both sides, the device clock ran about 620 ms
behind 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 row and the first reconnect row are all
device-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:

device_when_ms   utc            notification
1788532648669    14:37:28.669   Reconnecting…
1788532649027    14:37:29.027   Gateway error: Failed to connect to /10.0.2.2:18899
1788532673802    14:37:53.802   Reconnecting…
1788532673945    14:37:53.945   Gateway error: Failed to connect to /10.0.2.2:18899
1788532715549    14:38:35.549   Gateway error: Failed to connect to /10.0.2.2:18899
1788532758585    14:39:18.585   Gateway error: Failed to connect to /10.0.2.2:18899
1788532810239    14:40:10.239   Gateway error: Failed to connect to /10.0.2.2:18899
1788532847589    14:40:47.589   Gateway error: Failed to connect to /10.0.2.2:18899
1788532906769    14:41:46.769   Gateway error: Failed to connect to /10.0.2.2:18899
1788532939530    14:42:19.530   Gateway error: Failed to connect to /10.0.2.2:18899
1788532975253    14:42:55.253   Gateway error: Failed to connect to /10.0.2.2:18899
1788533020710    14:43:40.710   Reconnecting…
1788533021849    14:43:41.849   Gateway error: Failed to connect to /10.0.2.2:18899
1788533048088    14:44:08.088   Reconnecting…
1788533051394    14:44:11.394   Connected (operator: Reconnecting…
1788533054227    14:44:14.227   Connected

Raw capture, run B (control) — same:

device_when_ms   utc            notification
1788533272067    14:47:52.067   Starting…
1788533276382    14:47:56.382   Gateway error: Failed to connect to /10.0.2.2:18899
1788533280629    14:48:00.629   Gateway error: Failed to connect to /10.0.2.2:18899
1788533288148    14:48:08.148   Gateway error: Failed to connect to /10.0.2.2:18899
1788533297713    14:48:17.713   Gateway error: Failed to connect to /10.0.2.2:18899
1788533307584    14:48:27.584   Gateway error: Failed to connect to /10.0.2.2:18899
1788533325389    14:48:45.389   Gateway error: Failed to connect to /10.0.2.2:18899
1788533355671    14:49:15.671   Gateway error: Failed to connect to /10.0.2.2:18899
1788533396123    14:49:56.123   Gateway error: Failed to connect to /10.0.2.2:18899
1788533435990    14:50:35.990   Reconnecting…
1788533439317    14:50:39.317   Gateway error: Failed to connect to /10.0.2.2:18899
1788533478034    14:51:18.034   Reconnecting…
1788533479090    14:51:19.090   Gateway error: Failed to connect to /10.0.2.2:18899
1788533518974    14:51:58.974   Gateway error: Failed to connect to /10.0.2.2:18899
1788533569642    14:52:49.642   Connected (operator: Reconnecting…
1788533582451    14:53:02.451   Connected

These two blocks are the complete captures, not excerpts; the host-clock markers and the
dumpsys connectivity reads 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:assemblePlayDebug builds from the same toolchain with
the same pinned build stamps, installed by adb install -r into a single app slot —
so package id, uid, data directory and node identity cannot differ between the two
groups:

BEFORE  openclaw@28164d093498 (this PR's base)  sha256:a5016b2d808770de…
AFTER   openclaw@b6338e7773e3 (intermediate 300 s candidate)  sha256:694b2b5fd4c479dd…

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.dex and classes10.dex, 3,196 bytes of uncompressed content in total. gatewayReconnectDelayMs, awaitReconnectWake,
reconnectWakeObserved, GATEWAY_RECONNECT_MAX_DELAY_MS and
gatewaySessionsToWakeOnNetworkRestore are in the AFTER dex and in no BEFORE dex, and each APK carries its own build commit, so a
reader 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:

                   BEFORE  (openclaw@28164d09)      AFTER  (openclaw@b6338e77)
outage 60 s        3.988 s   3.942 s   3.944 s      2.062 s   29.080 s   20.919 s
  median           3.944 s                          20.919 s
outage 300 s       6.474 s   5.184 s   6.467 s     86.073 s   30.338 s   32.770 s
  median           6.467 s                          32.770 s

each outage length: 6/6 repetitions admitted, 6/6 reconnected (12/12 overall), none
           discarded, executed base-1, candidate-1, base-2, candidate-2, base-3,
           candidate-3; tolerance 1.5 s (absolute) or 20% of the base median, whichever
           is wider — the width a difference between the two medians has to exceed before
           the comparison calls it a difference at all, derived from within-group spread
           on this deployment rather than chosen for this change. Both runs clear it.

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 head cc3460fcbd2e (AFTER). This branch has since been
rebased onto 28164d09349, and the reconnect behaviour was re-measured there, on a
different 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:

  • no hunk falls inside runLoop() or the connect path it drives — the region from
    private suspend fun runLoop() through the opening half of connectOnce() is
    byte-identical across the two bases;
  • neither does any hunk fall inside the block from connect() to
    readyConnection(), which holds disconnect(), reconnect(),
    retryAfterNetworkRestore(), signalReconnect() and drainReconnectSignals() —
    every producer and consumer of reconnectSignal. That block is byte-identical too.
  • The observable is unchanged as well: NodeForegroundService.kt has no commit in
    that range and gatewayConnectionStatusForDisplay() in NodeRuntime.kt is
    byte-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,
drainReconnectSignals and the three runLoop call sites are byte-identical between the
measured head cc3460fcbd2e and this head. awaitReconnectWake is 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 condition delivered was 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.kt only, so the retry algorithm those
measurements 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.

before/after reconnect cadence on a physical device

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:ktlintCheck and :app:lintPlayDebug clean. 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 fails aWakeTheChannelNeverDeliveredStillCountsAsAWake, and leaving the endpoint-replacement producer out of the count fails everyWakeProducerAdvancesTheWakeCount (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, because NodeRuntime cannot 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

@clawsweeper

clawsweeper Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@masatohoshino
masatohoshino marked this pull request as ready for review August 22, 2026 11:33
@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 22, 2026
@clawsweeper

clawsweeper Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed September 4, 2026, 6:07 PM ET / 22:07 UTC.

ClawSweeper review

What this changes

The PR slows persistent Android Gateway reconnects, wakes all saved sessions after route changes, and adds a lightweight authenticated WebSocket liveness acknowledgement.

Regression provenance

Possible 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
Reviewed head: 38acb9e1605c077636542e60a0e526bfb36db13f

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The PR has substantial focused coverage but needs the protocol-order repair and final-head real route-recovery proof.
Proof confidence 🦐 gold shrimp (3/6) Needs stronger real behavior proof before merge: The changed production path is NetworkMonitor → NodeRuntime → GatewaySession. Available exact-head software and transport-fault evidence exercises pieces of it, but the supplied material does not establish an after-fix physical private-LAN/VPN route restoration on the final head; redact private details in any added trace. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: The changed production path is NetworkMonitor → NodeRuntime → GatewaySession. Available exact-head software and transport-fault evidence exercises pieces of it, but the supplied material does not establish an after-fix physical private-LAN/VPN route restoration on the final head; redact private details in any added trace. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 8 items Introduced compatibility regression: The PR inserts gateway.ping before existing advertised methods. The ordered spec is emitted unchanged into the advertised method list, while nearby established comments require additive methods to be appended to preserve existing indices.
Existing order contract: The existing test explicitly protects method-list index stability, but only for the current tail; it does not catch a newly inserted middle entry.
PR-head introduction provenance: The exact verified PR head adds the middle-table gateway.ping row relative to its recorded parent.
Findings 1 actionable finding [P1] Append gateway.ping without shifting discovery indices
Security None None.

How this fits together

The 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]
Loading

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: The changed production path is NetworkMonitor → NodeRuntime → GatewaySession. Available exact-head software and transport-fault evidence exercises pieces of it, but the supplied material does not establish an after-fix physical private-LAN/VPN route restoration on the final head; redact private details in any added trace. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Append gateway.ping without shifting discovery indices (P1) - listCoreAdvertisedGatewayMethodNames() preserves this table’s order, and established rows are appended specifically to keep prior hello-ok.features.methods indices stable. Inserting this new method here shifts every following advertised method for existing clients; append it at the tail and extend the ordering regression instead.
  • Resolve merge risk (P1) - Inserting gateway.ping into the middle of the ordered advertised method list shifts existing discovery indices for connected clients.
  • Resolve merge risk (P1) - The available evidence does not establish exact-head physical-device recovery when a private-LAN or VPN route returns; a missed wake leaves endpoint-only recovery to the 30–60 second retry interval plus connection time.
  • Resolve merge risk (P1) - This bug-fix branch adds production +324/-57 lines (net +267); the liveness protocol has a concrete purpose, but avoidable growth should be removed while correcting the discovery-order regression.
  • Complete next step (P2) - Append gateway.ping at the end of the advertised core-method list with an order-preservation regression, then attach redacted exact-head physical private-LAN or VPN restoration proof with build identity and elapsed recovery time.

Findings

  • [P1] Append gateway.ping without shifting discovery indices — src/gateway/methods/core-descriptors.ts:344-345
Agent review details

Security

None.

PR surface

Source +37, Tests +993, Docs +16, Other +230. Total +1276 across 18 files.

View PR surface stats
Area Files Added Removed Net
Source 5 47 10 +37
Tests 7 1013 20 +993
Docs 1 16 0 +16
Config 0 0 0 0
Generated 0 0 0 0
Other 5 277 47 +230
Total 18 1353 77 +1276

Review metrics

Metric Value Why it matters
Production versus test delta production +324/-57 (net +267); tests/support +1013/-20 (net +993); docs +16/-0 The large test investment covers retry, route, and transport cases, while the positive production growth needs to remain justified by the liveness contract.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #127872
Summary: This PR is the open implementation candidate formally linked to the reported Android reconnect behavior.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Preserve discovery ordering (recommended)
    Move gateway.ping to the append-only end of the advertised core-method list and add a regression proving prior method indices remain stable.
  2. Hold for route-recovery proof
    Keep merge blocked until a redacted exact-head physical-device trace proves automatic recovery after private-LAN or VPN route restoration.

Technical review

Best 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:

  • [P1] Append gateway.ping without shifting discovery indices — src/gateway/methods/core-descriptors.ts:344-345
    listCoreAdvertisedGatewayMethodNames() preserves this table’s order, and established rows are appended specifically to keep prior hello-ok.features.methods indices stable. Inserting this new method here shifts every following advertised method for existing clients; append it at the tail and extend the ordering regression instead.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 8918e743cdf8.

Labels

Label justifications:

  • P1: This PR changes recovery behavior for Android users whose configured Gateway becomes unreachable.
  • merge-risk: 🚨 compatibility: The introduced method’s position shifts the public ordered discovery list for existing Gateway clients.
  • merge-risk: 🚨 availability: The retry cadence and route-triggered recovery path determine how long an Android client remains disconnected.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The changed production path is NetworkMonitor → NodeRuntime → GatewaySession. Available exact-head software and transport-fault evidence exercises pieces of it, but the supplied material does not establish an after-fix physical private-LAN/VPN route restoration on the final head; redact private details in any added trace. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

Acceptance criteria:

  • [P1] pnpm test src/gateway/server-methods-list.test.ts.
  • [P1] pnpm test src/gateway/server/ws-connection/authenticated-request-dispatch.ping.test.ts.
  • [P1] node scripts/check-changed.mjs --dry-run -- src/gateway/methods/core-descriptors.ts src/gateway/server-methods-list.test.ts.

What I checked:

  • Introduced compatibility regression: The PR inserts gateway.ping before existing advertised methods. The ordered spec is emitted unchanged into the advertised method list, while nearby established comments require additive methods to be appended to preserve existing indices. (src/gateway/methods/core-descriptors.ts:345, 38acb9e1605c)
  • Existing order contract: The existing test explicitly protects method-list index stability, but only for the current tail; it does not catch a newly inserted middle entry. (src/gateway/server-methods-list.test.ts:164, 38acb9e1605c)
  • PR-head introduction provenance: The exact verified PR head adds the middle-table gateway.ping row relative to its recorded parent. (src/gateway/methods/core-descriptors.ts:345, 38acb9e1605c)
  • Android owner boundary: Retry timing remains in GatewaySession; route events fan out through NodeRuntime, and the ready-socket liveness check is gated on the advertised method and current connection identity. (apps/android/app/src/main/java/ai/openclaw/app/gateway/GatewaySession.kt:1272, 38acb9e1605c)
  • Current-main necessity check: The PR head is not contained in fetched current main, and no main-only commits after the branch point touch the three central Android owner files; the central Android fix is not obsolete. (8918e743cdf8)
  • Proof gap: The available PR-body excerpts provide current-head software and transport-fault controls, but characterize the supplied device evidence as an earlier candidate and explicitly retain physical private-LAN/VPN restoration as unproven; omitted body ranges remain unknown. (38acb9e1605c)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Ben.Li: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Append gateway.ping after the existing advertised-method tail and update the stable-order regression.
  • Attach a redacted exact-head physical-device trace of private-LAN or VPN route restoration with build identity and elapsed recovery time.
  • Update the PR body with that evidence so ClawSweeper can refresh automatically; if it does not, ask a maintainer to comment @clawsweeper re-review.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (21 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-03T23:37:24.759Z sha 25817cb0cb48835dde93b245552623f4916835cc :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-04T00:29:09.740Z sha b35d7eb3d7103e6df154dfdc0128b56e1b26e7d7 :: needs real behavior proof before merge. :: [P2] Do not suppress a real route restore during monitor startup
  • reviewed 2026-09-04T03:09:02.211Z sha 8e36d6b0496503c606a018199154c7b8e12b44f7 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-04T03:16:30.609Z sha 8e36d6b0496503c606a018199154c7b8e12b44f7 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-04T13:47:18.057Z sha d7d5c4e :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-04T13:55:03.804Z sha d7d5c4e :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-04T14:45:13.725Z sha d7d5c4e :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-04T16:47:43.365Z sha d7d5c4e :: needs real behavior proof before merge. :: none

@masatohoshino

Copy link
Copy Markdown
Contributor Author

Accepted — the finding is right, and it was a regression this PR introduced. Repaired in fe1ed30761f.

Root cause. retryGatewaySessionsAfterNetworkRestore in NodeRuntime.kt named only operatorSession and nodeSession, while the same class also keeps a live GatewaySession per additional saved gateway in secondaryOperatorSessions. Those inherit this PR's delay policy, so raising the ceiling turned a missed wake for them from at most ~8s into minutes.

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 backgroundGatewayStableIds / backgroundGatewayFleetPlan, and it snapshots the fleet the way disconnectSecondaryGatewayConnections already does, so an edit during the fan-out cannot make it skip a session. No new lifecycle state and no second reconnect loop; each session keeps its own desired connection, auth pause and retry ladder.

Coverage. apps/android/app/src/test/java/ai/openclaw/app/GatewayFleetSelectionTest.kt goes 4 → 8 tests: operator+node+three secondaries, a single secondary, none at all, and one that clears the fleet after the call to show the wake used a snapshot. All eight pass. Removing the secondaries from the selection makes three of the four new ones fail (expected:<5> but was:<2>); the command is :app:testPlayDebugUnitTest --tests ai.openclaw.app.GatewayFleetSelectionTest. Full suites are green at this head: 2144 and 2275 tests, ktlint and lint clean. Those tests pin the wake decision; they do not observe the call site, because NodeRuntime is not constructible in a unit test without dependency injection I did not want to add for this.

Scope of the change since your scan (the second commit on this PR). The diff from cc3460fcbd2e to fe1ed30761f touches two files: NodeRuntime.kt and that test. GatewaySession.kt is unchanged between the two heads. To be exact about what that buys: the device measurements were not re-run at this head — the source implementing the algorithm they measured is simply the same, which is why I did not repeat the 42-minute capture. The body now states that boundary, and that the fan-out is covered by tests rather than by a device run — a two-gateway physical scenario was not performed.

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.

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

Copy link
Copy Markdown
Contributor Author

I noticed the latest ClawSweeper verdict is already clean/ready-for-maintainer-review, but the managed PR labels are still showing the prior rating: 🦐 gold shrimp / status: ⏳ waiting on author state. Re-review requested above to reconcile the managed labels with the current verdict.

Copy link
Copy Markdown
Contributor Author

I’m treating this as a ClawSweeper status-label reconciliation issue, not a code issue: the latest durable verdict says Ready for maintainer review, Findings: None, and Overall readiness: 🐚 platinum hermit, while the managed labels still show the prior author-work state. No code change is being made.

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-run

@clawsweeper

clawsweeper Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

Copy link
Copy Markdown
Contributor Author

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.

Copy link
Copy Markdown
Contributor Author

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.

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

Copy link
Copy Markdown
Contributor Author

I’ll stop adding comments here; the requested re-review is already queued.

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 22, 2026
@IWhatsskill

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

masatohoshino and others added 8 commits September 4, 2026 13:26
`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.
@roboclaw-bot
roboclaw-bot force-pushed the fix/android-gateway-reconnect-battery-backoff branch from 8e36d6b to d7d5c4e Compare September 4, 2026 13:35
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

Please review exact head d7d5c4e0ec166e1c0d776cc1217dfd073212f9ca. The PR body now documents the stale-READY/one-way-transport repair, the before/after TCP controls, 234 passing final-head local tests and changed gates, and the independent P0-P2 repair review. The physical Android/private-route proof limitation is explicitly retained. Please assess the current source and evidence; no merge is requested.

@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Sep 4, 2026
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]>
@roboclaw-bot
roboclaw-bot requested a review from a team as a code owner September 4, 2026 21:53
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: XL and removed size: L labels Sep 4, 2026
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

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!

roboclaw-bot pushed a commit that referenced this pull request Sep 5, 2026
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]>
roboclaw-bot pushed a commit that referenced this pull request Sep 5, 2026
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]>
roboclaw-bot pushed a commit that referenced this pull request Sep 5, 2026
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]>
roboclaw-bot added a commit that referenced this pull request Sep 5, 2026
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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 6, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: android App: android docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Android: severe battery drain continues after the app is dismissed from Recents when the Gateway becomes unreachable

3 participants