Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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 <b>continuously observed down</b> (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 {
Expand Down Expand Up @@ -227,9 +222,14 @@ 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 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, servicesDownMs, SERVICE_DOWN_GRACE_MS);
envAlive, servicesAlive, ll != null && ll.booting(),
servicesDownMs, silentMs);
switch (action) {
case LAUNCH:
activity.runOnUiThread(this::doLaunchEnvironment);
Expand Down Expand Up @@ -272,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()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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); }
Expand All @@ -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); }
});
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
*
* <p><b>Why this is not held by the engine.</b> The fact belongs to <em>the environment</em>, 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.
*
* <p><b>Only the environment writes here.</b> 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.
*
* <p>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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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 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(), 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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,19 @@ private EnvironmentEnsure() {
*/
public static final long DEFAULT_SERVICE_DOWN_GRACE_MS = 20_000L;

/**
* ADFA-5365: how long a <b>boot</b> may show no sign of life before it counts as stalled.
*
* <p>Deliberately a cap on <em>silence</em>, 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,
Expand Down Expand Up @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand All @@ -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);
}

/**
Expand Down Expand Up @@ -121,13 +124,38 @@ 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.
// 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
|| (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
Expand Down
Loading
Loading