From 34a25a30d8884b9f23f24e6a698b37bf8c972f1a Mon Sep 17 00:00:00 2001 From: Luis-ADFA Date: Tue, 1 Sep 2026 04:34:23 -0600 Subject: [PATCH 1/2] ADFA-5365 fix(server-lifecycle): judge a boot on movement, not on the flap grace A boot and a flap are both "alive, not answering", and one 20s threshold was answering both. A boot has been down since its proot started, so its downtime IS its boot time: a device-measured 37s boot was killed at ~24s and relaunched forever, never finishing. The missing fact is whether this proot has ever answered. ServerLiveness now carries it from the observations it already makes, so a boot can be judged on whether it is still moving -- the guest keeps talking while it comes up, and the longest quiet step (13s measured) does not grow with content the way total boot time does. The flap path is untouched. Also removes ServerController's copy of the service-down grace, which sat beside an EnvironmentEnsure javadoc claiming to be the single source. Device-verified: boot reaches UP in 39.9s with zero kills; a killed dash-node is still relaunched at 21s. --- .../java/org/iiab/controller/PRootEngine.java | 25 ++++ .../org/iiab/controller/ServerController.java | 21 ++-- .../env/ServerLifecycleReconciler.java | 8 +- .../env/domain/EnvironmentEnsure.java | 47 ++++++- .../controller/env/domain/ServerLiveness.java | 31 ++++- .../env/domain/EnvironmentEnsureTest.java | 117 ++++++++++++++---- .../env/domain/ServerLivenessTest.java | 56 +++++++++ 7 files changed, 262 insertions(+), 43 deletions(-) diff --git a/controller/app/src/main/java/org/iiab/controller/PRootEngine.java b/controller/app/src/main/java/org/iiab/controller/PRootEngine.java index 91c28d576..b11b53180 100644 --- a/controller/app/src/main/java/org/iiab/controller/PRootEngine.java +++ b/controller/app/src/main/java/org/iiab/controller/PRootEngine.java @@ -43,6 +43,14 @@ public class PRootEngine { private volatile Process currentProcess; private volatile java.io.OutputStream processOutputStream; + /** + * ADFA-5365: when this launch last showed a sign of life, on the monotonic clock. Stamped at + * launch and on every guest line, so "has the boot stalled" is answerable without timing the + * boot as a whole — total boot time grows with the content installed, the gap between two lines + * does not. Per instance, not shared: the actuators hold one engine per launch. + */ + private volatile long lastOutputAtMs; + public interface OutputListener { void onOutputLine(String line); @@ -202,6 +210,9 @@ public void executeInContainer(Context context, String rootfsDir, String command // concurrent proot call can't make us return on the wrong process. Process proc = pb.start(); currentProcess = proc; + // ADFA-5365: the launch itself is the first sign of life, so a boot that never says + // anything is still measured from a real start rather than reading as silent forever. + lastOutputAtMs = android.os.SystemClock.elapsedRealtime(); // --- STREAM LIVE LOGS --- BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream())); @@ -213,6 +224,7 @@ public void executeInContainer(Context context, String rootfsDir, String command final String outLine = line; Log.i("IIAB-Ansible", "[Debian] " + outLine); // Funneled straight to Logcat! appendTail(tail, outLine); + lastOutputAtMs = android.os.SystemClock.elapsedRealtime(); mainHandler.post(() -> listener.onOutputLine(outLine)); } @@ -240,6 +252,19 @@ public void executeInContainer(Context context, String rootfsDir, String command }).start(); } + /** + * ADFA-5365: how long this launch has shown no sign of life, or {@code -1} when there is no + * signal to read — nothing was ever launched through this engine, so the caller has no progress + * fact and must fall back to its downtime rule. That is the orphan case: a proot this process + * did not start has no output stream we can watch. + * + * @param nowMs the same monotonic clock the stamps come from ({@code SystemClock.elapsedRealtime}). + */ + public long silentMs(long nowMs) { + final long last = lastOutputAtMs; + return last <= 0L ? -1L : Math.max(0L, nowMs - last); + } + /** Keep only the last {@link #TAIL_LIMIT} characters of the output. */ private static void appendTail(StringBuilder tail, String line) { tail.append(line).append('\n'); diff --git a/controller/app/src/main/java/org/iiab/controller/ServerController.java b/controller/app/src/main/java/org/iiab/controller/ServerController.java index bcf54323d..40c21f7a3 100644 --- a/controller/app/src/main/java/org/iiab/controller/ServerController.java +++ b/controller/app/src/main/java/org/iiab/controller/ServerController.java @@ -30,15 +30,10 @@ public class ServerController { private static final String TAG = "IIAB-ServerController"; private static final int CHECK_INTERVAL_MS = 3000; - /** - * ADFA-5103 / ADFA-5343a (D1): how long the services may be continuously observed down (proot - * present) before ensure-up escalates from "still coming up / pdsm will respawn it" to "stuck → - * relaunch". Timed from the service drop, not the proot's age (ADR-5343a): a mature proot whose - * dash-node blips stays well under this and self-heals via pdsm, while a boot — services down since - * the proot started — is still protected for this long (comfortably over the 3.5 s mid-boot window - * that got the earlier kill reverted, and over a normal boot-to-services time). - */ - private static final long SERVICE_DOWN_GRACE_MS = 20_000L; + // ADFA-5365: the service-downtime grace used to be declared here as well as in EnvironmentEnsure, + // whose javadoc claimed to be "the one canonical value both actuators use" while this copy sat + // beside it. Two constants for one threshold is how the two actuators come to disagree, so the + // copy is gone and decide() now supplies its own defaults to every caller. /** Activity-side callbacks the server lifecycle needs. */ public interface Host { @@ -227,9 +222,15 @@ public void startEnvironment() { org.iiab.controller.env.domain.ServerLiveness ll = lastLiveness; long servicesDownMs = (ll == null) ? -1L : ll.servicesDownMs(now, org.iiab.controller.env.domain.ServerLiveness.DEFAULT_FRESH_MS); + // ADFA-5365: a boot is judged on movement, not elapsed time. The progress signal is the + // engine that is streaming the boot; with no engine there is nothing to read and decide() + // falls back to the downtime rule. + PRootEngine eng = serverEngine; + long silentMs = (eng == null) ? -1L : eng.silentMs(now); org.iiab.controller.env.domain.EnvironmentEnsure.Action action = org.iiab.controller.env.domain.EnvironmentEnsure.decide( - envAlive, servicesAlive, servicesDownMs, SERVICE_DOWN_GRACE_MS); + envAlive, servicesAlive, ll != null && ll.booting(), + servicesDownMs, silentMs); switch (action) { case LAUNCH: activity.runOnUiThread(this::doLaunchEnvironment); diff --git a/controller/app/src/main/java/org/iiab/controller/env/ServerLifecycleReconciler.java b/controller/app/src/main/java/org/iiab/controller/env/ServerLifecycleReconciler.java index 7012ba0c5..3e7ebdb10 100644 --- a/controller/app/src/main/java/org/iiab/controller/env/ServerLifecycleReconciler.java +++ b/controller/app/src/main/java/org/iiab/controller/env/ServerLifecycleReconciler.java @@ -244,9 +244,13 @@ private void promoteOrTeardownWatchdog(Context ctx, boolean desiredUp) { private void offUiEnsureUp(Context ctx, ServerLiveness live, long now) { long downMs = live.servicesDownMs(now, ServerLiveness.DEFAULT_FRESH_MS); + // ADFA-5365: a boot is judged on movement, not elapsed time. The engine streaming this boot is + // the progress signal; with no engine (an orphan we did not launch) there is nothing to read + // and decide() falls back to the downtime rule that already recovers orphans. + PRootEngine eng = appScopedEngine; + long silentMs = (eng == null) ? -1L : eng.silentMs(now); EnvironmentEnsure.Action action = EnvironmentEnsure.decide( - live.processPresent(), live.servicesAnswering(), downMs, - EnvironmentEnsure.DEFAULT_SERVICE_DOWN_GRACE_MS); + live.processPresent(), live.servicesAnswering(), live.booting(), downMs, silentMs); if (action == EnvironmentEnsure.Action.KILL_AND_RELAUNCH) { EnvironmentProcess.killOrphan(ctx); } else if (action != EnvironmentEnsure.Action.LAUNCH) { diff --git a/controller/app/src/main/java/org/iiab/controller/env/domain/EnvironmentEnsure.java b/controller/app/src/main/java/org/iiab/controller/env/domain/EnvironmentEnsure.java index 00361f3b1..71a28d8bf 100644 --- a/controller/app/src/main/java/org/iiab/controller/env/domain/EnvironmentEnsure.java +++ b/controller/app/src/main/java/org/iiab/controller/env/domain/EnvironmentEnsure.java @@ -41,6 +41,19 @@ private EnvironmentEnsure() { */ public static final long DEFAULT_SERVICE_DOWN_GRACE_MS = 20_000L; + /** + * ADFA-5365: how long a boot may show no sign of life before it counts as stalled. + * + *

Deliberately a cap on silence, not on how long a boot takes. Device measurement: + * a slow device reaches its services in 37 s, and the longest gap between two guest output lines + * during that boot is 13 s. The two numbers age differently — total boot time grows with the + * content installed, so any cap on it is outgrown by the next device or the next library, which + * is how {@link #DEFAULT_SERVICE_DOWN_GRACE_MS} came to kill healthy boots at 20 s. The longest + * single quiet step does not grow with content, so a cap on it keeps holding. 60 s is 4.6x the + * worst gap measured, leaving room for a considerably slower device. + */ + public static final long DEFAULT_BOOT_SILENCE_GRACE_MS = 60_000L; + public enum Action { /** Nothing of ours is running — start it. */ LAUNCH, @@ -73,17 +86,41 @@ public enum Action { * @param serviceDownGraceMs how long "alive but not answering" is read as "still coming up / pdsm * will respawn it" rather than "stuck". */ - public static Action decide(boolean envAlive, boolean servicesAlive, long servicesDownMs, - long serviceDownGraceMs) { + public static Action decide(boolean envAlive, boolean servicesAlive, boolean booting, + long servicesDownMs, long silentMs) { + return decide(envAlive, servicesAlive, booting, servicesDownMs, DEFAULT_SERVICE_DOWN_GRACE_MS, + silentMs, DEFAULT_BOOT_SILENCE_GRACE_MS); + } + + /** + * ADFA-5365: the same escalation, with the thresholds injected so they can be varied in tests. + * + * @param booting this proot has never answered since it appeared ({@link + * ServerLiveness#booting()}) — it is coming up, not flapping. + * @param silentMs how long the launch has shown no sign of life, or negative when + * there is no such signal (an orphan this process did not launch). + * @param bootSilenceGraceMs how long a boot may be silent before it counts as stalled. + */ + public static Action decide(boolean envAlive, boolean servicesAlive, boolean booting, + long servicesDownMs, long serviceDownGraceMs, + long silentMs, long bootSilenceGraceMs) { if (!envAlive) { return Action.LAUNCH; } if (servicesAlive) { return Action.NOOP_HEALTHY; } - // Alive, services down. Kill only when we can be sure they have stayed down past the grace — - // never on an unknown downtime, because "cannot confirm it is stuck" must fall on the side of - // waiting (pdsm may still be respawning the service). + // Alive, services down — but that is two different situations wearing the same face, and one + // threshold cannot answer both. A boot has been down since the proot started, so its downtime + // IS its boot time; judging it against the flap grace is what killed healthy 37 s boots at 20 s. + // Judge a boot on whether it is still moving instead: the guest keeps talking while it comes up. + if (booting && silentMs >= 0) { + return silentMs < bootSilenceGraceMs ? Action.WAIT_BOOT_GRACE : Action.KILL_AND_RELAUNCH; + } + // It answered once and stopped (a flap), or there is no progress signal to read (an orphan we + // did not launch). Both are the case this grace was written for, unchanged. Kill only when we + // can be sure the services stayed down past it — never on an unknown downtime, because + // "cannot confirm it is stuck" must fall on the side of waiting (pdsm may still be respawning). if (servicesDownMs < 0 || servicesDownMs < serviceDownGraceMs) { return Action.WAIT_BOOT_GRACE; } diff --git a/controller/app/src/main/java/org/iiab/controller/env/domain/ServerLiveness.java b/controller/app/src/main/java/org/iiab/controller/env/domain/ServerLiveness.java index 62d1727c6..b6dc55a03 100644 --- a/controller/app/src/main/java/org/iiab/controller/env/domain/ServerLiveness.java +++ b/controller/app/src/main/java/org/iiab/controller/env/domain/ServerLiveness.java @@ -64,13 +64,15 @@ public enum Phase { private final boolean servicesAnswering; private final long observedAtMs; private final long servicesDownSinceMs; + private final boolean booting; private ServerLiveness(boolean processPresent, boolean servicesAnswering, long observedAtMs, - long servicesDownSinceMs) { + long servicesDownSinceMs, boolean booting) { this.processPresent = processPresent; this.servicesAnswering = servicesAnswering; this.observedAtMs = observedAtMs; this.servicesDownSinceMs = servicesDownSinceMs; + this.booting = booting; } /** @@ -87,7 +89,8 @@ private ServerLiveness(boolean processPresent, boolean servicesAnswering, long o public static ServerLiveness of(boolean processPresent, boolean servicesAnswering, long observedAtMs) { long downSince = (!servicesAnswering && processPresent && observedAtMs > 0) ? observedAtMs : 0L; - return new ServerLiveness(processPresent, servicesAnswering, observedAtMs, downSince); + return new ServerLiveness(processPresent, servicesAnswering, observedAtMs, downSince, + processPresent && !servicesAnswering); } /** @@ -121,13 +124,35 @@ public static ServerLiveness next(ServerLiveness prev, boolean processPresent, && Freshness.fresh(prev.observedAtMs, nowMs, freshnessMs); // no observation gap downSince = continuousStreak ? prev.servicesDownSinceMs : nowMs; } - return new ServerLiveness(processPresent, servicesAnswering, nowMs, downSince); + + // ADFA-5365: is this proot still coming up, or one that served and stopped? Carried the same + // way as the downtime clock and answered from the same observations, because it is the same + // kind of fact: what this stream has seen since this proot appeared. + // - no previous snapshot -> a proot we just launched (the actuators null this on launch) + // - previous says the proot was gone -> this is a new one, so it has not served yet + // - otherwise carry the answer forward, but only across a fresh streak: after an + // observation gap we cannot claim it never served, so it falls back to "not booting" + // and the caller keeps today's flap rule. + boolean stillBooting = processPresent && !servicesAnswering + && (prev == null + || !prev.processPresent + || (Freshness.fresh(prev.observedAtMs, nowMs, freshnessMs) && prev.booting)); + + return new ServerLiveness(processPresent, servicesAnswering, nowMs, downSince, stillBooting); } public boolean processPresent() { return processPresent; } public boolean servicesAnswering() { return servicesAnswering; } public long observedAtMs() { return observedAtMs; } + /** + * ADFA-5365: true while this proot has never answered since it appeared — it is coming up, not + * flapping. The distinction the escalation needs: a boot and a flap both read as "alive, not + * answering", but a boot legitimately takes as long as the device needs (37 s measured on a slow + * device, and longer as content grows) while a flap should be back in about 3 s. + */ + public boolean booting() { return booting; } + /** * How long the services have been continuously observed down (proot present), or {@code -1} when * that is not a fact to act on: the snapshot itself is stale (a background gap — never time a kill diff --git a/controller/app/src/test/java/org/iiab/controller/env/domain/EnvironmentEnsureTest.java b/controller/app/src/test/java/org/iiab/controller/env/domain/EnvironmentEnsureTest.java index 9889c4fc8..11fa6e48d 100644 --- a/controller/app/src/test/java/org/iiab/controller/env/domain/EnvironmentEnsureTest.java +++ b/controller/app/src/test/java/org/iiab/controller/env/domain/EnvironmentEnsureTest.java @@ -13,64 +13,135 @@ * {@link #anUnknownDowntimeIsNeverKilled}), and — the ADFA-5336 regression this delta fixes — a mature * proot whose dash-node just blipped must WAIT for pdsm's respawn, not be killed * ({@link #aMatureProotWhoseServiceJustDroppedWaitsForRespawn}). + * + *

ADFA-5365 adds the third: a boot and a flap are both "alive, not answering", and one threshold + * cannot serve both. The boot cases below are keyed on whether the boot is still moving, + * because a legitimate boot takes as long as the device and its content need — device-measured at + * 37 s, which the 20 s flap grace was killing. */ public class EnvironmentEnsureTest { private static final long GRACE = 20_000L; + private static final long BOOT_SILENCE = 60_000L; + + /** No progress signal to read — an orphan this process did not launch. */ + private static final long NO_SIGNAL = -1L; + + private static EnvironmentEnsure.Action flap(long servicesDownMs) { + return EnvironmentEnsure.decide(true, false, false, servicesDownMs, GRACE, + NO_SIGNAL, BOOT_SILENCE); + } + + private static EnvironmentEnsure.Action booting(long servicesDownMs, long silentMs) { + return EnvironmentEnsure.decide(true, false, true, servicesDownMs, GRACE, + silentMs, BOOT_SILENCE); + } + + // ---------------------------------------------------------------- unchanged behaviour @Test public void nothingRunningLaunches() { assertEquals(EnvironmentEnsure.Action.LAUNCH, - EnvironmentEnsure.decide(false, false, -1L, GRACE)); + EnvironmentEnsure.decide(false, false, false, NO_SIGNAL, GRACE, + NO_SIGNAL, BOOT_SILENCE)); } @Test public void aliveAndAnsweringIsANoOp() { // The redundant-call case: five of the six callers fire "ensure it is up" when it already is. - // servicesAlive short-circuits, so the downtime argument is irrelevant. + // servicesAlive short-circuits, so every clock argument is irrelevant. assertEquals(EnvironmentEnsure.Action.NOOP_HEALTHY, - EnvironmentEnsure.decide(true, true, -1L, GRACE)); + EnvironmentEnsure.decide(true, true, true, NO_SIGNAL, GRACE, 0L, BOOT_SILENCE)); } @Test public void aBootingProotIsLeftToFinish() { - // 3.5 s in, services not up yet — services have been down since the proot started, which is - // exactly the proot the earlier wiring killed. Under the grace → never touch it. - assertEquals(EnvironmentEnsure.Action.WAIT_BOOT_GRACE, - EnvironmentEnsure.decide(true, false, 3_500L, GRACE)); + // 3.5 s in, services not up yet — exactly the proot the earlier wiring killed. + assertEquals(EnvironmentEnsure.Action.WAIT_BOOT_GRACE, flap(3_500L)); } @Test public void aMatureProotWhoseServiceJustDroppedWaitsForRespawn() { - // The ADFA-5336 fix: a long-lived (mature) proot whose dash-node just died. Keyed on proot age - // this was an instant KILL_AND_RELAUNCH (age >> grace); keyed on SERVICE downtime it is a 2 s - // flap, well under the grace, so pdsm gets its ~3 s to respawn it. WAIT, do not kill. - assertEquals(EnvironmentEnsure.Action.WAIT_BOOT_GRACE, - EnvironmentEnsure.decide(true, false, 2_000L, GRACE)); + // The ADFA-5336 fix: a 2 s flap, well under the grace, so pdsm gets its ~3 s to respawn. + assertEquals(EnvironmentEnsure.Action.WAIT_BOOT_GRACE, flap(2_000L)); } @Test public void anUnknownDowntimeIsNeverKilled() { - // A stale or never-observed snapshot reports downtime < 0: we cannot prove the services have - // stayed down, so we must not kill — "cannot confirm it is stuck" falls on the side of waiting. - assertEquals(EnvironmentEnsure.Action.WAIT_BOOT_GRACE, - EnvironmentEnsure.decide(true, false, -1L, GRACE)); + // "Cannot confirm it is stuck" falls on the side of waiting. + assertEquals(EnvironmentEnsure.Action.WAIT_BOOT_GRACE, flap(NO_SIGNAL)); } @Test public void servicesDownPastTheGraceIsAStuckEnvironmentAndIsRelaunched() { - // Alive, services down far past the grace — pdsm could not bring them back. A proot cannot be - // re-entered, so recovery is to end it and bring up a fresh one. - assertEquals(EnvironmentEnsure.Action.KILL_AND_RELAUNCH, - EnvironmentEnsure.decide(true, false, 120_000L, GRACE)); + assertEquals(EnvironmentEnsure.Action.KILL_AND_RELAUNCH, flap(120_000L)); } @Test public void theGraceBoundaryKillsAtOrAfterIt() { - // Just under the grace waits; at the grace the services are considered stuck. + assertEquals(EnvironmentEnsure.Action.WAIT_BOOT_GRACE, flap(GRACE - 1)); + assertEquals(EnvironmentEnsure.Action.KILL_AND_RELAUNCH, flap(GRACE)); + } + + // ---------------------------------------------------------------- ADFA-5365 + + @Test + public void aSlowBootPastTheFlapGraceIsNotKilledWhileItIsStillTalking() { + // THE BUG. A device-measured boot: 37 s to its services, last output 2 s ago. Down for 37 s is + // far past the 20 s flap grace, and that is precisely what killed it at ~24 s, forever. + assertEquals(EnvironmentEnsure.Action.WAIT_BOOT_GRACE, booting(37_000L, 2_000L)); + } + + @Test + public void aBootIsNotKilledHoweverLongItTakesWhileItKeepsMoving() { + // Total boot time grows with the content installed, so it is not a thing to cap. Ten minutes + // in and still talking is a slow device doing real work, not a stuck one. + assertEquals(EnvironmentEnsure.Action.WAIT_BOOT_GRACE, booting(600_000L, 5_000L)); + } + + @Test + public void aBootThatHasGoneQuietPastTheSilenceGraceIsStuck() { + assertEquals(EnvironmentEnsure.Action.KILL_AND_RELAUNCH, booting(90_000L, 90_000L)); + } + + @Test + public void theSilenceBoundaryKillsAtOrAfterIt() { + assertEquals(EnvironmentEnsure.Action.WAIT_BOOT_GRACE, booting(999_000L, BOOT_SILENCE - 1)); + assertEquals(EnvironmentEnsure.Action.KILL_AND_RELAUNCH, booting(999_000L, BOOT_SILENCE)); + } + + @Test + public void theWorstMeasuredQuietStepIsComfortablyInsideTheSilenceGrace() { + // The longest gap between two guest lines during a real boot was 13 s on a slow device. + // If this ever fails, the grace is too tight for the devices we ship to. + assertEquals(EnvironmentEnsure.Action.WAIT_BOOT_GRACE, booting(30_000L, 13_000L)); + } + + @Test + public void aMatureEnvironmentIsNeverJudgedOnSilence() { + // A served environment produces no output at all — it is sitting in `tail -f /dev/null` — so + // its silence is unbounded and meaningless. Judging it on silence would kill every healthy + // box on the first blip. Only `booting` keeps that apart. + assertEquals(EnvironmentEnsure.Action.WAIT_BOOT_GRACE, + EnvironmentEnsure.decide(true, false, false, 2_000L, GRACE, + 3_600_000L, BOOT_SILENCE)); + } + + @Test + public void aBootWithNoProgressSignalFallsBackToTheDowntimeRule() { + // Cold start onto an orphaned proot: it looks like a boot (never seen answering) but this + // process never launched it, so there is no stream to watch. Orphan recovery must still work. + assertEquals(EnvironmentEnsure.Action.KILL_AND_RELAUNCH, booting(120_000L, NO_SIGNAL)); + assertEquals(EnvironmentEnsure.Action.WAIT_BOOT_GRACE, booting(2_000L, NO_SIGNAL)); + } + + @Test + public void theDefaultsAreTheOnesTheActuatorsGet() { + // Both actuators call the short form; a copy of these thresholds living anywhere else is how + // they came to disagree in the first place. assertEquals(EnvironmentEnsure.Action.WAIT_BOOT_GRACE, - EnvironmentEnsure.decide(true, false, GRACE - 1, GRACE)); + EnvironmentEnsure.decide(true, false, true, 37_000L, 2_000L)); assertEquals(EnvironmentEnsure.Action.KILL_AND_RELAUNCH, - EnvironmentEnsure.decide(true, false, GRACE, GRACE)); + EnvironmentEnsure.decide(true, false, false, 120_000L, NO_SIGNAL)); } } diff --git a/controller/app/src/test/java/org/iiab/controller/env/domain/ServerLivenessTest.java b/controller/app/src/test/java/org/iiab/controller/env/domain/ServerLivenessTest.java index 8eb76e846..f468c689d 100644 --- a/controller/app/src/test/java/org/iiab/controller/env/domain/ServerLivenessTest.java +++ b/controller/app/src/test/java/org/iiab/controller/env/domain/ServerLivenessTest.java @@ -1,6 +1,8 @@ package org.iiab.controller.env.domain; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import org.junit.Test; @@ -133,4 +135,58 @@ public void aGoneProotIsNotATrackedDowntime() { ServerLiveness gone = ServerLiveness.next(down, false, false, 4_000L, FRESH); assertEquals(-1L, gone.servicesDownMs(4_000L, FRESH)); } + + // ------------------------------------------------------- ADFA-5365: booting vs flapping + + @Test + public void aFreshlyLaunchedProotThatHasNotAnsweredIsBooting() { + // The actuators null the previous snapshot when they launch, so no history means "we just + // started this one". Down since it appeared, never seen answering -> a boot. + assertTrue(ServerLiveness.next(null, true, false, 1_000L, FRESH).booting()); + } + + @Test + public void aBootStaysABootAcrossTheWholeStartup() { + ServerLiveness l = ServerLiveness.next(null, true, false, 1_000L, FRESH); + for (long t = 4_000L; t <= 37_000L; t += 3_000L) { + l = ServerLiveness.next(l, true, false, t, FRESH); + assertTrue("stopped counting as a boot at " + t + "ms", l.booting()); + } + } + + @Test + public void onceItAnswersItIsNeverBootingAgain() { + // The whole point: after this, a service drop is a flap and must be judged on downtime, not + // on silence -- a served environment produces no output at all. + ServerLiveness booting = ServerLiveness.next(null, true, false, 1_000L, FRESH); + ServerLiveness served = ServerLiveness.next(booting, true, true, 4_000L, FRESH); + assertFalse(served.booting()); + + ServerLiveness dropped = ServerLiveness.next(served, true, false, 7_000L, FRESH); + assertFalse("a mature environment that dropped is a flap, not a boot", dropped.booting()); + } + + @Test + public void aReplacementProotStartsBootingAgain() { + // The old one died and a fresh one was launched: it has not served, whatever the old one did. + ServerLiveness served = ServerLiveness.next(null, true, true, 1_000L, FRESH); + ServerLiveness gone = ServerLiveness.next(served, false, false, 4_000L, FRESH); + assertTrue(ServerLiveness.next(gone, true, false, 7_000L, FRESH).booting()); + } + + @Test + public void anObservationGapDropsBackToTheDowntimeRule() { + // After a gap we cannot claim this proot never served, so it must not get the boot treatment. + // Not booting means the caller keeps today's flap rule, which is the safe fallback. + ServerLiveness booting = ServerLiveness.next(null, true, false, 1_000L, FRESH); + ServerLiveness afterGap = + ServerLiveness.next(booting, true, false, 1_000L + FRESH + 1, FRESH); + assertFalse(afterGap.booting()); + } + + @Test + public void anAbsentProotIsNeverBooting() { + assertFalse(ServerLiveness.next(null, false, false, 1_000L, FRESH).booting()); + assertFalse(ServerLiveness.of(false, false, NOW).booting()); + } } From ba410271e2737a399bb6e1423f165742a1693fec Mon Sep 17 00:00:00 2001 From: Luis-ADFA Date: Tue, 1 Sep 2026 04:52:42 -0600 Subject: [PATCH 2/2] ADFA-5365 fix(server-lifecycle): the boot progress fact belongs to the environment Reading the progress stamp off "my engine" meant a boot started by the foreground actuator and then backgrounded looked silent to the reconciler, which fell back to the downtime rule and killed it at 20s -- the very bug this ticket removes. There are two launch paths holding two different engines, so the fact cannot live on either one. EnvironmentProgress holds it once, app-scoped like ServerStateRepository, and is written only by the environment launches' own listeners so a module install streaming through the same engine class cannot make a stalled environment look alive. PRootEngine's per-instance copy is removed rather than kept alongside it. Clearing lives in EnvironmentControl.stop, symmetric with the launch stamp: three call sites stop the environment, and an invariant only one of them upholds rots. Device-verified: a boot backgrounded 12s in reaches UP with zero kills. --- .../java/org/iiab/controller/PRootEngine.java | 25 ------- .../org/iiab/controller/ServerController.java | 12 +-- .../controller/env/EnvironmentControl.java | 10 ++- .../controller/env/EnvironmentProgress.java | 75 +++++++++++++++++++ .../env/ServerLifecycleReconciler.java | 10 +-- .../controller/env/domain/ServerLiveness.java | 3 + 6 files changed, 99 insertions(+), 36 deletions(-) create mode 100644 controller/app/src/main/java/org/iiab/controller/env/EnvironmentProgress.java diff --git a/controller/app/src/main/java/org/iiab/controller/PRootEngine.java b/controller/app/src/main/java/org/iiab/controller/PRootEngine.java index b11b53180..91c28d576 100644 --- a/controller/app/src/main/java/org/iiab/controller/PRootEngine.java +++ b/controller/app/src/main/java/org/iiab/controller/PRootEngine.java @@ -43,14 +43,6 @@ public class PRootEngine { private volatile Process currentProcess; private volatile java.io.OutputStream processOutputStream; - /** - * ADFA-5365: when this launch last showed a sign of life, on the monotonic clock. Stamped at - * launch and on every guest line, so "has the boot stalled" is answerable without timing the - * boot as a whole — total boot time grows with the content installed, the gap between two lines - * does not. Per instance, not shared: the actuators hold one engine per launch. - */ - private volatile long lastOutputAtMs; - public interface OutputListener { void onOutputLine(String line); @@ -210,9 +202,6 @@ public void executeInContainer(Context context, String rootfsDir, String command // concurrent proot call can't make us return on the wrong process. Process proc = pb.start(); currentProcess = proc; - // ADFA-5365: the launch itself is the first sign of life, so a boot that never says - // anything is still measured from a real start rather than reading as silent forever. - lastOutputAtMs = android.os.SystemClock.elapsedRealtime(); // --- STREAM LIVE LOGS --- BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream())); @@ -224,7 +213,6 @@ public void executeInContainer(Context context, String rootfsDir, String command final String outLine = line; Log.i("IIAB-Ansible", "[Debian] " + outLine); // Funneled straight to Logcat! appendTail(tail, outLine); - lastOutputAtMs = android.os.SystemClock.elapsedRealtime(); mainHandler.post(() -> listener.onOutputLine(outLine)); } @@ -252,19 +240,6 @@ public void executeInContainer(Context context, String rootfsDir, String command }).start(); } - /** - * ADFA-5365: how long this launch has shown no sign of life, or {@code -1} when there is no - * signal to read — nothing was ever launched through this engine, so the caller has no progress - * fact and must fall back to its downtime rule. That is the orphan case: a proot this process - * did not start has no output stream we can watch. - * - * @param nowMs the same monotonic clock the stamps come from ({@code SystemClock.elapsedRealtime}). - */ - public long silentMs(long nowMs) { - final long last = lastOutputAtMs; - return last <= 0L ? -1L : Math.max(0L, nowMs - last); - } - /** Keep only the last {@link #TAIL_LIMIT} characters of the output. */ private static void appendTail(StringBuilder tail, String line) { tail.append(line).append('\n'); diff --git a/controller/app/src/main/java/org/iiab/controller/ServerController.java b/controller/app/src/main/java/org/iiab/controller/ServerController.java index 40c21f7a3..32b97457a 100644 --- a/controller/app/src/main/java/org/iiab/controller/ServerController.java +++ b/controller/app/src/main/java/org/iiab/controller/ServerController.java @@ -222,11 +222,10 @@ public void startEnvironment() { org.iiab.controller.env.domain.ServerLiveness ll = lastLiveness; long servicesDownMs = (ll == null) ? -1L : ll.servicesDownMs(now, org.iiab.controller.env.domain.ServerLiveness.DEFAULT_FRESH_MS); - // ADFA-5365: a boot is judged on movement, not elapsed time. The progress signal is the - // engine that is streaming the boot; with no engine there is nothing to read and decide() - // falls back to the downtime rule. - PRootEngine eng = serverEngine; - long silentMs = (eng == null) ? -1L : eng.silentMs(now); + // ADFA-5365: a boot is judged on movement, not elapsed time. The progress fact belongs to + // the environment, not to whichever actuator launched it, so both read the same answer; + // with no signal (nothing launched in this process) decide() falls back to the downtime rule. + long silentMs = org.iiab.controller.env.EnvironmentProgress.silentMs(now); org.iiab.controller.env.domain.EnvironmentEnsure.Action action = org.iiab.controller.env.domain.EnvironmentEnsure.decide( envAlive, servicesAlive, ll != null && ll.booting(), @@ -273,10 +272,13 @@ private void doLaunchEnvironment() { createFakeSysData(rootfsDir); if (serverEngine != null) serverEngine.killProcess(); serverEngine = new PRootEngine(); + org.iiab.controller.env.EnvironmentProgress.launched(); // ADFA-5365: first sign of life String startCmd = "/usr/bin/env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin bash -lc '/usr/local/bin/pdsm start && tail -f /dev/null'"; serverEngine.executeInContainer(activity, rootfsDir.getAbsolutePath(), startCmd, new PRootEngine.OutputListener() { @Override public void onOutputLine(String line) { + // ADFA-5365: whoever launched it, the environment's progress lands in one place. + org.iiab.controller.env.EnvironmentProgress.alive(); activity.runOnUiThread(() -> host.addToLog("[Server] " + line)); java.util.regex.Matcher m = PDSM_SVC.matcher(line); if (m.find()) { diff --git a/controller/app/src/main/java/org/iiab/controller/env/EnvironmentControl.java b/controller/app/src/main/java/org/iiab/controller/env/EnvironmentControl.java index 4629aa917..927117f0b 100644 --- a/controller/app/src/main/java/org/iiab/controller/env/EnvironmentControl.java +++ b/controller/app/src/main/java/org/iiab/controller/env/EnvironmentControl.java @@ -52,6 +52,10 @@ public interface LineSink { void onLine(String line); } * that no service is left writing). Runs on the PRootEngine worker thread. */ public static void stop(Context ctx, final LineSink log, final Runnable onDone) { + // ADFA-5365: stopping ends the environment, so its progress stamp ends with it — here rather + // than at the call sites, so every stop clears it. There are three (the reconciler's teardown + // and DeepOp's backup and restore) and an invariant only one of them upholds is one that rots. + EnvironmentProgress.cleared(); new PRootEngine().executeInContainer(ctx.getApplicationContext(), rootfs(ctx).getAbsolutePath(), CMD_STOP, new PRootEngine.OutputListener() { @Override public void onOutputLine(String line) { if (log != null) log.onLine("[PDSM Stop] " + line); } @@ -77,9 +81,13 @@ public static PRootEngine start(Context ctx, final LineSink log) { File rootfsDir = rootfs(ctx); createFakeSysData(rootfsDir); PRootEngine engine = new PRootEngine(); + EnvironmentProgress.launched(); // ADFA-5365: the launch is the environment's first sign of life engine.executeInContainer(ctx.getApplicationContext(), rootfsDir.getAbsolutePath(), CMD_START, new PRootEngine.OutputListener() { - @Override public void onOutputLine(String line) { if (log != null) log.onLine("[Server] " + line); } + @Override public void onOutputLine(String line) { + EnvironmentProgress.alive(); // ADFA-5365: this boot is still moving + if (log != null) log.onLine("[Server] " + line); + } @Override public void onProcessExit(int exitCode) { if (log != null) log.onLine("[Server] engine exit " + exitCode); } @Override public void onError(String error) { if (log != null) log.onLine("[Server] error " + error); } }); diff --git a/controller/app/src/main/java/org/iiab/controller/env/EnvironmentProgress.java b/controller/app/src/main/java/org/iiab/controller/env/EnvironmentProgress.java new file mode 100644 index 000000000..14995a0ec --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/env/EnvironmentProgress.java @@ -0,0 +1,75 @@ +/* + * ============================================================================ + * Name : EnvironmentProgress.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : ADFA-5365. When did the environment last show a sign of life? + * ============================================================================ + */ +package org.iiab.controller.env; + +import android.os.SystemClock; + +/** + * The environment's last sign of life, in one place. + * + *

Why this is not held by the engine. The fact belongs to the environment, not to + * whichever actuator happens to hold a reference to the {@code PRootEngine} that started it. There + * are two launch paths — the foreground {@code ServerController} and the app-scoped reconciler — and + * they hold different engines. Reading the stamp off "my engine" means a boot started in the + * foreground and then backgrounded mid-way looks silent to the reconciler, which falls back to the + * downtime rule and kills the boot at 20 s: precisely the bug ADFA-5365 exists to remove. One fact, + * one owner, both actuators reading the same answer regardless of who launched. + * + *

Only the environment writes here. The stamp is fed from the environment launches' own + * output listeners, not from {@code PRootEngine} itself, so a module install streaming through the + * same engine class cannot make a stalled environment look alive. + * + *

App-scoped and static, mirroring {@code ServerStateRepository}: the environment outlives every + * Activity, so the fact about it has to as well. Its lifetime is the process — after a restart there + * is no stamp, which reads as "no signal" and returns the caller to the downtime rule, the same + * fail-safe an orphaned proot already gets. + */ +public final class EnvironmentProgress { + + /** Monotonic stamp of the last sign of life, or {@code 0} for "no signal". */ + private static volatile long lastSignOfLifeMs = 0L; + + private EnvironmentProgress() { + } + + /** + * A fresh environment launch. The launch itself counts as the first sign of life, so an + * environment that never says anything is still measured from a real start rather than reading + * as silent since the beginning of time. + */ + public static void launched() { + lastSignOfLifeMs = SystemClock.elapsedRealtime(); + } + + /** The environment produced output: it is still moving. */ + public static void alive() { + lastSignOfLifeMs = SystemClock.elapsedRealtime(); + } + + /** + * The environment is gone (a stop, or a teardown). Drops the stamp so the next decision has no + * stale progress to trust — a signal from a proot that no longer exists is not a signal. + */ + public static void cleared() { + lastSignOfLifeMs = 0L; + } + + /** + * How long the environment has shown no sign of life, or {@code -1} when there is no signal — + * nothing was launched in this process, or it has been cleared. Callers treat {@code -1} as + * "no progress fact here" and fall back to their downtime rule. + * + * @param nowMs the same monotonic clock the stamps come from + * ({@code SystemClock.elapsedRealtime}). + */ + public static long silentMs(long nowMs) { + final long last = lastSignOfLifeMs; + return last <= 0L ? -1L : Math.max(0L, nowMs - last); + } +} diff --git a/controller/app/src/main/java/org/iiab/controller/env/ServerLifecycleReconciler.java b/controller/app/src/main/java/org/iiab/controller/env/ServerLifecycleReconciler.java index 3e7ebdb10..2cbd9a905 100644 --- a/controller/app/src/main/java/org/iiab/controller/env/ServerLifecycleReconciler.java +++ b/controller/app/src/main/java/org/iiab/controller/env/ServerLifecycleReconciler.java @@ -244,11 +244,11 @@ private void promoteOrTeardownWatchdog(Context ctx, boolean desiredUp) { private void offUiEnsureUp(Context ctx, ServerLiveness live, long now) { long downMs = live.servicesDownMs(now, ServerLiveness.DEFAULT_FRESH_MS); - // ADFA-5365: a boot is judged on movement, not elapsed time. The engine streaming this boot is - // the progress signal; with no engine (an orphan we did not launch) there is nothing to read - // and decide() falls back to the downtime rule that already recovers orphans. - PRootEngine eng = appScopedEngine; - long silentMs = (eng == null) ? -1L : eng.silentMs(now); + // ADFA-5365: a boot is judged on movement, not elapsed time. The progress fact belongs to the + // environment, so a boot started by the foreground actuator and then backgrounded is still + // seen as moving here; with no signal (an orphan we did not launch, or a fresh process) + // decide() falls back to the downtime rule that already recovers orphans. + long silentMs = EnvironmentProgress.silentMs(now); EnvironmentEnsure.Action action = EnvironmentEnsure.decide( live.processPresent(), live.servicesAnswering(), live.booting(), downMs, silentMs); if (action == EnvironmentEnsure.Action.KILL_AND_RELAUNCH) { diff --git a/controller/app/src/main/java/org/iiab/controller/env/domain/ServerLiveness.java b/controller/app/src/main/java/org/iiab/controller/env/domain/ServerLiveness.java index b6dc55a03..82edf8864 100644 --- a/controller/app/src/main/java/org/iiab/controller/env/domain/ServerLiveness.java +++ b/controller/app/src/main/java/org/iiab/controller/env/domain/ServerLiveness.java @@ -133,6 +133,9 @@ public static ServerLiveness next(ServerLiveness prev, boolean processPresent, // - otherwise carry the answer forward, but only across a fresh streak: after an // observation gap we cannot claim it never served, so it falls back to "not booting" // and the caller keeps today's flap rule. + // That fallback is deliberately sticky for the life of this proot: once a gap has cost us the + // answer, no later tick can honestly recover it, so it stays false until the proot is replaced. + // The same gap also resets the downtime clock, so the flap rule starts its grace from scratch. boolean stillBooting = processPresent && !servicesAnswering && (prev == null || !prev.processPresent