From 45d05506612865ce0d254044ae13cc9793f99eac Mon Sep 17 00:00:00 2001 From: NubsCarson Date: Fri, 4 Dec 2026 11:59:32 -0800 Subject: [PATCH] fix(android): guard AlphaLocalAgentRunner phase transitions against stop races Guard lifecycle phase, epoch, and failure-detail transitions in AlphaLocalAgentRunner under lifecycleLock so an in-flight async launchLocked(), failLocked(), markReadyLocked(), watchExit(), or failOrScheduleRestartLocked() task on the serial executor cannot flip statusJson() back to starting, running, or failed after stop() sets desiredRunning = false or restart() advances activeEpoch. Make statusJson() and isRunning() read lifecycle state atomically under lifecycleLock (always reporting stopped with epoch 0 whenever !desiredRunning), track childEpoch separately so queued stop teardown retires only the child it tears down, and add deterministic async-stop and stress-cycle regression tests in AlphaAgentServiceLocalHandoffTest. --- .../alphaphone/AlphaLocalAgentRunner.java | 215 +++++++++++++----- .../AlphaAgentServiceLocalHandoffTest.java | 154 +++++++++++++ 2 files changed, 316 insertions(+), 53 deletions(-) diff --git a/apps/app/android/app/src/main/java/ai/alphacompute/alphaphone/AlphaLocalAgentRunner.java b/apps/app/android/app/src/main/java/ai/alphacompute/alphaphone/AlphaLocalAgentRunner.java index 1f79ed0dce..0720205b0a 100644 --- a/apps/app/android/app/src/main/java/ai/alphacompute/alphaphone/AlphaLocalAgentRunner.java +++ b/apps/app/android/app/src/main/java/ai/alphacompute/alphaphone/AlphaLocalAgentRunner.java @@ -105,6 +105,7 @@ private enum Phase { STOPPED, STARTING, RUNNING, FAILED } private volatile Path activeSocket; private volatile String activeToken; private Process childProcess; + private long childEpoch; private ScheduledFuture watchdogTask; private ScheduledFuture restartTask; private Map lastEnvironment = Map.of(); @@ -139,7 +140,7 @@ public static AutoCloseable onReady(Runnable observer) { Objects.requireNonNull(observer); READY_OBSERVERS.add(observer); AlphaLocalAgentRunner current = instance; - if (current != null && current.phase == Phase.RUNNING) { + if (current != null && current.isPhaseRunning()) { NOTICES.execute(observer); } return () -> READY_OBSERVERS.remove(observer); @@ -152,14 +153,45 @@ public boolean isActive() { /** True when the local Node 26 agent is healthy and serving on {@link AgentService#channel()}. */ public boolean isRunning() { - return phase == Phase.RUNNING && AgentService.channel().policy().servingEpoch() == activeEpoch && activeEpoch > 0; + long epoch; + synchronized (lifecycleLock) { + if (!desiredRunning || phase != Phase.RUNNING || activeEpoch <= 0L) { + return false; + } + epoch = activeEpoch; + } + return AgentService.channel().policy().servingEpoch() == epoch; + } + + private boolean isEpochCurrent(long epoch) { + synchronized (lifecycleLock) { + return desiredRunning && activeEpoch == epoch; + } + } + + private boolean isPhaseRunning() { + synchronized (lifecycleLock) { + return desiredRunning && phase == Phase.RUNNING; + } } /** Returns the {@code ElizaAgent.getStatus()} JSON snapshot for the local runner. */ public JSONObject statusJson() { - Phase current = phase; - if (current == Phase.STOPPED && desiredRunning) { - current = Phase.STARTING; + Phase current; + long epoch; + String failure; + String detail; + synchronized (lifecycleLock) { + if (!desiredRunning) { + current = Phase.STOPPED; + } else if (phase == Phase.STOPPED) { + current = Phase.STARTING; + } else { + current = phase; + } + epoch = current == Phase.STOPPED ? 0L : activeEpoch; + failure = current == Phase.FAILED ? failureReason : null; + detail = current == Phase.FAILED ? errorDetail : null; } String state = switch (current) { case STOPPED -> "stopped"; @@ -171,12 +203,12 @@ public JSONObject statusJson() { try { out.put("available", true) .put("state", state) - .put("epoch", current == Phase.STOPPED ? 0L : activeEpoch) + .put("epoch", epoch) .put("requestBodyLimit", AgentService.REQUEST_BODY_LIMIT) .put("mode", "local"); if (current == Phase.FAILED) { - if (failureReason != null) out.put("failure", failureReason); - if (errorDetail != null) out.put("error", errorDetail); + if (failure != null) out.put("failure", failure); + if (detail != null) out.put("error", detail); } } catch (JSONException impossible) { throw new IllegalStateException(impossible); @@ -206,13 +238,19 @@ public void start(Map environment, AgentConfig.GoogleConsent con } long targetEpoch = launchEpoch; serial.execute(() -> { - if (!desiredRunning || activeEpoch != targetEpoch) return; + if (!isEpochCurrent(targetEpoch)) return; lastEnvironment = envCopy; lastConsent = consent; restartAttempt = 0; cancelRestartLocked(); - if (phase == Phase.RUNNING && childProcess != null) return; - if (phase == Phase.STARTING && childProcess != null) return; + if (childProcess != null && childEpoch == targetEpoch) { + synchronized (lifecycleLock) { + if (desiredRunning && activeEpoch == targetEpoch + && (phase == Phase.RUNNING || phase == Phase.STARTING)) { + return; + } + } + } launchLocked(targetEpoch, envCopy, consent); }); } @@ -229,7 +267,7 @@ public void restart(Map environment, AgentConfig.GoogleConsent c failureReason = null; errorDetail = null; serial.execute(() -> { - if (!desiredRunning || activeEpoch != targetEpoch) return; + if (!isEpochCurrent(targetEpoch)) return; lastEnvironment = envCopy; lastConsent = consent; restartAttempt = 0; @@ -253,10 +291,16 @@ public void stop() { restartAttempt = 0; cancelRestartLocked(); teardownChildLocked(); - if (!desiredRunning) { - phase = Phase.STOPPED; - failureReason = null; - errorDetail = null; + boolean shouldNotify = false; + synchronized (lifecycleLock) { + if (!desiredRunning) { + phase = Phase.STOPPED; + failureReason = null; + errorDetail = null; + shouldNotify = true; + } + } + if (shouldNotify) { notifyObservers(); } }); @@ -284,24 +328,26 @@ public boolean awaitReady(long timeoutMs) { } private void launchLocked(long epoch, Map environment, AgentConfig.GoogleConsent consent) { - activeEpoch = epoch; - phase = Phase.STARTING; - failureReason = null; - errorDetail = null; + synchronized (lifecycleLock) { + if (!desiredRunning || activeEpoch != epoch) return; + phase = Phase.STARTING; + failureReason = null; + errorDetail = null; + } notifyObservers(); AgentConfig config; try { config = AgentService.config(appContext); } catch (AgentConfig.Refused | IOException refused) { - failLocked("config", refused.getMessage()); + failLocked(epoch, "config", refused.getMessage()); return; } AgentChannel channel = AgentService.channel(); channel.policy().loadRoutes(CallerKind.NATIVE, config.routes(CallerKind.NATIVE)); if (!channel.policy().loadRoutes(CallerKind.RENDERER, config.routes(CallerKind.RENDERER))) { - failLocked("config", "The agent renderer route list could not be loaded"); + failLocked(epoch, "config", "The agent renderer route list could not be loaded"); return; } @@ -317,15 +363,17 @@ private void launchLocked(long epoch, Map environment, AgentConf directories.sync() ); if (check instanceof PayloadCheck.Failed failed) { - failLocked("payload", String.join("; ", failed.errors())); + failLocked(epoch, "payload", String.join("; ", failed.errors())); return; } prepared = AlphaDevBuild.agent(appContext, ((PayloadCheck.Ready) check).payload()); } catch (IOException | PackageManager.NameNotFoundException failed) { - failLocked("payload", "The agent runtime could not be verified: " + failed.getMessage()); + failLocked(epoch, "payload", "The agent runtime could not be verified: " + failed.getMessage()); return; } + if (!isEpochCurrent(epoch)) return; + String token = LaunchFrame.newToken(); try { @@ -362,6 +410,8 @@ private void launchLocked(long epoch, Map environment, AgentConf } builder.redirectErrorStream(true).redirectOutput(ProcessBuilder.Redirect.appendTo(logFile.toFile())); + if (!isEpochCurrent(epoch)) return; + Process spawned = builder.start(); try (OutputStream stdin = spawned.getOutputStream()) { stdin.write(frame); @@ -371,8 +421,17 @@ private void launchLocked(long epoch, Map environment, AgentConf throw writeFailed; } + if (!isEpochCurrent(epoch)) { + spawned.destroyForcibly(); + try { + Files.deleteIfExists(socketPath); + } catch (IOException ignored) { + } + return; + } + childProcess = spawned; - activeEpoch = epoch; + childEpoch = epoch; activeSocket = socketPath; activeToken = token; Log.i(TAG, "Spawned zero-cloud local agent epoch=" + epoch + " socket=" + socketPath); @@ -386,13 +445,13 @@ private void launchLocked(long epoch, Map environment, AgentConf readyWatcher.start(); } catch (IOException | JSONException | RuntimeException failed) { Log.e(TAG, "Failed to spawn zero-cloud local agent", failed); - failLocked("spawn", failed.getMessage() == null ? "Local agent failed to spawn" : failed.getMessage()); + failLocked(epoch, "spawn", failed.getMessage() == null ? "Local agent failed to spawn" : failed.getMessage()); } } private void awaitChildReady(Process process, long epoch, Path socketPath, String token) { long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(READY_TIMEOUT_MS); - while (process.isAlive() && activeEpoch == epoch && desiredRunning) { + while (process.isAlive() && isEpochCurrent(epoch)) { enforceSocketPermissions(socketPath); HealthPolicy.ProbeReply reply = probeHealth(socketPath, token, process::isAlive); if (HealthPolicy.classify(reply, epoch) == HealthPolicy.Probe.OK) { @@ -403,10 +462,10 @@ private void awaitChildReady(Process process, long epoch, Path socketPath, Strin long remaining = deadline - System.nanoTime(); if (remaining <= 0L) { serial.execute(() -> { - if (childProcess == process && activeEpoch == epoch) { + if (childProcess == process && childEpoch == epoch && isEpochCurrent(epoch)) { Log.w(TAG, "Local agent readiness timed out for epoch=" + epoch); teardownChildLocked(); - failOrScheduleRestartLocked("timeout", "Local agent did not become healthy in time"); + failOrScheduleRestartLocked(epoch, "timeout", "Local agent did not become healthy in time"); } }); return; @@ -420,7 +479,7 @@ private void awaitChildReady(Process process, long epoch, Path socketPath, Strin } private void markReadyLocked(Process process, long epoch, Path socketPath, String token) { - if (childProcess != process || activeEpoch != epoch || !desiredRunning) return; + if (childProcess != process || childEpoch != epoch || !isEpochCurrent(epoch)) return; if (!AgentService.channel().open(epoch, token, socketPath)) { long currentServing = AgentService.channel().policy().servingEpoch(); if (currentServing > 0L && currentServing != epoch) { @@ -428,14 +487,27 @@ private void markReadyLocked(Process process, long epoch, Path socketPath, Strin } if (!AgentService.channel().open(epoch, token, socketPath)) { teardownChildLocked(); - failLocked("channel", "Could not open local agent channel for epoch " + epoch); + failLocked(epoch, "channel", "Could not open local agent channel for epoch " + epoch); return; } } - phase = Phase.RUNNING; + boolean becameRunning; + synchronized (lifecycleLock) { + if (desiredRunning && activeEpoch == epoch) { + phase = Phase.RUNNING; + failureReason = null; + errorDetail = null; + becameRunning = true; + } else { + becameRunning = false; + } + } + if (!becameRunning) { + AgentService.channel().retire(epoch); + teardownChildLocked(); + return; + } restartAttempt = 0; - failureReason = null; - errorDetail = null; Log.i(TAG, "Zero-cloud local agent ready epoch=" + epoch); startWatchdogLocked(process, epoch, socketPath); notifyObservers(); @@ -454,66 +526,103 @@ private void watchExit(Process process, long epoch) { } int code = exitCode; serial.execute(() -> { - if (childProcess != process || activeEpoch != epoch) return; + if (childProcess != process || childEpoch != epoch) return; Log.i(TAG, "Local agent epoch=" + epoch + " exited code=" + code); cancelWatchdogLocked(); AgentService.channel().retire(epoch); childProcess = null; + childEpoch = 0L; activeSocket = null; activeToken = null; - if (!desiredRunning) { - phase = Phase.STOPPED; + boolean stillCurrent; + boolean notifyStopped = false; + synchronized (lifecycleLock) { + stillCurrent = desiredRunning && activeEpoch == epoch; + if (!desiredRunning) { + phase = Phase.STOPPED; + failureReason = null; + errorDetail = null; + notifyStopped = true; + } + } + if (notifyStopped) { notifyObservers(); return; } - failOrScheduleRestartLocked("exit", "Local agent exited with code " + code); + if (!stillCurrent) { + return; + } + failOrScheduleRestartLocked(epoch, "exit", "Local agent exited with code " + code); }); } private void startWatchdogLocked(Process process, long epoch, Path socketPath) { cancelWatchdogLocked(); watchdogTask = serial.scheduleWithFixedDelay(() -> { - if (childProcess != process || activeEpoch != epoch || phase != Phase.RUNNING || !desiredRunning) return; + if (childProcess != process || childEpoch != epoch || !isEpochCurrent(epoch) || !isPhaseRunning()) return; if (!process.isAlive() || !socketAccepts(socketPath)) { Log.w(TAG, "Local agent watchdog detected dead process/socket for epoch=" + epoch); teardownChildLocked(); - failOrScheduleRestartLocked("unhealthy", "Local agent stopped accepting connections"); + failOrScheduleRestartLocked(epoch, "unhealthy", "Local agent stopped accepting connections"); } }, WATCHDOG_INTERVAL_MS, WATCHDOG_INTERVAL_MS, TimeUnit.MILLISECONDS); } - private void failOrScheduleRestartLocked(String reason, String detail) { - if (!desiredRunning || restartAttempt >= MAX_RESTART_ATTEMPTS) { - failLocked(reason, detail); + private void failOrScheduleRestartLocked(long epoch, String reason, String detail) { + if (!isEpochCurrent(epoch)) { return; } + if (restartAttempt >= MAX_RESTART_ATTEMPTS) { + failLocked(epoch, reason, detail); + return; + } + synchronized (lifecycleLock) { + if (!desiredRunning || activeEpoch != epoch) { + return; + } + phase = Phase.STARTING; + failureReason = null; + errorDetail = null; + } long delayMs = HealthPolicy.restartDelay(restartAttempt++); - phase = Phase.STARTING; - failureReason = null; - errorDetail = null; notifyObservers(); cancelRestartLocked(); restartTask = serial.schedule(() -> { - if (desiredRunning && phase != Phase.RUNNING) { - launchLocked(reserveEpoch(), lastEnvironment, lastConsent); + long retryEpoch; + synchronized (lifecycleLock) { + if (!desiredRunning || activeEpoch != epoch || phase == Phase.RUNNING) { + return; + } + retryEpoch = reserveEpoch(); + activeEpoch = retryEpoch; + phase = Phase.STARTING; + failureReason = null; + errorDetail = null; } + launchLocked(retryEpoch, lastEnvironment, lastConsent); }, delayMs, TimeUnit.MILLISECONDS); } - private void failLocked(String reason, String detail) { + private void failLocked(long epoch, String reason, String detail) { cancelWatchdogLocked(); - phase = Phase.FAILED; - failureReason = reason; - errorDetail = detail; + synchronized (lifecycleLock) { + if (!desiredRunning || activeEpoch != epoch) { + return; + } + phase = Phase.FAILED; + failureReason = reason; + errorDetail = detail; + } notifyObservers(); } private void teardownChildLocked() { cancelWatchdogLocked(); - long retiringEpoch = activeEpoch; + long retiringEpoch = childEpoch; Process stopping = childProcess; Path retiringSocket = activeSocket; childProcess = null; + childEpoch = 0L; activeSocket = null; activeToken = null; if (retiringEpoch > 0L) { diff --git a/apps/app/android/app/src/test/java/ai/alphacompute/alphaphone/AlphaAgentServiceLocalHandoffTest.java b/apps/app/android/app/src/test/java/ai/alphacompute/alphaphone/AlphaAgentServiceLocalHandoffTest.java index 6ae1b7bba3..e469709e55 100644 --- a/apps/app/android/app/src/test/java/ai/alphacompute/alphaphone/AlphaAgentServiceLocalHandoffTest.java +++ b/apps/app/android/app/src/test/java/ai/alphacompute/alphaphone/AlphaAgentServiceLocalHandoffTest.java @@ -16,6 +16,13 @@ import android.content.Intent; import android.content.SharedPreferences; import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.LockSupport; +import org.json.JSONObject; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -123,6 +130,153 @@ public void localRunnerLifecycleTransitionsAreSynchronousAndRaceFree() { assertEquals("stopped", runner.statusJson().optString("state")); } + @Test + public void stopDuringAsyncLaunchFailureNeverRevertsStatusFromStopped() throws Exception { + AlphaLocalAgentRunner runner = AlphaLocalAgentRunner.shared(app); + AtomicBoolean stopped = new AtomicBoolean(false); + AtomicReference violation = new AtomicReference<>(); + CountDownLatch launchNotified = new CountDownLatch(1); + CountDownLatch stopNotified = new CountDownLatch(1); + + try (AutoCloseable ignored = AlphaLocalAgentRunner.observe(() -> { + if (!runner.isActive()) { + JSONObject status = runner.statusJson(); + String state = status.optString("state"); + long epoch = status.optLong("epoch", -1L); + if (!"stopped".equals(state) || epoch != 0L || status.has("failure") || status.has("error")) { + violation.compareAndSet(null, "Observed non-stopped snapshot while inactive: " + status); + } + if (stopped.get()) { + stopNotified.countDown(); + } + } else { + launchNotified.countDown(); + } + })) { + runner.start(Map.of("ALPHA_LLM_MODE", "local"), null); + assertTrue("Expected async launch notification", launchNotified.await(5, TimeUnit.SECONDS)); + + stopped.set(true); + runner.stop(); + assertStoppedSnapshot(runner); + + assertTrue("Expected queued stop teardown notification", stopNotified.await(5, TimeUnit.SECONDS)); + } + + // Queue a second stop and wait for its observer callback as a FIFO barrier on serial + notices. + CountDownLatch drained = new CountDownLatch(1); + try (AutoCloseable ignored = AlphaLocalAgentRunner.observe(() -> { + if (!runner.isActive()) { + JSONObject status = runner.statusJson(); + String state = status.optString("state"); + long epoch = status.optLong("epoch", -1L); + if (!"stopped".equals(state) || epoch != 0L || status.has("failure") || status.has("error")) { + violation.compareAndSet(null, "Observed non-stopped snapshot while draining: " + status); + } + drained.countDown(); + } + })) { + runner.stop(); + assertTrue("Expected serial drain barrier", drained.await(5, TimeUnit.SECONDS)); + } + + assertEquals(null, violation.get()); + assertStoppedSnapshot(runner); + } + + @Test + public void repeatedStartRestartStopCyclesKeepStoppedStateAndMonotonicEpochs() throws Exception { + AlphaLocalAgentRunner runner = AlphaLocalAgentRunner.shared(app); + AtomicReference violation = new AtomicReference<>(); + // Even sequence means stop() has returned and no start()/restart() has begun yet. + AtomicLong testPhaseSeq = new AtomicLong(0L); + + try (AutoCloseable ignored = AlphaLocalAgentRunner.observe(() -> { + long seqBefore = testPhaseSeq.get(); + JSONObject status = runner.statusJson(); + long seqAfter = testPhaseSeq.get(); + String state = status.optString("state"); + long epoch = status.optLong("epoch", -1L); + if ("stopped".equals(state)) { + if (epoch != 0L || status.has("failure") || status.has("error")) { + violation.compareAndSet(null, "Inconsistent stopped snapshot: " + status); + } + } else if (epoch <= 0L) { + violation.compareAndSet(null, "Non-stopped snapshot missing positive epoch: " + status); + } + if (seqBefore == seqAfter && (seqBefore & 1L) == 0L) { + if (!"stopped".equals(state) || epoch != 0L || status.has("failure") || status.has("error")) { + violation.compareAndSet(null, "Observed non-stopped snapshot while stopped: " + status); + } + } + })) { + long previousEpoch = 0L; + for (int i = 0; i < 60; i++) { + testPhaseSeq.incrementAndGet(); + runner.start(Map.of("ALPHA_LLM_MODE", "local"), null); + assertTrue(runner.isActive()); + JSONObject started = runner.statusJson(); + assertNotEquals("stopped", started.optString("state")); + long startEpoch = started.optLong("epoch", 0L); + assertTrue("Epoch must advance monotonically across cycles", startEpoch > previousEpoch); + previousEpoch = startEpoch; + + if ((i % 4) == 1) { + Thread.yield(); + } else if ((i % 4) == 2) { + LockSupport.parkNanos(TimeUnit.MICROSECONDS.toNanos(150L)); + } else if ((i % 4) == 3) { + runner.restart(Map.of("ALPHA_LLM_MODE", "local"), null); + assertTrue(runner.isActive()); + JSONObject restarted = runner.statusJson(); + assertNotEquals("stopped", restarted.optString("state")); + long restartEpoch = restarted.optLong("epoch", 0L); + assertTrue("restart() must advance epoch monotonically", restartEpoch > previousEpoch); + previousEpoch = restartEpoch; + LockSupport.parkNanos(TimeUnit.MICROSECONDS.toNanos(100L)); + } + + runner.stop(); + testPhaseSeq.incrementAndGet(); + assertStoppedSnapshot(runner); + if ((i % 3) == 0) { + LockSupport.parkNanos(TimeUnit.MICROSECONDS.toNanos(150L)); + assertStoppedSnapshot(runner); + } + } + } + + CountDownLatch drained = new CountDownLatch(1); + try (AutoCloseable ignored = AlphaLocalAgentRunner.observe(() -> { + if (!runner.isActive()) { + JSONObject status = runner.statusJson(); + if (!"stopped".equals(status.optString("state")) + || status.optLong("epoch", -1L) != 0L + || status.has("failure") + || status.has("error")) { + violation.compareAndSet(null, "Observed stale state after final drain: " + status); + } + drained.countDown(); + } + })) { + runner.stop(); + assertTrue("Expected final drain barrier", drained.await(5, TimeUnit.SECONDS)); + } + + assertEquals(null, violation.get()); + assertStoppedSnapshot(runner); + } + + private static void assertStoppedSnapshot(AlphaLocalAgentRunner runner) { + assertFalse(runner.isActive()); + assertFalse(runner.isRunning()); + JSONObject status = runner.statusJson(); + assertEquals("stopped", status.optString("state")); + assertEquals(0L, status.optLong("epoch", -1L)); + assertFalse("Stopped status must not expose a failure reason", status.has("failure")); + assertFalse("Stopped status must not expose an error detail", status.has("error")); + } + @Test public void keepGoogleConsentPersistsAndPreservesActiveLocalRunner() { assertTrue(AlphaPreferencesProvider.writeForCore(app, AlphaIpcContract.KEY_LLM_MODE, "local"));