Skip to content

ADFA-5343 feat(server-lifecycle): Phase 4 — the app-scoped reconciler owns the lifecycle (own tick, set-desired toggle, cluster collapse) - #501

Merged
luisguzman-adfa merged 9 commits into
mainfrom
feat/ADFA-5343-phase0-server-liveness
Aug 31, 2026
Merged

luisguzman-adfa merged 9 commits into
mainfrom
feat/ADFA-5343-phase0-server-liveness

Conversation

@luisguzman-adfa

Copy link
Copy Markdown
Collaborator

What

Phase 4 of the server-lifecycle redesign (ADR-5343 §7; ADR-5343a §11–14) — the culmination: the
reconciler becomes the single, app-scoped owner of the server lifecycle, and the scattered boot
cluster + dead transition state are deleted. Base is main (Phases 0–3 already merged).

4a — app-scoped tick + off-UI actuator. The reconciler gains its own 3 s tick (foreground +
background) and an off-UI EnvironmentControl.start, so it keeps/brings the box up without a
foreground Activity.

4b — reconciler owns WatchdogService promotion. Promotion moves from 3 Activity sites to 1,
started on desired=UP for background/Doze survival and torn down on desired=DOWN (FGS +
wakelock + battery-opt exemption; loopback probe is Doze-immune).

4c — toggle becomes set-desired; reconciler owns STOP. Open app = setUserWantsOn(true),
Settings turn-off = setUserWantsOn(false); the reconciler stops on desired=DOWN gated to
holder==NONE, so a deep op's own quiesce is not double-stopped.

4d — collapse the cluster. Deletes the autostart / install-success / BackupRestore boots (booting
routes through desired now), the foreground poll + Actuator bridge (one tick is the sole driver),
and the dead transition flags; slims ServerController to connectivity. Retry is reformed into a
reconciler-aware recover action (setUserWantsOn(true) + immediate reconcile); user nav (See
progress / View / Recover) is preserved. The recovery boot (:394) is deferred to Phase 5.

Why

The server lifecycle had overlapping states and multiple sources of truth for the lack of a single
process-scoped owner. Phase 4 lands that owner and deletes the scaffolding it replaces.

Reduction (ADR §8 scorecard, before → after)

Lifecycle owners 4→1 · liveness sources 4→1 · boot actuation call-sites ~16→1 · stop emitters 6→1 ·
transition/guard flags ~15→2 · distinct server states 12→5 (0 compensation) · copy-pasted apiReady
reboot loops 4→0 · bespoke post-op reboots →0. Every §8 target is met on the active path; the only
residue is deliberately deferred (the recovery chain → Phase 5; the <1.2.0 STOPPED rebuild → §11).

Verification

Full device regression matrix, all green on OnePlus 7T (a026a310): open=boot, rotation (no
double-boot), user turn-off (stop + no background), background-restart-stays-off (D3), server flap
(no wrongful kill), backup/restore/clone (no double-stop, return on release), dashboard rebuild
(LIVE defer, no relaunch), fresh-install auto-boot, unplugged deep-Doze flap re-drive off-UI, and
ungraceful-kill recovery (orphan reclaim). :app:testDebugUnitTest + :app:lintDebug green; the
pure decisions are unit-tested. ADFA-5336 (server flap) is fixed and device-verified.

Follow-ups

  • Phase 5 (stacked next): recovery-verdict decouple + InstallGuard session token (ADFA-5330);
    deletes the remaining :394 recovery residue.
  • Dashboard/rebuild + php-fpm items tracked in ADR-5343a §10/§12.

luisguzman-adfa and others added 9 commits August 30, 2026 10:36
…ck + off-UI actuator

The reconciler gains its OWN tick, so it can bring the box up / re-drive a flap with no
foreground Activity - removing the Phase-2/3 'box returns needs a foreground Activity'
limit. Additive and mutually exclusive with the existing foreground path; the toggle,
autostart, and ServerController.doLaunchEnvironment are UNTOUCHED (per the approved order,
they stay as the proven foreground boot until 4d, after the app-scoped actuator is
device-verified).

- EnvironmentControl.start(ctx, log): the OFF-UI boot - createFakeSysData +  in a fresh app-scoped PRootEngine returned to the caller, minus
  the Activity-UI callbacks. The reconciler HOLDS the engine (the process-scoped owner
  the ADR §1.1 root cause needs).
- ServerLifecycleReconciler: a Handler tick every 3s while the process is alive. It
  STANDS DOWN while an Activity is foregrounded (actuator != null - the Activity poll +
  bridge drive) and only takes over when backgrounded (actuator == null): captures one
  ServerLiveness, publishes ServerStateRepository, and actuates off-UI via
  EnvironmentControl.start, gated by EnvironmentEnsure (idempotent; relaunch only a stuck
  past-grace proot) and deferred for a self-restarting holder (DASHBOARD). Downtime clock
  reset after a launch so the fresh proot gets full grace.
- EnvironmentEnsure.DEFAULT_SERVICE_DOWN_GRACE_MS: the one canonical grace both actuators
  use (ServerController's private copy unifies in 4d).
- IIABApplication starts the tick once.

No double-boot: the tick and the foreground path are mutually exclusive on actuator==null,
and EnvironmentEnsure's /proc check guards the transition window. 4a limitation: the
background tick runs only while WatchdogService is already up (box booted in foreground);
cold-background promotion is 4b. ADR-5343a §13 records the tick/service cycle.

Scorecard: 4a is net-additive by design (builds the owner's tick); the reduction lands at
4d (delete poll + autostart cluster + dead flags). Pure decisions (EnvironmentEnsure,
ServerReconcile) are already unit-tested; the tick is impure.

Verified: :app:testDebugUnitTest + :app:lintDebug BUILD SUCCESSFUL. Device-only (4a gate,
per review): launch still boots (autostart, unchanged); a background flap recovers with NO
foreground Activity - test on OnePlus + HMD (OEM background-survival differs).

Rollback: revert this commit (foreground poll + bridge return; nothing else depended on it).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…Service promotion

The reconciler becomes the ONE promoter of WatchdogService, driven by desired: start it on
desired=UP (the foreground service + wakelock keep the process alive so the app-scoped tick
survives Doze and re-drives a flap with no Activity), tear it down on desired=DOWN. Moves
promotion from 3 Activity-Host sites (via ServerController's 2 calls) to one place.

- WatchdogService: process-scoped RUNNING + isRunning(); startWatchdog is idempotent (a repeat
  ACTION_START re-affirms startForeground but does NOT re-acquire the hardware locks - no leak);
  onDestroy clears RUNNING.
- ServerLifecycleReconciler.promoteOrTeardownWatchdog(ctx, desiredUp): edge-detected via
  WatchdogService.isRunning() (no reconciler-side flag; self-corrects a START_STICKY-revived
  service), called from both observe() (foreground) and the background tick. targetSdk 28 allows
  starting a foreground service from the background (API-31 restriction does not apply; revisit if
  targetSdk is raised).
- ServerController: drop host.enableSystemProtection()/disableSystemProtection() from the boot and
  stop paths - the reconciler promotes from desired now (setWatchdogEnable stays as the intent).
  The now-dead Host enable/disableSystemProtection methods are left for 4d deletion.

Scope held to promotion (your call): NO reconciler STOP and NO toggle change here - those are
coupled and land together in 4c with their own verification; the old turn-off (ServerController
inline stop -> setWatchdogEnable(false) -> reconciler tears the watchdog down) still works in 4b.
Battery: 3s cadence unchanged; idle back-off tracked as a measured follow-up (ADR-5343a §14).
foregroundServiceType already 'specialUse' (correct at targetSdk 28) - no manifest change.

Reduction: WatchdogService promoters 3 -> 1; no new flag (uses the service's own RUNNING).

Verified: :app:testDebugUnitTest + :app:lintDebug BUILD SUCCESSFUL. Device-only (the key 4b gate):
unplugged-stationary Doze - box up, background, unplug, let Doze enter, induce a flap, confirm the
reconciler-promoted watchdog survives and the tick recovers off-UI, on OnePlus + HMD.

Rollback: revert this commit (promotion returns to the Activity-Host calls).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…ed; reconciler owns STOP

The user button stops being a start-XOR-stop-on-a-cache and becomes set-desired; the
reconciler honors a turn-off by stopping the box itself. Coupled with the toggle
conversion so there is no double-stop and no broken intermediate.

- LibraryActivity.startServer -> setUserWantsOn(true); turnOffK2Go -> setUserWantsOn(false)
  (drops the inline handleServerLaunchClick stop). The turn-off close scene stays
  observer-driven (closing && !alive -> onClosedReady), fed by the reconciler's stop.
- ServerReconcile.shouldStop(intent, holderIsNone) = intent==STOP && holderIsNone: the
  reconciler stops only a plain user turn-off (holder NONE); a deep op holds a STOPPED-class
  lock and quiesced the box itself, so the reconciler NOOPs - no double-stop (your condition).
  LIVE holders keep desired UP, so never a STOP.
- ServerLifecycleReconciler: setUserWantsOn (the set-desired API), and actuateStop -> graceful
  EnvironmentControl.stop + killOrphan so the box reaches phase DOWN, serialized by
  reconcilerStopping (subsumes ServerController.stopping, deleted in 4d). Wired into both
  observe() (foreground) and the background tick, gated by shouldStop.
- ServerController: removed the now-dead inline-stop else branch of handleServerLaunchClick
  (all other callers are boot-gated on !alive, verified) + its orphaned rootfsDir.
  handleServerLaunchClick is boot-only now for the autostart cluster; 4d deletes it.

Dead after this (for 4d): ServerController.stopping (reads always false), the Host
onShutdownProgress/onShutdownComplete/startExitPulse callbacks. UX: the off-UI stop loses the
per-service shutdown line; the close scene keeps its generic 'shutting down' + alive-observer close.

Reduction: lifecycle stop owners -> 1 (reconciler); removed the bespoke inline stop; +1 pure
predicate (shouldStop), reconcilerStopping subsumes ServerController.stopping.

Verified: :app:testDebugUnitTest + :app:lintDebug BUILD SUCCESSFUL (shouldStop unit-tested).
Device-only (4c gate): turn-off now performed by the reconciler (graceful stop + box reaches
DOWN, close scene finishes); and a deep op (backup/restore/clone) does NOT trigger a double-stop
(holder != NONE -> reconciler NOOPs while the op quiesces synchronously).

Rollback: revert this commit (button returns to handleServerLaunchClick start/stop).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…er; reform Retry; keep nav

Collapse the boot-owner cluster onto the reconciler (desired-driven), classified:

DELETE (server-state scaffolding the reconciler replaces):
- LibraryActivity autostart boot (:413) + its AUTOSTART_DELAY_MS constant. On a normal
  launch the reconciler boots from desired=UP (userWantsOn, persisted the last time the
  server ran) via its tick + foreground observe - no bespoke postDelayed start.
- LibraryActivity install-success boot (:346): install SUCCESS now sets userWantsOn=true
  (route install through desired - the piece Phase 3 deferred here) so the reconciler
  boots; the bespoke handleServerLaunchClick is gone.
- BackupRestoreFragment.startReturnToHome boot: redundant - DeepOpService.finishJob
  already set desired=UP on release (Phase 3A); the fragment only waits for apiReady then
  goes Home.

RE-FORM (not delete) - Retry, the user's last-defense button:
- LibraryActivity.startServer = setUserWantsOn(true) + reconciler.requestReconcileNow()
  (act now, not on the next tick). A set-desired + nudge, never a raw start/stop toggle.
  ServerLifecycleReconciler.requestReconcileNow(): boot via the foreground actuator if
  registered, else nudge the tick. (Wedged content-service Retry / kiwix = ADFA-4842,
  untouched.)

PRESERVE - user navigation, untouched: See progress (install/clone), View (clone
openCloneTab), Recover (H_DAMAGED), Install system (H_NO_LIBRARY).

Not in 4d-1 (kept alive): handleServerLaunchClick now has a single caller - the recovering
boot (LibraryActivity:394) - which, with doLaunchEnvironment + ensuring, is deferred to
Phase 5's recovery redesign (scorecard credits those to Phase 5, not 4d). The poll +
bridge + dead flags are 4d-2 / 4d-3.

Behavior: launch-boot is now desired-gated - a user who turned the server off and
relaunches stays off (the old autostart booted regardless of intent, the D3 bug);
post-install auto-boots because install sets userWantsOn=true.

Verified: :app:testDebugUnitTest + :app:lintDebug BUILD SUCCESSFUL. Device-only (the
critical 4d-1 gate): COLD LAUNCH still boots the box - via the reconciler, not the
autostart; fresh full install auto-boots; backup/restore returns to a live Home; Retry
acts immediately when a start failed.

Rollback: revert this commit (autostart + install/BackupRestore boots return).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…t-desired-UP

Behavior correction to 4d-1. Deleting the autostart removed 'open the app = boot the
box' (the pre-4d-1 autostart did that on every open). Restore it, but as set-desired,
not the raw autostart: on a FRESH launch (savedInstanceState == null) of an installed
system, LibraryActivity.onCreate sets userWantsOn=true -> desired=UP -> the reconciler
boots. Gated to a fresh launch so a rotation/config-change recreate does not re-power-on.

Final model:
- open app (foreground onCreate, fresh) = power-on -> boot;
- Settings turn-off = setUserWantsOn(false) = stop + no background;
- background process-restart after a turn-off (no foreground Activity, so no power-on
  gesture) = stays off. That last case is the real D3 the desired-gate protects.

Re-verify (corrected Check 2): a user OPEN boots; a background-restart after off stays
off. Checks 1/3/4/5 unchanged (cold launch boots, fresh install boots, backup/restore
returns live, Retry acts now).

Verified: :app:testDebugUnitTest + :app:lintDebug BUILD SUCCESSFUL.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…er to one tick

The reconciler tick becomes the SINGLE driver, foreground and background - the one
liveness capture, the one publisher, the one actuator. Net reduction: the second poll,
the foreground bridge, and the dual liveness-capture are gone.

DELETE:
- ServerController.checkServerStatus (the server-liveness poll); the runnable keeps only
  updateConnectivityStatus (Wi-Fi/hotspot LEDs).
- The bridge: reconciler Actuator interface + setActuator/clearActuator + observe(), and
  ServerController implements Actuator / ensureServerUp / the onResume/onPause
  registration.
- The tick's actuator==null stand-down: it now runs in foreground too (mutually-exclusive
  gating no longer needed - there is no other driver).
- Dead/migrated: ServerController currentTargetUrl + getCurrentTargetUrl (no callers),
  updateServerAlive + serverUpSinceMs (analytics migrated to the tick), reconciler
  lastLiveness field + getter, the now-unused BoxEndpoints/Operation imports.

RE-POINT to the published state (no poll):
- LibraryActivity.isServerStarting -> reconciler.lastDesiredUp() && !alive (the header's
  'Starting' reads the reconciler, not the retired targetServerState). startServer no
  longer sets targetServerState (the poll that cleared it is gone; it would stick and
  disable Retry). requestReconcileNow posts the tick (the one actuator).
- Server-uptime analytics (logServerStarted/Stopped) fire from the tick on an alive
  transition.

Not deleted (Phase 5): ServerController.startEnvironment/doLaunchEnvironment/ensuring +
handleServerLaunchClick + lastLiveness/livenessLock survive for the single recovery caller
(LibraryActivity:394). With the poll gone, that path's lastLiveness stays null so its
EnvironmentEnsure only LAUNCH/WAIT (never KILL); the tick owns kill+relaunch for everything
else - recovery's kill path is the Phase-5 recovery redesign. Dead flags
(isNegotiating/targetServerState/onShutdown*) + slim ServerController are 4d-3.

Verified: :app:testDebugUnitTest + :app:lintDebug BUILD SUCCESSFUL.
Device-only: (1) foreground status UI runs at the tick cadence (3s) - not slow/stale;
(2) 4d-1 model holds - open=boot, Settings turn-off=stop+no-background, background-restart
after off stays off, Retry immediate, backup/restore + fresh-install-hand-off return live;
(3) cold launch boots via the reconciler (no poll). Boot screen shows generic 'Starting'
(off-UI boot has no per-service line) - noted.

Rollback: revert this commit (poll + bridge return).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…ansition flags

Final cleanup: remove the monitor/actuator scaffolding the reconciler made dead. Each was
verified to have zero real callers before deletion (only the interface decls + impls, or
comments):

- isNegotiating: Host method + LibraryActivity field/impl + the two Setup impls. Its sole
  caller was checkServerStatus, deleted in 4d-2 -> never invoked, and the field was never
  written (always false).
- stopping (ServerController): field + isStopping() + the two recovery-chain guards + the
  canStartServer term. No writer since 4c removed the inline stop -> always false.
- onShutdownProgress / onShutdownComplete / startExitPulse (Host + impls): only callers were
  the inline stop, deleted in 4c. The turn-off close is driven by the ServerStateRepository
  observer (closing && !alive) + the 120s safety, so onShutdownComplete was redundant.
- targetServerState dead copies in SetupProgressActivity + SetupLibraryActivity: fields
  always null; getters now return null, setters no-op (the Host methods stay - LibraryActivity's
  copy is live for the recovery handleServerLaunchClick, Phase 5).

Also now dead but NOT in this commit's scope (surfaced for your call): Host
enableSystemProtection/disableSystemProtection + their impls - 4b orphaned them (the
reconciler promotes WatchdogService now). refreshServerUi stays (called by the recovery
handleServerLaunchClick, :347/:355 -> Phase 5).

Verified: :app:testDebugUnitTest + :app:lintDebug BUILD SUCCESSFUL. 4d-3 deletes only dead
code, so its device-verify is a 'nothing regressed' pass of the full matrix.

Rollback: revert this commit.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
… dead blocks

Both verified genuinely unreferenced before deletion:

- Host.enableSystemProtection/disableSystemProtection + the 3 impls (LibraryActivity,
  SetupProgressActivity, SetupLibraryActivity): dead since 4b, when the reconciler took over
  WatchdogService promotion (grep found zero invocations - only the interface decls + impls).
  Removed the interface methods, the 3x2 impls, and LibraryActivity's now-orphaned
  WatchdogService import.
- The orphaned liveness poller the ADR named for deletion: HttpServerReachability +
  DashboardStatusViewModel + DashboardStatusViewModelFactory. Fully self-referential (the
  Factory constructed the VM + reachability; nothing constructed the Factory) - never wired to
  any screen. All 3 files deleted.

This clears the two residual-dead-code rows from the final scorecard. What remains is the
deliberately-deferred Phase-5 residue only (recovery :394 + handleServerLaunchClick/
doLaunchEnvironment/ensuring/targetServerState@Library) and the <1.2.0 STOPPED rebuild path.

Verified: :app:testDebugUnitTest + :app:lintDebug BUILD SUCCESSFUL. Dead-code only - no
device-verify needed.

Rollback: revert this commit (restores the trio + the protection methods).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@luisguzman-adfa
luisguzman-adfa merged commit 3350c32 into main Aug 31, 2026
3 checks passed
@luisguzman-adfa
luisguzman-adfa deleted the feat/ADFA-5343-phase0-server-liveness branch August 31, 2026 03:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant