From 9414a49e7d74406e7f6d75d1a769dc4784edbdc6 Mon Sep 17 00:00:00 2001 From: "Luis Guzman (AppDevForAll)" Date: Wed, 12 Aug 2026 21:16:26 -0600 Subject: [PATCH 1/6] ADFA-4895 fix(download): read aria2's exit code instead of discarding it, and ask aria2 to survive a bad link Every non-zero exit produced the same sentence - "Aria2c native process failed with code N" - so a full disk, a missing mirror and a dropped Wi-Fi were one event, and nothing downstream could tell which of them was worth trying again. Retry, resume and any honest report to the user all need that distinction first, which is why it lands before them. - Aria2Exit (pure, unit-tested) classifies the exit code: transient, stalled, permanent, or unknown. It describes and does not decide - the retry policy belongs to whoever owns the download, and keeping it out lets the rootfs and content paths choose differently from one reading. aria2's own code 1 is "unknown error" and stays UNKNOWN rather than being folded into a bucket we would be inventing. - Explicit --max-tries / --retry-wait / --timeout / --connect-timeout. retry-wait especially: the default is 0, so retries hammer a server that is already struggling. Set explicitly so a rebuilt aria2 cannot change the behaviour under us. - isCancelled is volatile. It is written by stopDownload() on the caller's thread and read by the download thread, so a stop could go unseen and a user cancellation be reported as a fatal error. No --lowest-speed-limit yet, deliberately: it aborts a transfer below a floor, which is only safe once a caller retries and resumes. On the links this product targets a slow download is the normal case. ADFA-4832: the dashboard's aria2 flags (static/dashboard/sockets/ kiwix.exec.ts) do not carry these yet. That side is ADFA-4894. --- .../org/iiab/controller/Aria2Manager.java | 30 ++++- .../controller/download/domain/Aria2Exit.java | 119 ++++++++++++++++++ .../download/domain/Aria2ExitTest.java | 97 ++++++++++++++ 3 files changed, 244 insertions(+), 2 deletions(-) create mode 100644 controller/app/src/main/java/org/iiab/controller/download/domain/Aria2Exit.java create mode 100644 controller/app/src/test/java/org/iiab/controller/download/domain/Aria2ExitTest.java diff --git a/controller/app/src/main/java/org/iiab/controller/Aria2Manager.java b/controller/app/src/main/java/org/iiab/controller/Aria2Manager.java index f509a55bf..497e884db 100644 --- a/controller/app/src/main/java/org/iiab/controller/Aria2Manager.java +++ b/controller/app/src/main/java/org/iiab/controller/Aria2Manager.java @@ -32,7 +32,12 @@ public class Aria2Manager { private static final String TAG = "IIAB-Aria2-Native"; private Process aria2Process; - private boolean isCancelled = false; + /** + * ADFA-4895: volatile. It is written by {@code stopDownload()} on the caller's thread and read + * by the download thread's loop and its catch block, so without this a stop could go unseen and + * a user cancellation would be reported as a fatal error. + */ + private volatile boolean isCancelled = false; public interface DownloadListener { void onProgress(int percentage, String speed, String eta); @@ -179,6 +184,20 @@ public void startDownload(Context context, String url, DownloadListener listener command.add("--summary-interval=1"); command.add("--download-result=hide"); + // ADFA-4895: aria2 already knows how to survive a bad link; we were not asking it + // to. These are set explicitly rather than inherited, so the behaviour is pinned by + // this file and does not change under us when the bundled aria2 is rebuilt. + // + // No --lowest-speed-limit here on purpose. It makes aria2 abort a transfer that + // drops below a floor, which is only safe once a caller retries and resumes: on the + // links this product targets, a slow download is the normal case, and aborting one + // with nothing to catch it would be worse than the stall we are trying to detect. + // It lands with the retry loop, not before it. + command.add("--max-tries=5"); + command.add("--retry-wait=5"); // default is 0 — retries hammer a struggling server + command.add("--timeout=60"); // per-connection read timeout + command.add("--connect-timeout=30"); + // Apply network decision if (forceIpv4) { Log.w(TAG, "Network profiler decided to FORCE IPv4."); @@ -233,7 +252,14 @@ public void startDownload(Context context, String url, DownloadListener listener } if (exitCode != 0) { - mainHandler.post(() -> listener.onError("Aria2c native process failed with code " + exitCode)); + // ADFA-4895: say what aria2 said. Every non-zero exit used to produce the same + // sentence, so a full disk, a missing mirror and a dropped Wi-Fi were one + // event, and nothing downstream could tell which of them was worth retrying. + org.iiab.controller.download.domain.Aria2Exit.Kind kind = + org.iiab.controller.download.domain.Aria2Exit.kindOf(exitCode); + String reason = org.iiab.controller.download.domain.Aria2Exit.label(exitCode); + Log.e(TAG, "aria2 exit " + exitCode + " (" + kind + "): " + reason); + mainHandler.post(() -> listener.onError(reason)); return; } // ADFA-4676: never trust the exit code alone. For a Metalink download, diff --git a/controller/app/src/main/java/org/iiab/controller/download/domain/Aria2Exit.java b/controller/app/src/main/java/org/iiab/controller/download/domain/Aria2Exit.java new file mode 100644 index 000000000..462220d20 --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/download/domain/Aria2Exit.java @@ -0,0 +1,119 @@ +/* + * ============================================================================ + * Name : Aria2Exit.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : ADFA-4895. Pure rule: what an aria2 exit code means. + * No Android, no I/O. + * ============================================================================ + */ +package org.iiab.controller.download.domain; + +/** + * What aria2 was telling us when it stopped. + * + *

Until now every non-zero exit produced the same message — "Aria2c native process failed with + * code N" — and the caller failed the whole install on all of them. That throws away the one thing + * aria2 is careful about: it distinguishes a network hiccup from a missing file from a full disk, + * and only one of those is worth trying again. Retry, resume and any honest report to the user all + * need this distinction first, which is why it lands before them. + * + *

Describes, does not decide. This class says what happened; it does not say how many + * times to retry or how long to wait. That policy belongs with the caller that owns the download, + * and keeping it out of here is what lets the rootfs path and the content paths make different + * choices from the same reading. + * + *

Unknown is its own answer, not a synonym for fatal. aria2's own code 1 is literally + * "unknown error" and in practice it covers transient conditions as well as real ones; folding it + * into either bucket would be inventing information we do not have. The caller decides what + * caution means for it. + */ +public final class Aria2Exit { + + /** What kind of stop this was. */ + public enum Kind { + /** Everything downloaded. */ + SUCCESS, + /** A condition that commonly clears by itself: timeouts, resolution, network drops. */ + TRANSIENT, + /** aria2 gave up because the transfer was too slow ({@code --lowest-speed-limit}). */ + STALLED, + /** Trying again with the same inputs cannot help: not found, no disk space, bad auth. */ + PERMANENT, + /** aria2 did not say, or said something this table does not cover. */ + UNKNOWN + } + + private Aria2Exit() { + } + + /** + * Classify an aria2 process exit code. + * + *

The table below is aria2's documented set. Codes outside it are {@link Kind#UNKNOWN} + * rather than assumed, so a future aria2 that adds one does not get silently mislabelled. + */ + public static Kind kindOf(int exitCode) { + switch (exitCode) { + case 0: return Kind.SUCCESS; + + // Worth another attempt: the far side or the link misbehaved. + case 2: // timeout + case 6: // network problem + case 7: // unfinished downloads remained + case 19: // name resolution failed + case 22: // bad HTTP response header + case 29: // server temporarily unavailable + return Kind.TRANSIENT; + + // aria2 aborted the transfer itself for being below the floor we set. + case 5: + return Kind.STALLED; + + // Same inputs, same outcome. Retrying only wastes the user's data. + case 3: // resource not found + case 4: // resource not found too many times + case 8: // remote server does not support resume + case 9: // not enough disk space + case 16: // could not open or create the file + case 24: // HTTP authorization failed + return Kind.PERMANENT; + + case 1: // aria2's own "unknown error" + default: + return Kind.UNKNOWN; + } + } + + /** + * A short, stable English phrase for logs and for the failure text we keep in the install + * state. Not a user-facing string: those are localized resources chosen by the presentation + * layer, which can map {@link Kind} however it needs to. + */ + public static String label(int exitCode) { + switch (exitCode) { + case 0: return "ok"; + case 1: return "unspecified aria2 error"; + case 2: return "connection timed out"; + case 3: return "file not found on the server"; + case 4: return "file not found on any mirror"; + case 5: return "transfer too slow, aborted"; + case 6: return "network problem"; + case 7: return "download left unfinished"; + case 8: return "server does not support resuming"; + case 9: return "not enough disk space"; + case 16: return "could not write the file"; + case 19: return "could not resolve the host"; + case 22: return "bad response from the server"; + case 24: return "server rejected the request"; + case 29: return "server temporarily unavailable"; + default: return "aria2 exit code " + exitCode; + } + } + + /** Whether trying the same download again could plausibly end differently. */ + public static boolean worthAnotherAttempt(int exitCode) { + Kind k = kindOf(exitCode); + return k == Kind.TRANSIENT || k == Kind.STALLED; + } +} diff --git a/controller/app/src/test/java/org/iiab/controller/download/domain/Aria2ExitTest.java b/controller/app/src/test/java/org/iiab/controller/download/domain/Aria2ExitTest.java new file mode 100644 index 000000000..6aac5a2d2 --- /dev/null +++ b/controller/app/src/test/java/org/iiab/controller/download/domain/Aria2ExitTest.java @@ -0,0 +1,97 @@ +package org.iiab.controller.download.domain; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +import org.iiab.controller.download.domain.Aria2Exit.Kind; +import org.junit.Test; + +/** + * Unit tests for {@link Aria2Exit} — reading aria2's exit code instead of discarding it. Pure JVM. + * + *

The distinction under all of these: a download worth retrying costs a little time, and one + * that is not worth retrying costs the user data they may be paying for by the megabyte on a link + * this product exists to work around. Both mistakes are real, so neither bucket is the default. + */ +public class Aria2ExitTest { + + @Test + public void zeroIsTheOnlySuccess() { + assertEquals(Kind.SUCCESS, Aria2Exit.kindOf(0)); + for (int code = 1; code <= 32; code++) { + assertNotEquals("code " + code, Kind.SUCCESS, Aria2Exit.kindOf(code)); + } + } + + @Test + public void theLinkMisbehavingIsTransient() { + for (int code : new int[]{2, 6, 7, 19, 22, 29}) { + assertEquals("code " + code, Kind.TRANSIENT, Aria2Exit.kindOf(code)); + } + } + + @Test + public void aTooSlowAbortIsItsOwnKind() { + assertEquals(Kind.STALLED, Aria2Exit.kindOf(5)); + } + + @Test + public void theSameInputsFailingAgainIsPermanent() { + for (int code : new int[]{3, 4, 8, 9, 16, 24}) { + assertEquals("code " + code, Kind.PERMANENT, Aria2Exit.kindOf(code)); + } + } + + // ---- what we refuse to guess ------------------------------------------- + + /** + * aria2's code 1 is documented as "unknown error" and covers transient conditions as well as + * real ones. Calling it either would be inventing information; the caller decides. + */ + @Test + public void ariasOwnUnknownStaysUnknown() { + assertEquals(Kind.UNKNOWN, Aria2Exit.kindOf(1)); + } + + /** A future aria2 that adds a code must not be silently sorted into a bucket. */ + @Test + public void codesOutsideTheTableAreUnknown() { + for (int code : new int[]{40, 99, -1, Integer.MAX_VALUE}) { + assertEquals("code " + code, Kind.UNKNOWN, Aria2Exit.kindOf(code)); + } + } + + // ---- the question the caller actually asks ------------------------------ + + @Test + public void onlyTransientAndStalledAreWorthAnotherAttempt() { + assertTrue(Aria2Exit.worthAnotherAttempt(6)); + assertTrue(Aria2Exit.worthAnotherAttempt(5)); + assertFalse(Aria2Exit.worthAnotherAttempt(0)); + assertFalse(Aria2Exit.worthAnotherAttempt(9)); + assertFalse("unknown must not opt in by default", Aria2Exit.worthAnotherAttempt(1)); + } + + /** + * A full disk is the case where retrying is actively harmful: every attempt re-downloads + * gigabytes that cannot be written. Pinned separately because it is the one a generous default + * would get wrong. + */ + @Test + public void aFullDiskIsNeverRetried() { + assertEquals(Kind.PERMANENT, Aria2Exit.kindOf(9)); + assertFalse(Aria2Exit.worthAnotherAttempt(9)); + } + + // ---- labels ------------------------------------------------------------- + + @Test + public void everyLabelSaysSomethingAndUnknownCodesCarryTheNumber() { + for (int code = 0; code <= 30; code++) { + assertFalse("code " + code, Aria2Exit.label(code).trim().isEmpty()); + } + assertTrue(Aria2Exit.label(77).contains("77")); + } +} From 3e2b3f27e20e3e278ef5d8abfad1a5a4dedd8f33 Mon Sep 17 00:00:00 2001 From: "Luis Guzman (AppDevForAll)" Date: Thu, 13 Aug 2026 00:20:01 -0600 Subject: [PATCH 2/6] ADFA-4893 docs: an ADR for where a download runs, and who decides when it is going badly MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Written after reading all five download paths rather than from the ticket text, which said they were uniformly weak. Two of them — the rootfs image and ZIM, the two largest transfers — already do resume, per-piece hashes, multiple mirrors and an integrity gate. Nothing needs inventing there, and saying so changes what is left to do. Five decisions: - Slowness is a condition, not an error. Nothing aborts a transfer for being slow, so --lowest-speed-limit stays off both aria2 invocations. It is the right flag for a script and the wrong one for a person on the links this product exists for. - Resume on an event, never on a timer. A changed precondition — the network came back, the user joined another Wi-Fi — is a reason to retry; a clock is not. aria2's own bounded --max-tries stays: that is one connection inside one transfer, not the app relaunching itself. - The trigger is estimated time, not speed. A rate is not actionable and is meaningless without a reference; the estimate is read against the baseline the profiler already measures on the same transfer. - The app offers, the user decides. - UIDT applies to the STOPPED class only. LIVE downloads are owned by the dashboard inside the container, so wrapping them device-side would add a second owner for work that already has one. Also recorded: from Android 16, long-running workers backed by foreground services can exhaust the app's job quota. InstallService is one, running for hours. Three claims in it are not verified and are marked as such, each with the cheap test that would settle it: whether a LIVE download survives the app process being killed (this sizes ADFA-4897 and nothing else can), whether tile-extract.py resumes, and what Kolibri's importcontent does on a failed transfer. --- ...893-download-execution-and-user-control.md | 245 ++++++++++++++++++ 1 file changed, 245 insertions(+) create mode 100644 controller/docs/ADR-4893-download-execution-and-user-control.md diff --git a/controller/docs/ADR-4893-download-execution-and-user-control.md b/controller/docs/ADR-4893-download-execution-and-user-control.md new file mode 100644 index 000000000..6b79035b3 --- /dev/null +++ b/controller/docs/ADR-4893-download-execution-and-user-control.md @@ -0,0 +1,245 @@ +# ADR-4893 — Where a download runs, and who decides when it is going badly + +Status: Proposed (ADFA-4893; hangs off Epic ADFA-1028). **Scope: the decision and its consequences, +no refactor.** The area tickets do the work: **ADFA-4895** (rootfs image), **ADFA-4894** (the REST +runners), **ADFA-4897** (the device's memory of a live run), **ADFA-4898** (maps), **ADFA-4896** +(FQR controls), **ADFA-4899** (Portal). `operation-model-roadmap.svg`, beside this file, tracks how +far each has got. + +Written after reading all five download paths rather than from the ticket text, because the ticket +text said the paths were uniformly weak and they are not. Two of them are already where this +document wants everything to end up, and saying so changes what is left to do. + +## Context + +K2Go downloads very large things over links it does not control: a 2–4 GB rootfs image, ZIM files +in the tens to hundreds of GB, map layers in the tens of GB. A slow link, a network change +mid-transfer, or simply closing the app must not cost the user hours of data. + +### The five paths, as they actually are + +| What | Class | Tool | Resumes | Verifies | Mirrors | +|---|---|---|---|---|---| +| rootfs image | STOPPED, on the device | bundled `libaria2c.so` + `.meta4` | `.aria2` control file, per-piece | size + SHA-256 (`DownloadVerifier`), plus `--check-integrity` per piece | yes, from the Metalink | +| ZIM / Kiwix | LIVE, in-server | `/usr/bin/aria2c --follow-metalink=mem` | yes | `--check-integrity` | yes | +| Maps / FQR | LIVE, in-server | `tile-extract.py` under `sudo` | *unverified* — see below | *unverified* | no | +| Books / Gutenberg | LIVE, in-server | plain `fetch()` | no | no | no | +| Kolibri | LIVE, in-server | Kolibri's own `importcontent` | *unknown* | *unknown* | no | + +**Where this table is a citation and where it is not.** The first two rows and the Books row were +read in this repository: `Aria2Manager.java` and `MetalinkFile.java` for the rootfs, +`sockets/kiwix.exec.ts` for ZIM, `sockets/books.exec.ts` for Books — five `fetch()` calls with no +`AbortController`, no timeout and no `Range` anywhere in the file. + +The Maps row is **not** verified here. `maps.exec.ts` spawns `tile-extract.py` and parses its output; +whether a failed run resumes is a property of that script, which does not live in this repository. +"Restarts all three layers from zero" is ADFA-4894's claim, repeated here without confirmation. +Read the script before acting on it. + +The Kolibri row is an **assumption**. `kolibri.exec.ts` spawns no binary and delegates to +`importcontent`; what that does on a failed transfer was not investigated. + +The first two are the two largest transfers and they are already at the target: Metalink gives them +several servers, per-piece hashes, resume across a kill, and an integrity gate that runs before the +artifact is ever extracted or executed. **Nothing needs inventing for them.** The gap is entirely in +Books, Maps and Kolibri. + +### The class distinction is the one we already have + +These are not "two stages of downloading". They are the two **execution classes** ADR-5061 already +declared, and the download story falls exactly onto them: + +- **STOPPED** — no rootfs yet, or the box is down. The app itself is the downloader, spawning the + bundled binary. This is the rootfs image, and only this. +- **LIVE** — the rootfs exists and the services answer. The dashboard's job engine owns the work + inside the container; the app only asks and observes. + +In the LIVE class the work is owned by the dashboard inside the container, and `jobs.ts` gives it a +real substrate: SQLite, a `canceled` phase distinct from `error`, a `cancel()` that kills the +tracked children, and `reconcileOnBoot()` — all verified in the file. + +**But the container is not independent of the app**, and an earlier draft of this document claimed +it was. The environment proot is a child of this app's process (`EnvironmentProcessMatcher`, and +`ServerController` reaches for `killall -9 proot`). So: + +- The app **backgrounded**, or its Activity gone: the proot survives. Nothing kills it — + ADFA-5103 documents that as a defect in the other direction. +- The app's **process killed**: its children go with it. Android 12's phantom-process killer does + this deliberately, and `InstallService` already handles the resulting exit 137. + +So a LIVE download survives being left alone and probably does not survive a process kill. +`reconcileOnBoot()` exists precisely because whoever wrote it expected interruption. **ADFA-4897 is +therefore not the small ticket a previous draft here said it was** — the device's memory of what it +asked for is one half, and the transfer's own survival is still the other. Which half dominates is +a device question, not a reading question: kill the app mid-ZIM and see whether aria2 is still +running. + +In the STOPPED class the app *is* the downloader, so process death is unambiguously fatal, and that +is where Android's background-execution rules bite hardest. + +### What is measured today and thrown away + +Two figures already exist and neither survives its own function: + +- `Aria2NetworkProfiler.runTimeBoxedTest` measures six seconds of real transfer, twice (IPv4 and + default), in KB/s — and the result is used only to pick a flag, then discarded. +- `Aria2Manager` parses aria2's `DL:` field on every progress line and immediately concatenates a + localized unit onto it, so what reaches the listener is a display string, not a number. + +And a third, which is the one that matters most: **aria2 prints an `ETA:` on every progress line, +`Aria2Manager` parses it into the third argument of `onProgress(percentage, speed, eta)`, and all +three call sites in `InstallService` drop it on the floor** (`:330`, `:488`, `:655`). + +ADFA-5118 (merged 12 Aug) built an estimate for the **write** side — verify and extract — with +`EtaSmoother` to stop the label flickering across a bucket boundary, a state that carries it +(`postVerifying(percent, message, eta)`), the layout, and the strings in all 34 locales. The +download leg has none of that, and it is the longest of the three and the one on the worst link. + +**Reusing that machinery for the download is a proposal, not a wiring gap**, and the two signals +are not the same. The extract estimate is derived locally and wobbles because files decompress at +different speeds; a download estimate wobbles because the network does, which is noise of a +different kind and duration. The smoother's shape fits — it already keeps the last shown value +through a rate gap, which is exactly what a stalling transfer produces — but its five-second dwell +was tuned for the other signal and should not be inherited without a reason. + +**We compute our own estimate rather than adopt aria2's.** aria2 prints one and we parse it, so +taking it would be free; it is rejected because this document makes the estimate a *decision input* +— the trigger for offering the user an action — and a black box is not a thing to decide on. With +Metalink across several mirrors, aria2's figure can jump when a mirror drops, and we would have no +way to tell that from the network degrading. Ours is `(total − completed) / rate`, from the figures +aria2 already prints on the same line, with the Metalink size as the authority for the total. + +### What the industry does + +Android now has an API for precisely this shape of work: **user-initiated data transfer** (UIDT), +API 34+, via `JobScheduler`, outside the standby-bucket job quotas. Google Maps reported a 10% +improvement in download reliability after adopting it, together with resumable downloads. There is +no Jetpack wrapper, so the documented approach is to gate on Android 14+ and fall back to a +WorkManager foreground service below it. + +There is a deadline hiding in that: **from Android 16, long-running workers backed by foreground +services can exhaust the app's job quota.** `InstallService` is a foreground service running for +hours. This is not a theoretical concern for us. + +The wider pattern across Play Store, Steam and torrent clients is consistent, and it is the +opposite of what a command-line downloader does: a slow transfer is never aborted. It is shown, and +the user is offered something — Steam offers a different download region, Play Store offers +"waiting for Wi-Fi" as a *state* rather than an error. + +## Decision + +### 1. Slowness is a condition, not an error + +Errors are retried. Conditions are reported, and the user is offered an action. A transfer below +any speed we care to name is still a transfer, and on the links this product exists for, slow is +the normal case. Nothing in the app aborts a download for being slow. + +Concretely: `--lowest-speed-limit` is **not** set on either aria2 invocation. It is the correct flag +for a script and the wrong one for a person. + +### 2. Resume on an event, never on a timer + +Retrying because a precondition changed — the network came back, the user joined a different +Wi-Fi — is correct and expected. Retrying on a clock against unchanged conditions is the loop that +burns a metered connection while achieving nothing. + +This is a boundary, not a ban on all retries: aria2's own `--max-tries` / `--retry-wait`, bounded, +operate on a single connection inside one transfer and are kept. What is excluded is the +application relaunching a failed transfer by itself. + +### 3. The trigger is estimated time, not speed + +A rate is not actionable. "180 KiB/s" tells a user nothing; "at this rate this finishes in fourteen +hours" tells them everything, and it already folds in the size of what they asked for. + +The estimate is read against the baseline the profiler measured at the start of this same transfer, +not against an absolute floor. Twenty KiB/s means nothing on its own; twenty KiB/s where we measured +three MiB/s ten minutes ago means the network changed under us, which is a different statement and +a different offer. + +An absolute floor is kept only to avoid dividing by zero. + +### 4. The user decides; the app offers + +When the estimate crosses the threshold and stays there, the app offers — pause and switch network, +pause and continue later, carry on. It does not act. When a new validated network appears, a paused +transfer resumes by itself, because that is a changed precondition and the `.aria2` control file +makes resuming nearly free. + +### 5. UIDT applies to the STOPPED class only + +The LIVE downloads already survive the app; wrapping them in a device-side job would add a second +owner for work the dashboard already owns. The rootfs image download is the one that needs UIDT on +API 34+, a foreground-service fallback below it, and it is the one exposed to the Android 16 quota +change. + +## Options considered + +**A — Measure, advise, let the user act (chosen).** Matches how every consumer download product +behaves, keeps control where the person with the context is, and costs nothing to build because the +inputs are already computed. + +**B — Abort and auto-retry on a speed floor.** One flag on aria2 and a loop in the app. Rejected: +on a genuinely slow link it turns a long download into an infinite sequence of short ones, and the +user is never told why. + +**C — Do nothing; slowness is the user's problem.** The current behaviour. Rejected because the user +cannot even see the problem: the rate is a display string, there is no estimate, and the boot gate +gives them nothing to press. + +## Consequences + +- The boot gate stops needing to hold. A download that is pausable, has a visible estimate and + survives being left alone is a background job with a surface, not a modal event — which dissolves + state-spine findings 1 and 6 and half of 3 without touching any of them directly. +- Two downloaders reach the target by doing nothing, and it should be said out loud on the board so + nobody "improves" them. +- Books is confirmed work and it is server-side, in ADFA-4894 — currently ranked below tickets that + matter less. Maps probably belongs with it, pending someone reading `tile-extract.py`. +- Kolibri delegates to `importcontent` and we do not control its transfer. Whether we wrap it or + accept it as opaque is an open decision with no ticket — and it cannot be taken before someone + establishes what `importcontent` does on a failed transfer. +- A user who is offered "switch network" and does so must find the transfer where they left it. + That requires the device-side memory of ADFA-4897 even in the STOPPED class. + +## Action items + +1. Carry aria2's `ETA:` through to the state, so the download leg shows the estimate that verify + and extract already show. `postDownloading` gains the argument its caller already receives and + discards; `EtaSmoother` and the display come from ADFA-5118 unchanged. Also stop destroying the + numeric rate at `Aria2Manager:219`, and keep the profiler's baseline instead of discarding it + after the IPv4 decision. **ADFA-4895.** +2. The control surface — pause, switch network, resume — and a `ConnectivityManager.NetworkCallback` + that resumes on a new validated network. **ADFA-4895**, after 1. +3. Bring Books to a timeout, an abort wired to cancel, and a ranged resume; give Maps a per-layer + checkpoint. **ADFA-4894.** +4. Device-side memory of a live run, and re-attachment on relaunch. **ADFA-4897**. Size it after the + device test below, not before. +5. UIDT on API 34+ with a foreground-service fallback, for the rootfs download only. Not yet + ticketed; carries the Android 16 quota exposure. +6. Decide Kolibri: wrap `importcontent` or accept it as opaque. Not yet ticketed. + +### Open before any of this is acted on + +Three claims above are not verified, and each one changes what its area ticket is worth: + +- **Does a LIVE download survive the app's process being killed?** Kill the app mid-ZIM and check + whether aria2 is still running inside the container. This sizes ADFA-4897 and nothing else can. +- **Does `tile-extract.py` resume?** It is not in this repository. This decides whether Maps is a + checkpoint problem or already fine. +- **What does Kolibri's `importcontent` do on a failed transfer?** This decides whether there is + anything to wrap. + +None needs a large investigation. All three are cheap, and all three are load-bearing. + +## References + +- `controller/docs/ADR-5061-rest-vs-proot-operation-model.md` — the execution classes this reuses. +- `controller/docs/ADR-4832-live-content-channel.md` — the three aria2 flag sets that must stay + aligned. +- `controller/docs/state-spine.svg` — findings 1, 3 and 6. +- `controller/docs/operation-model-roadmap.svg` — where each area ticket has got to. +- [User-initiated data transfer](https://developer.android.com/develop/background-work/background-tasks/uidt) +- [Google Maps improved download reliability by 10% using the UIDT API](https://android-developers.googleblog.com/2024/09/google-maps-improved-download-reliability-user-initiated-data-transfer-api.html) +- [Changes to foreground services](https://developer.android.com/develop/background-work/services/fgs/changes) +- [Data transfer background task options](https://developer.android.com/about/versions/15/changes/datasync-migration) From cd616341127d13b0e3159cd2a4eed9336757fcad Mon Sep 17 00:00:00 2001 From: "Luis Guzman (AppDevForAll)" Date: Thu, 13 Aug 2026 00:34:33 -0600 Subject: [PATCH 3/6] ADFA-4895 feat(download): show how long is left, computed from figures we already had MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The download is the longest phase of an install and the one on the worst link, and it showed a percentage and a rate. On a slow connection the percentage barely moves and the rate alone does not answer the only question the user has, which is whether this finishes tonight. Nothing new is measured. aria2 prints completed, total and rate on every progress line; the rate was being destroyed one line after being parsed — concatenated with a localized unit into a display string — so nothing downstream could compare it or divide a remaining size by it. - ByteToken (pure, unit-tested) reads aria2's tokens back into bytes. It mirrors parseRate in sockets/kiwix.exec.ts on purpose, KiB=1024 against KB=1000 included: at gigabyte scale conflating them is a 7% error, and it lands in a figure the user is asked to act on. Keep the two in step, same standing coordination as the aria2 flag sets (ADFA-4832). - DownloadEta (pure, unit-tested) is (total - completed) / rate, with the Metalink size as the authority for the total so the estimate and the integrity gate measure against the same number. A stalled transfer returns UNKNOWN, not a huge number: a huge number reads downstream as "very slow", which is a different situation with a different remedy. aria2's own ETA is parsed and still unused, deliberately. ADR-4893 makes the estimate a decision input, and a figure we cannot explain is a bad one to decide on — across Metalink mirrors it can jump when one drops, and nothing could tell that from the link degrading. Display: the download joins the weighted row from ADFA-5118 instead of concatenating into one centred line. It has three figures now, and a rate swinging between 412KiB/s and 37MiB/s would drag its neighbours sideways every tick — the dance ADFA-4910 and ADFA-5118 already fixed for extract. A third cell, so none of the three can move another; GONE for verify and extract, which keep exactly the 2/3 split 5118 tuned. InstallState gains a real eta field rather than borrowing the speed slot: DOWNLOADING shows a rate and an estimate at once, so the slot is not free the way it is for verify and extract. Those are left as they are, with a note to migrate when their layout is next touched. The three-argument onProgress stays live and still posts: Aria2NetworkProfiler reports through it before the transfer begins, so an empty override would blank the status line for the whole probe. The smoother dwell is 15s here against 5s for extract. Files decompressing at different speeds is noise that passes in a moment; a network degrades and recovers over tens of seconds, and a short window would let the label chase every dip. Not addressed, and present before this: resuming onto a complete-but- unverified artifact runs a SHA-256 over up to 2.5 GB with no feedback at all — DownloadVerifier has no progress callback. Same shape as the extract "reading" sub-phase, without its handling. --- .../org/iiab/controller/Aria2Manager.java | 44 ++++- .../controller/download/domain/ByteToken.java | 108 +++++++++++++ .../download/domain/DownloadEta.java | 80 ++++++++++ .../InstallProgressRepository.java | 2 + .../install/presentation/InstallService.java | 24 +++ .../install/presentation/InstallState.java | 30 +++- .../controller/redesign/LibraryActivity.java | 27 +++- .../src/main/res/layout/activity_library.xml | 15 ++ .../download/domain/DownloadEtaTest.java | 151 ++++++++++++++++++ 9 files changed, 475 insertions(+), 6 deletions(-) create mode 100644 controller/app/src/main/java/org/iiab/controller/download/domain/ByteToken.java create mode 100644 controller/app/src/main/java/org/iiab/controller/download/domain/DownloadEta.java create mode 100644 controller/app/src/test/java/org/iiab/controller/download/domain/DownloadEtaTest.java diff --git a/controller/app/src/main/java/org/iiab/controller/Aria2Manager.java b/controller/app/src/main/java/org/iiab/controller/Aria2Manager.java index 497e884db..62c3f52b1 100644 --- a/controller/app/src/main/java/org/iiab/controller/Aria2Manager.java +++ b/controller/app/src/main/java/org/iiab/controller/Aria2Manager.java @@ -27,6 +27,8 @@ import org.iiab.controller.download.domain.MetalinkSplit; import org.iiab.controller.download.domain.MetalinkFile; import org.iiab.controller.download.domain.DownloadVerifier; +import org.iiab.controller.download.domain.ByteToken; +import org.iiab.controller.download.domain.DownloadEta; public class Aria2Manager { @@ -41,6 +43,23 @@ public class Aria2Manager { public interface DownloadListener { void onProgress(int percentage, String speed, String eta); + + /** + * ADFA-4895: the same tick, with the figures as numbers instead of display text. + * + *

Added rather than replacing the three-argument form so the two content call sites are + * untouched: they keep overriding that one and inherit this default, which forwards. Only a + * caller that needs to *decide* on the transfer — rather than draw it — overrides this. + * + * @param bytesPerSecond current rate, or {@link ByteToken#UNKNOWN} + * @param etaSeconds our own estimate, or {@link DownloadEta#UNKNOWN}. Not aria2's: + * see ADR-4893 for why a figure we cannot explain is a bad one to + * act on. + */ + default void onProgress(int percentage, String speed, String eta, + long bytesPerSecond, long etaSeconds) { + onProgress(percentage, speed, eta); + } void onComplete(String downloadPath); void onError(String error); /** ADFA-4676: post-download integrity gate failed (size/SHA-256 mismatch). */ @@ -219,6 +238,11 @@ public void startDownload(Context context, String url, DownloadListener listener // Regex to capture typical Aria2c output // Example: [#2089b0 400MiB/1.0GiB(39%) CN:4 DL:4.5MiB ETA:2m20s] Pattern pattern = Pattern.compile("\\((\\d+)%\\).*?DL:([^\\s]+).*?ETA:([^\\s\\]]+)"); + // ADFA-4895: the same line also carries "400MiB/1.0GiB" — completed and total. A + // second, separate pattern on purpose: if it fails to match, the estimate is simply + // unknown and the progress line above is untouched. Folding it into the pattern + // that already works would put a working display at the mercy of a new regex. + Pattern sizes = Pattern.compile("([\\d.]+[A-Za-z]*)/([\\d.]+[A-Za-z]*)\\(\\d+%\\)"); while ((line = reader.readLine()) != null) { if (isCancelled) { @@ -238,7 +262,25 @@ public void startDownload(Context context, String url, DownloadListener listener String speed = matcher.group(2) + context.getString(R.string.k2go_rate_per_second); String eta = matcher.group(3); - mainHandler.post(() -> listener.onProgress(percent, speed, eta)); + // ADFA-4895: keep the figures as numbers alongside the display text. The + // rate was being destroyed one line above — concatenated into a localized + // string — so nothing downstream could compare it to anything or divide a + // remaining size by it. + long bytesPerSecond = ByteToken.parse(matcher.group(2)); + long etaSeconds = DownloadEta.UNKNOWN; + Matcher sm = sizes.matcher(line); + if (sm.find()) { + long done = ByteToken.parse(sm.group(1)); + // The Metalink's size is the authority when we have it: it is what the + // integrity gate will check against, so the estimate and the verdict + // are measured against the same number. + long total = (mf != null && mf.sizeBytes() > 0) + ? mf.sizeBytes() : ByteToken.parse(sm.group(2)); + etaSeconds = DownloadEta.secondsRemaining(done, total, bytesPerSecond); + } + final long rate = bytesPerSecond; + final long secs = etaSeconds; + mainHandler.post(() -> listener.onProgress(percent, speed, eta, rate, secs)); } } diff --git a/controller/app/src/main/java/org/iiab/controller/download/domain/ByteToken.java b/controller/app/src/main/java/org/iiab/controller/download/domain/ByteToken.java new file mode 100644 index 000000000..6cd998128 --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/download/domain/ByteToken.java @@ -0,0 +1,108 @@ +/* + * ============================================================================ + * Name : ByteToken.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : ADFA-4895. Pure rule: aria2's "400MiB" / "4.5MiB" / "1.0GiB" + * tokens back into bytes. No Android, no I/O. + * ============================================================================ + */ +package org.iiab.controller.download.domain; + +/** + * Reads a size or rate token out of an aria2 progress line and gives back a number. + * + *

Why this exists. aria2 prints everything we need on one line — + * {@code [#2089b0 400MiB/1.0GiB(39%) CN:4 DL:4.5MiB ETA:2m20s]} — and until now the app captured + * the rate only to concatenate a localized "/s" onto it and hand a display string upwards. A + * string cannot be compared to a baseline, cannot be divided into a remaining size, and cannot be + * decided on. The number has to survive the parse. + * + *

Binary and decimal are not the same and the difference is not academic. aria2 emits + * IEC units (KiB, MiB, GiB — powers of 1024) but the same field can carry SI units from other + * tools, and at gigabyte scale treating GiB as GB is a 7% error — which lands directly in an + * estimate the user is asked to make a decision on. Both tables are kept, and the {@code i} is + * what selects between them. + * + *

Mirrors {@code parseRate} in {@code static/dashboard/sockets/kiwix.exec.ts}, deliberately: + * the in-server downloader reads the same tokens from the same program. If one changes, change + * both — the same standing coordination as the aria2 flag sets (ADFA-4832). + */ +public final class ByteToken { + + /** The token could not be read. Distinct from a real zero, which is a legitimate rate. */ + public static final long UNKNOWN = -1L; + + private static final long KI = 1024L; + private static final long MI = KI * 1024L; + private static final long GI = MI * 1024L; + private static final long TI = GI * 1024L; + + private ByteToken() { + } + + /** + * Parse a token such as {@code 400MiB}, {@code 4.5MiB}, {@code 1.0GiB}, {@code 512K}, + * {@code 1.2MB} or a bare {@code 850} into bytes. + * + *

A missing unit means bytes, which is what aria2 does. Anything unreadable is + * {@link #UNKNOWN} rather than zero: a download reporting nothing and a download reporting + * genuinely no throughput are different facts, and only one of them means the transfer is in + * trouble. + */ + public static long parse(String token) { + if (token == null) return UNKNOWN; + String t = token.trim(); + if (t.isEmpty()) return UNKNOWN; + + int i = 0; + while (i < t.length() && (Character.isDigit(t.charAt(i)) || t.charAt(i) == '.')) i++; + if (i == 0) return UNKNOWN; + + double value; + try { + value = Double.parseDouble(t.substring(0, i)); + } catch (NumberFormatException e) { + return UNKNOWN; + } + if (value < 0 || Double.isNaN(value) || Double.isInfinite(value)) return UNKNOWN; + + String unit = t.substring(i).trim(); + // aria2 writes a trailing "/s" on some fields; the rate and the size share this parser. + int slash = unit.indexOf('/'); + if (slash >= 0) unit = unit.substring(0, slash); + unit = unit.toUpperCase(java.util.Locale.ROOT); + + long multiplier = multiplierFor(unit); + if (multiplier == UNKNOWN) return UNKNOWN; + + double bytes = value * multiplier; + if (bytes > Long.MAX_VALUE) return UNKNOWN; + return Math.round(bytes); + } + + /** {@code UNKNOWN} for a unit this does not recognise, so a typo is never read as bytes. */ + private static long multiplierFor(String unit) { + switch (unit) { + case "": + case "B": return 1L; + case "K": + case "KI": + case "KIB": return KI; + case "M": + case "MI": + case "MIB": return MI; + case "G": + case "GI": + case "GIB": return GI; + case "T": + case "TI": + case "TIB": return TI; + case "KB": return 1000L; + case "MB": return 1000_000L; + case "GB": return 1000_000_000L; + case "TB": return 1000_000_000_000L; + default: return UNKNOWN; + } + } +} diff --git a/controller/app/src/main/java/org/iiab/controller/download/domain/DownloadEta.java b/controller/app/src/main/java/org/iiab/controller/download/domain/DownloadEta.java new file mode 100644 index 000000000..9a60b97bf --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/download/domain/DownloadEta.java @@ -0,0 +1,80 @@ +/* + * ============================================================================ + * Name : DownloadEta.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : ADFA-4895. Pure rule: how long is left, from what is left and + * how fast it is moving. No Android, no I/O. + * ============================================================================ + */ +package org.iiab.controller.download.domain; + +/** + * How much longer a transfer needs, computed here rather than taken from aria2. + * + *

Why not aria2's own ETA. It prints one on every progress line and parsing it would be + * free. It is not used because ADR-4893 makes the estimate a decision input — the figure the app + * weighs before offering the user an action — and a number we cannot explain is a bad thing to + * decide on. With a Metalink across several mirrors, aria2's estimate can jump when one mirror + * drops, and nothing downstream could tell that from the link itself degrading. Ours is arithmetic + * on two figures printed on the same line, so when it moves we know why. + * + *

What it refuses to answer. A rate of zero is not "infinity seconds", it is "no + * estimate": a stalled transfer has no honest completion time, and inventing a very large number + * would be read downstream as a very slow transfer, which is a different situation with a + * different remedy. {@link #UNKNOWN} keeps those apart. + */ +public final class DownloadEta { + + /** No honest estimate. Matches {@code EtaSmoother.UNKNOWN} so the two compose. */ + public static final long UNKNOWN = -1L; + + private DownloadEta() { + } + + /** + * Seconds remaining, or {@link #UNKNOWN}. + * + * @param completedBytes bytes transferred so far, or {@link ByteToken#UNKNOWN} + * @param totalBytes the full size — prefer the Metalink's figure over the progress line's, + * since the Metalink is what the integrity gate will check against + * @param bytesPerSecond current rate, or {@link ByteToken#UNKNOWN} + */ + public static long secondsRemaining(long completedBytes, long totalBytes, long bytesPerSecond) { + if (totalBytes <= 0 || completedBytes < 0 || bytesPerSecond <= 0) return UNKNOWN; + if (completedBytes >= totalBytes) return 0L; + return (totalBytes - completedBytes) / bytesPerSecond; + } + + /** + * Whether the estimate is far enough out to be worth telling the user about. + * + *

Deliberately a comparison against a budget the caller supplies rather than a constant + * here: what counts as too long depends on what is being fetched and on what the app intends + * to offer, and this class should not know either. It answers the question; it does not decide + * that the question was worth asking. + * + *

An {@link #UNKNOWN} estimate is never "too long". Not knowing is not the same as knowing + * it is bad, and acting on a rate gap would fire the offer every time a connection hiccups. + */ + public static boolean exceeds(long etaSeconds, long budgetSeconds) { + return etaSeconds != UNKNOWN && etaSeconds > budgetSeconds; + } + + /** + * How the current rate compares with what this same transfer managed at the start, as a + * percentage of the baseline. {@link #UNKNOWN} when either figure is missing. + * + *

This is the reading that makes "20 KiB/s" mean something. On its own the number says + * nothing — it may be all this link has ever done. Against a baseline of three MiB/s measured + * ten minutes ago on the same connection, it says the network changed under us, which is a + * different statement and earns a different offer. + * + *

The baseline is the one {@code Aria2NetworkProfiler} already measures before the transfer + * starts and currently discards after choosing an IP stack. + */ + public static long percentOfBaseline(long bytesPerSecond, long baselineBytesPerSecond) { + if (bytesPerSecond < 0 || baselineBytesPerSecond <= 0) return UNKNOWN; + return (bytesPerSecond * 100L) / baselineBytesPerSecond; + } +} diff --git a/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallProgressRepository.java b/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallProgressRepository.java index 72ff20405..3d8ea1113 100644 --- a/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallProgressRepository.java +++ b/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallProgressRepository.java @@ -62,6 +62,8 @@ public boolean isRunning() { // All posts are thread-safe (callable from the aria2 / proot worker threads). public void postDownloading(int percent, String speed) { post(InstallState.downloading(percent, speed)); } + /** ADFA-4895: the rate and our own estimate, together. */ + public void postDownloading(int percent, String speed, String eta) { post(InstallState.downloading(percent, speed, eta)); } public void postExtracting(String message) { post(InstallState.extracting(message)); } public void postExtracting(int percent, String message) { post(InstallState.extracting(percent, message)); } // ADFA-5118: unified verify+extract bar — determinate progress with an ETA for both passes. diff --git a/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallService.java b/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallService.java index 1d78e2887..807cde0c8 100644 --- a/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallService.java +++ b/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallService.java @@ -326,13 +326,37 @@ private void startRootfsDownload() { if (aria2Manager == null) aria2Manager = new Aria2Manager(); aria2Manager.startDownload(this, directUrl, new Aria2Manager.DownloadListener() { + /** + * ADFA-4895: a longer dwell than the extract bar's five seconds. That one debounces + * files decompressing at different speeds — noise that passes in a moment. A network + * degrades and recovers over tens of seconds, so a short window would let the estimate + * chase every dip and make the label the least trustworthy thing on the screen. + */ + private final org.iiab.controller.install.domain.EtaSmoother etaSmoother = + new org.iiab.controller.install.domain.EtaSmoother(15000L); + @Override public void onProgress(int percentage, String speed, String eta) { + // Still live, and not a leftover: Aria2NetworkProfiler reports through this form + // ("Test IPv4", "Test IPv6", then the winner) before the real transfer begins, so + // an empty override here would blank the status line for the whole probe. It has + // no rate and no estimate to carry — those only exist once aria2 is transferring. if (cancelled) return; InstallProgressRepository.get().postDownloading(percentage, speed); updateNotification(getString(R.string.install_status_os_download, percentage, speed)); } + @Override + public void onProgress(int percentage, String speed, String eta, + long bytesPerSecond, long etaSeconds) { + if (cancelled) return; + int bucket = etaSmoother.smooth( + org.iiab.controller.install.domain.EtaSmoother.bucketOf(etaSeconds), + android.os.SystemClock.elapsedRealtime()); + InstallProgressRepository.get().postDownloading(percentage, speed, formatEta(bucket)); + updateNotification(getString(R.string.install_status_os_download, percentage, speed)); + } + @Override public void onComplete(String downloadPath) { if (cancelled) return; diff --git a/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallState.java b/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallState.java index 901520e3b..b0bb5dad5 100644 --- a/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallState.java +++ b/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallState.java @@ -34,7 +34,24 @@ public enum Op { INSTALL, RESET, REBUILD } public final String message; // resolved status text / current file line / error public final long seq; // assigned by the repository; identifies terminal events + /** + * ADFA-4895: resolved "time left" text, or empty. A field of its own because DOWNLOADING has to + * show a rate AND an estimate at once, so it cannot borrow the speed slot the way ADFA-5118's + * verify/extract states do — those have no rate to display, so the slot was free there. + * + *

The 5118 states are left as they are. When their layout is next touched they should move + * onto this field too, so "speed" means a rate everywhere and nothing has to be read twice to + * find out what it is carrying. + */ + public final String eta; + private InstallState(Phase phase, Op op, int percent, String speed, String message, long seq) { + this(phase, op, percent, speed, message, seq, ""); + } + + private InstallState(Phase phase, Op op, int percent, String speed, String message, long seq, + String eta) { + this.eta = eta != null ? eta : ""; this.phase = phase; this.op = op != null ? op : Op.INSTALL; this.percent = percent; @@ -54,12 +71,12 @@ public boolean isTerminal() { /** Returns a copy with the given sequence number (the repository assigns it). */ InstallState withSeq(long seq) { - return new InstallState(phase, op, percent, speed, message, seq); + return new InstallState(phase, op, percent, speed, message, seq, eta); } /** Returns a copy tagged with the given operation (the repository stamps it). */ InstallState withOp(Op op) { - return new InstallState(phase, op, percent, speed, message, seq); + return new InstallState(phase, op, percent, speed, message, seq, eta); } public static InstallState idle() { @@ -70,6 +87,15 @@ public static InstallState downloading(int percent, String speed) { return new InstallState(Phase.DOWNLOADING, Op.INSTALL, percent, speed, "", 0L); } + /** + * ADFA-4895: downloading with an estimate beside the rate. The screen shows all three — + * "32% · 37MiB/s · about 3 min left" — because on a slow link the percentage barely moves + * and the rate alone does not say whether this finishes tonight. + */ + public static InstallState downloading(int percent, String speed, String eta) { + return new InstallState(Phase.DOWNLOADING, Op.INSTALL, percent, speed, "", 0L, eta); + } + public static InstallState extracting(String message) { return new InstallState(Phase.EXTRACTING, Op.INSTALL, 0, "", message, 0L); } diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/LibraryActivity.java b/controller/app/src/main/java/org/iiab/controller/redesign/LibraryActivity.java index d78c1677c..a675d2ce4 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/LibraryActivity.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/LibraryActivity.java @@ -56,7 +56,7 @@ public class LibraryActivity extends AppCompatActivity implements ServerControll private LottieAnimationView bootGate; private View installProgress; - private android.widget.TextView installStatus, installDetail, installPercent, installEta; + private android.widget.TextView installStatus, installDetail, installPercent, installEta, installRate; private View installPercentRow; // ADFA-5118: the %/ETA weighted-column row private android.widget.ProgressBar installBar; private boolean gateDismissed = false; @@ -129,6 +129,7 @@ protected void onCreate(Bundle savedInstanceState) { installDetail = findViewById(R.id.k2go_install_detail); installPercentRow = findViewById(R.id.k2go_install_percent_row); installPercent = findViewById(R.id.k2go_install_percent); + installRate = findViewById(R.id.k2go_install_rate); // ADFA-4895 installEta = findViewById(R.id.k2go_install_eta); // ADFA-4947: shared ellipsis animators (fixed-width so the centered lines don't shift). bootEllipsis = new org.iiab.controller.util.EllipsisAnimator(installStatus, true); @@ -331,12 +332,32 @@ private void showInstallProgress(InstallState st) { stopBootEllipsis(); // ADFA-4837: an install owns the status line; stop the boot animation installProgress.setVisibility(View.VISIBLE); if (installBar != null) installBar.setVisibility(View.VISIBLE); // ADFA-4837: boot/shutdown hide it - if (installPercentRow != null) installPercentRow.setVisibility(View.GONE); // ADFA-4910/5118: only the determinate verify/extract shows it + if (installPercentRow != null) installPercentRow.setVisibility(View.GONE); + if (installRate != null) installRate.setVisibility(View.GONE); // ADFA-4895: only DOWNLOADING has a rate if (st.phase == InstallState.Phase.DOWNLOADING) { installStatus.setText(getString(R.string.k2go_downloading_library)); installBar.setIndeterminate(false); installBar.setProgress(st.percent); - installDetail.setText(pct(st.percent) + (st.speed.isEmpty() ? "" : " · " + st.speed)); + // ADFA-4895: the download joins the weighted row instead of concatenating its figures + // into one centred line. It has three of them now — % , rate and estimate — and a rate + // that swings between "412KiB/s" and "37MiB/s" would drag everything beside it sideways + // on every tick, which is the dance ADFA-4910 and ADFA-5118 already fixed for extract. + // Each figure gets its own cell, so none of them can move another. + if (installPercentRow != null) { + installPercentRow.setVisibility(View.VISIBLE); + installPercent.setText(pct(st.percent)); + boolean hasRate = !st.speed.isEmpty(); + boolean hasEta = !st.eta.isEmpty(); + installRate.setText(hasRate ? st.speed : ""); + installRate.setVisibility(hasRate ? View.VISIBLE : View.GONE); + installEta.setText(hasEta ? "· " + st.eta : ""); + installEta.setVisibility(hasEta ? View.VISIBLE : View.GONE); + // With nothing to its right the % owns the row and centres, exactly as ADFA-5118 + // does before its own estimate appears. + installPercent.setGravity((hasRate || hasEta) + ? android.view.Gravity.END : android.view.Gravity.CENTER_HORIZONTAL); + } + installDetail.setText(""); } else if (st.phase == InstallState.Phase.VERIFYING || st.phase == InstallState.Phase.EXTRACTING) { // ADFA-5118: the unified verify+extract bar. Both passes render identically — determinate // bar + % + ETA + current file — so there is no "first nothing, then detail" asymmetry. diff --git a/controller/app/src/main/res/layout/activity_library.xml b/controller/app/src/main/res/layout/activity_library.xml index c61b20ec0..12fb8b72c 100644 --- a/controller/app/src/main/res/layout/activity_library.xml +++ b/controller/app/src/main/res/layout/activity_library.xml @@ -119,6 +119,21 @@ android:gravity="end" android:textAppearance="?attr/textAppearanceBodySmall" android:textColor="@color/k2go_boot_ink" /> + + The distinction under most of these: **no estimate** and **a bad estimate** are different + * answers. A stalled transfer has no honest completion time, and a very large number would be read + * downstream as a very slow transfer — a different situation with a different remedy. + */ +public class DownloadEtaTest { + + private static final long KI = 1024L, MI = KI * 1024L, GI = MI * 1024L; + + // ---- ByteToken: the units aria2 actually prints ------------------------- + + @Test + public void readsTheTokensFromARealProgressLine() { + // [#2089b0 400MiB/1.0GiB(39%) CN:4 DL:4.5MiB ETA:2m20s] + assertEquals(400 * MI, ByteToken.parse("400MiB")); + assertEquals(GI, ByteToken.parse("1.0GiB")); + assertEquals(Math.round(4.5 * MI), ByteToken.parse("4.5MiB")); + } + + @Test + public void aMissingUnitMeansBytes() { + assertEquals(850L, ByteToken.parse("850")); + assertEquals(850L, ByteToken.parse("850B")); + } + + /** + * The one that costs real money if it is wrong. At gigabyte scale, reading GiB as GB is a 7% + * error, and it lands straight in an estimate the user is asked to act on. + */ + @Test + public void binaryAndDecimalUnitsAreNotConflated() { + assertEquals(GI, ByteToken.parse("1GiB")); + assertEquals(1_000_000_000L, ByteToken.parse("1GB")); + assertTrue(ByteToken.parse("1GiB") > ByteToken.parse("1GB")); + assertEquals(KI, ByteToken.parse("1KiB")); + assertEquals(1000L, ByteToken.parse("1KB")); + } + + @Test + public void aTrailingPerSecondIsStripped() { + assertEquals(Math.round(4.5 * MI), ByteToken.parse("4.5MiB/s")); + } + + @Test + public void caseAndSurroundingSpaceDoNotMatter() { + assertEquals(MI, ByteToken.parse(" 1mib ")); + assertEquals(MI, ByteToken.parse("1MIB")); + } + + /** An unreadable token is UNKNOWN, never zero — zero is a legitimate rate and means something. */ + @Test + public void unreadableIsUnknownAndNotZero() { + for (String s : new String[]{null, "", " ", "--", "MiB", "abc", "1.2XB", "-5MiB"}) { + assertEquals(String.valueOf(s), ByteToken.UNKNOWN, ByteToken.parse(s)); + } + assertEquals(0L, ByteToken.parse("0")); + assertEquals(0L, ByteToken.parse("0B")); + } + + // ---- DownloadEta: the estimate ------------------------------------------ + + @Test + public void theOrdinaryCase() { + // 600 MiB left at 4 MiB/s + long left = 400 * MI, total = GI, rate = 4 * MI; + assertEquals((total - left) / rate, DownloadEta.secondsRemaining(left, total, rate)); + } + + @Test + public void alreadyCompleteIsZeroSecondsAndNotNegative() { + assertEquals(0L, DownloadEta.secondsRemaining(GI, GI, MI)); + assertEquals(0L, DownloadEta.secondsRemaining(2 * GI, GI, MI)); + } + + /** + * A stalled transfer has no completion time. Returning a huge number instead would be read as + * "very slow", which is a different situation and would earn the wrong offer. + */ + @Test + public void aStalledTransferHasNoEstimateRatherThanAHugeOne() { + assertEquals(DownloadEta.UNKNOWN, DownloadEta.secondsRemaining(400 * MI, GI, 0L)); + } + + @Test + public void missingInputsGiveNoEstimate() { + assertEquals(DownloadEta.UNKNOWN, DownloadEta.secondsRemaining(400 * MI, 0L, MI)); + assertEquals(DownloadEta.UNKNOWN, DownloadEta.secondsRemaining(400 * MI, -1L, MI)); + assertEquals(DownloadEta.UNKNOWN, DownloadEta.secondsRemaining(-1L, GI, MI)); + assertEquals(DownloadEta.UNKNOWN, DownloadEta.secondsRemaining(400 * MI, GI, -1L)); + } + + /** UNKNOWN composes with EtaSmoother, which uses the same sentinel for "no honest estimate". */ + @Test + public void unknownMatchesTheSmootherSentinel() { + assertEquals(org.iiab.controller.install.domain.EtaSmoother.UNKNOWN, + (int) DownloadEta.UNKNOWN); + } + + // ---- the threshold, and what must never trip it ------------------------- + + @Test + public void exceedsComparesAgainstTheCallersBudget() { + assertTrue(DownloadEta.exceeds(3601, 3600)); + assertFalse(DownloadEta.exceeds(3600, 3600)); + assertFalse(DownloadEta.exceeds(60, 3600)); + } + + /** + * Not knowing is not the same as knowing it is bad. If UNKNOWN tripped the threshold, the offer + * would fire on every connection hiccup — which is the automatic behaviour ADR-4893 rejects. + */ + @Test + public void noEstimateNeverTripsTheThreshold() { + assertFalse(DownloadEta.exceeds(DownloadEta.UNKNOWN, 0L)); + assertFalse(DownloadEta.exceeds(DownloadEta.UNKNOWN, 3600L)); + } + + // ---- the baseline, which is what makes a rate mean anything ------------- + + @Test + public void aRateIsReadAgainstWhatThisLinkAlreadyManaged() { + assertEquals(100L, DownloadEta.percentOfBaseline(3 * MI, 3 * MI)); + assertEquals(50L, DownloadEta.percentOfBaseline(MI, 2 * MI)); + // 20 KiB/s against a 3 MiB/s baseline: under 1%, i.e. the network changed under us. + assertTrue(DownloadEta.percentOfBaseline(20 * KI, 3 * MI) < 1L); + } + + @Test + public void aMissingBaselineGivesNoComparison() { + assertEquals(DownloadEta.UNKNOWN, DownloadEta.percentOfBaseline(MI, 0L)); + assertEquals(DownloadEta.UNKNOWN, DownloadEta.percentOfBaseline(MI, -1L)); + assertEquals(DownloadEta.UNKNOWN, DownloadEta.percentOfBaseline(-1L, MI)); + } + + /** A stalled transfer is 0% of its baseline, which is a reading — not a missing one. */ + @Test + public void aStalledTransferIsZeroPercentNotUnknown() { + assertEquals(0L, DownloadEta.percentOfBaseline(0L, 3 * MI)); + } +} From 5e1598b1768ba8f0c5d10ac40508dca29a276477 Mon Sep 17 00:00:00 2001 From: "Luis Guzman (AppDevForAll)" Date: Thu, 13 Aug 2026 01:20:30 -0600 Subject: [PATCH 4/6] ADFA-4895 fix(download): the estimate moves, and each line gets a table its own size MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both found on device. It read "about 26 min left" from 23% to 48%, then "almost done" from 52% to the end, on a download that took sixty seconds. Two causes in EtaSmoother, and the second is the one that mattered: - It adopts its first reading immediately. That reading lands while aria2 is still ramping, at around 1 MB/s, which is the worst estimate of the whole run — and it became the value that stuck. - Its dwell only advances while the bucket holds steady. A figure that moves every tick resets the window on every tick, so it never elapses and nothing ever replaces the first reading. A 15s dwell made that certain rather than likely. The download no longer smooths at all. The two signals are not alike: extraction wobbles because files decompress at wildly different speeds, while a transfer rate is comparatively steady — 34 to 40 MiB/s across the whole measured run. Fed a steady rate the estimate moves on its own, and moving is what an estimate is for. bucketOf is still used, for the minutes formatting; verify and extract keep their 5s smoother untouched, because there the wobble is real. Expect the first seconds to fall quickly from a large number as aria2 takes speed. That is the honest reading. If it reads badly, the answer is to withhold the estimate until the rate settles — not to freeze it again. Before the transfer starts the line carries two things — "0%" and "Test IPv4" — and pushing them through the three-column row left them visibly off-balance, with a hole where the third figure would be. ADFA-5118's row --- .../install/presentation/InstallService.java | 26 +++++----- .../controller/redesign/LibraryActivity.java | 47 ++++++++++++------- .../src/main/res/layout/activity_library.xml | 41 ++++++++++++---- 3 files changed, 76 insertions(+), 38 deletions(-) diff --git a/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallService.java b/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallService.java index 807cde0c8..0a551ddbc 100644 --- a/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallService.java +++ b/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallService.java @@ -326,15 +326,6 @@ private void startRootfsDownload() { if (aria2Manager == null) aria2Manager = new Aria2Manager(); aria2Manager.startDownload(this, directUrl, new Aria2Manager.DownloadListener() { - /** - * ADFA-4895: a longer dwell than the extract bar's five seconds. That one debounces - * files decompressing at different speeds — noise that passes in a moment. A network - * degrades and recovers over tens of seconds, so a short window would let the estimate - * chase every dip and make the label the least trustworthy thing on the screen. - */ - private final org.iiab.controller.install.domain.EtaSmoother etaSmoother = - new org.iiab.controller.install.domain.EtaSmoother(15000L); - @Override public void onProgress(int percentage, String speed, String eta) { // Still live, and not a leftover: Aria2NetworkProfiler reports through this form @@ -350,9 +341,20 @@ public void onProgress(int percentage, String speed, String eta) { public void onProgress(int percentage, String speed, String eta, long bytesPerSecond, long etaSeconds) { if (cancelled) return; - int bucket = etaSmoother.smooth( - org.iiab.controller.install.domain.EtaSmoother.bucketOf(etaSeconds), - android.os.SystemClock.elapsedRealtime()); + // ADFA-4895: no smoothing here, deliberately, and it is not an oversight — a first + // pass used EtaSmoother and the label froze at "about 26 min" for half a download + // that took sixty seconds. Two reasons, and the second is the one that matters: + // the smoother adopts its first reading immediately, which lands while aria2 is + // still ramping and is the worst estimate of the whole run; and its dwell only + // advances while the value holds steady, so a figure that moves every tick resets + // the window forever and nothing ever replaces that first reading. + // + // The deeper reason is that this signal does not need it. Extraction wobbles + // because files decompress at wildly different speeds; a transfer rate over a + // network is comparatively steady — 34 to 40 MiB/s across a whole run, measured. + // Fed a steady rate the estimate moves smoothly on its own, and moving is what an + // estimate is supposed to do. + int bucket = org.iiab.controller.install.domain.EtaSmoother.bucketOf(etaSeconds); InstallProgressRepository.get().postDownloading(percentage, speed, formatEta(bucket)); updateNotification(getString(R.string.install_status_os_download, percentage, speed)); } diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/LibraryActivity.java b/controller/app/src/main/java/org/iiab/controller/redesign/LibraryActivity.java index a675d2ce4..e9cf1719d 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/LibraryActivity.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/LibraryActivity.java @@ -56,7 +56,10 @@ public class LibraryActivity extends AppCompatActivity implements ServerControll private LottieAnimationView bootGate; private View installProgress; - private android.widget.TextView installStatus, installDetail, installPercent, installEta, installRate; + private android.widget.TextView installStatus, installDetail, installPercent, installEta; + // ADFA-4895: the three-column row, shown only once the transfer is really running. + private android.widget.TextView dlPercent, dlRate, dlEta; + private View downloadRow; private View installPercentRow; // ADFA-5118: the %/ETA weighted-column row private android.widget.ProgressBar installBar; private boolean gateDismissed = false; @@ -129,8 +132,11 @@ protected void onCreate(Bundle savedInstanceState) { installDetail = findViewById(R.id.k2go_install_detail); installPercentRow = findViewById(R.id.k2go_install_percent_row); installPercent = findViewById(R.id.k2go_install_percent); - installRate = findViewById(R.id.k2go_install_rate); // ADFA-4895 installEta = findViewById(R.id.k2go_install_eta); + downloadRow = findViewById(R.id.k2go_download_row); // ADFA-4895 + dlPercent = findViewById(R.id.k2go_download_percent); + dlRate = findViewById(R.id.k2go_download_rate); + dlEta = findViewById(R.id.k2go_download_eta); // ADFA-4947: shared ellipsis animators (fixed-width so the centered lines don't shift). bootEllipsis = new org.iiab.controller.util.EllipsisAnimator(installStatus, true); readingEllipsis = new org.iiab.controller.util.EllipsisAnimator(installDetail, true); @@ -333,28 +339,33 @@ private void showInstallProgress(InstallState st) { installProgress.setVisibility(View.VISIBLE); if (installBar != null) installBar.setVisibility(View.VISIBLE); // ADFA-4837: boot/shutdown hide it if (installPercentRow != null) installPercentRow.setVisibility(View.GONE); - if (installRate != null) installRate.setVisibility(View.GONE); // ADFA-4895: only DOWNLOADING has a rate + if (downloadRow != null) downloadRow.setVisibility(View.GONE); // ADFA-4895 if (st.phase == InstallState.Phase.DOWNLOADING) { installStatus.setText(getString(R.string.k2go_downloading_library)); installBar.setIndeterminate(false); installBar.setProgress(st.percent); - // ADFA-4895: the download joins the weighted row instead of concatenating its figures - // into one centred line. It has three of them now — % , rate and estimate — and a rate - // that swings between "412KiB/s" and "37MiB/s" would drag everything beside it sideways - // on every tick, which is the dance ADFA-4910 and ADFA-5118 already fixed for extract. - // Each figure gets its own cell, so none of them can move another. - if (installPercentRow != null) { + // ADFA-4895: one table per line, sized to the line, rather than one table stretched + // over both. Before the transfer starts the line carries two things — "0%" and + // "Test IPv4" — and pushing those through a three-column row leaves a visible hole + // where the third would be. Once a rate and an estimate are both real there are three, + // and they get a row built for three. Either way every figure sits in a fixed column, + // so a rate swinging between "412KiB/s" and "37MiB/s" cannot drag the % sideways — + // the dance ADFA-4910 and ADFA-5118 already fixed for extract. + boolean threeUp = !st.speed.isEmpty() && !st.eta.isEmpty(); + if (threeUp && downloadRow != null) { + downloadRow.setVisibility(View.VISIBLE); + dlPercent.setText(pct(st.percent)); + dlRate.setText(st.speed); + dlEta.setText("· " + st.eta); + } else if (installPercentRow != null) { installPercentRow.setVisibility(View.VISIBLE); installPercent.setText(pct(st.percent)); - boolean hasRate = !st.speed.isEmpty(); - boolean hasEta = !st.eta.isEmpty(); - installRate.setText(hasRate ? st.speed : ""); - installRate.setVisibility(hasRate ? View.VISIBLE : View.GONE); - installEta.setText(hasEta ? "· " + st.eta : ""); - installEta.setVisibility(hasEta ? View.VISIBLE : View.GONE); - // With nothing to its right the % owns the row and centres, exactly as ADFA-5118 - // does before its own estimate appears. - installPercent.setGravity((hasRate || hasEta) + boolean hasSecond = !st.speed.isEmpty(); + installEta.setText(hasSecond ? st.speed : ""); + installEta.setVisibility(hasSecond ? View.VISIBLE : View.GONE); + // Alone, the % owns the row and centres — the rule ADFA-5118 already applies + // before its own estimate appears. + installPercent.setGravity(hasSecond ? android.view.Gravity.END : android.view.Gravity.CENTER_HORIZONTAL); } installDetail.setText(""); diff --git a/controller/app/src/main/res/layout/activity_library.xml b/controller/app/src/main/res/layout/activity_library.xml index 12fb8b72c..914163f8f 100644 --- a/controller/app/src/main/res/layout/activity_library.xml +++ b/controller/app/src/main/res/layout/activity_library.xml @@ -119,23 +119,48 @@ android:gravity="end" android:textAppearance="?attr/textAppearanceBodySmall" android:textColor="@color/k2go_boot_ink" /> - + + + + + + Date: Thu, 13 Aug 2026 05:03:05 -0600 Subject: [PATCH 5/6] =?UTF-8?q?ADFA-4895=20fix(download):=20review=20pass?= =?UTF-8?q?=20=E2=80=94=20cancel=20actually=20cancels,=20and=20the=20fragi?= =?UTF-8?q?le=20regex=20becomes=20testable?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four findings from the review of this PR. Cancel could be ignored. aria2Process is assigned on the download thread and read by stopDownload() on the caller's, and it was not volatile — a stale null there means the process is never destroyed and the user's stop does nothing at all. The earlier commit made the flag volatile and left the handle, which is the only thing that actually has to be killed. Half a fix reads worse than none, because it looks finished. The most breakable part had no test. The completed/total pattern lived inside Aria2Manager, an Android class holding a live process and a Handler, so a regex against a third party's output format was the one piece nothing could reach. It moves to Aria2ProgressLine, pure, with six cases. A change to aria2's formatting now fails a test instead of quietly producing a wrong estimate on a device. Pinned there too, documented rather than endorsed: a --check-integrity line carries the same shape, so this parser would read verification progress as transfer progress. Harmless today — the estimate is recomputed on the next real progress line — and written down so it is a known limit. Requiring DL: on the same line is the fix if it ever bites. Three dead methods removed with their tests: DownloadEta.percentOfBaseline, DownloadEta.exceeds and Aria2Exit.worthAnotherAttempt had no production caller. They were written for the next step, which is the same excuse that got killOrphan deleted earlier; the ticket that needs them can bring them with a caller. And an unreachable guard in ByteToken: the scanner never consumes a '-', so the sign check could not fire. Replaced by a comment saying why it is not needed. Left open on purpose, both pending a decision: the percentage shifts once when the two-column row hands over to the three-column one, and InstallState now carries an estimate two different ways — its own field for the download, ADFA-5118's speed slot for verify and extract. --- .../org/iiab/controller/Aria2Manager.java | 33 +++++---- .../controller/download/domain/Aria2Exit.java | 5 -- .../download/domain/Aria2ProgressLine.java | 70 +++++++++++++++++++ .../controller/download/domain/ByteToken.java | 4 +- .../download/domain/DownloadEta.java | 31 -------- .../download/domain/Aria2ExitTest.java | 20 ++---- .../download/domain/DownloadEtaTest.java | 65 ++++++++++------- controller/docs/operation-model-roadmap.svg | 8 ++- 8 files changed, 139 insertions(+), 97 deletions(-) create mode 100644 controller/app/src/main/java/org/iiab/controller/download/domain/Aria2ProgressLine.java diff --git a/controller/app/src/main/java/org/iiab/controller/Aria2Manager.java b/controller/app/src/main/java/org/iiab/controller/Aria2Manager.java index 62c3f52b1..4618b5e20 100644 --- a/controller/app/src/main/java/org/iiab/controller/Aria2Manager.java +++ b/controller/app/src/main/java/org/iiab/controller/Aria2Manager.java @@ -29,11 +29,18 @@ import org.iiab.controller.download.domain.DownloadVerifier; import org.iiab.controller.download.domain.ByteToken; import org.iiab.controller.download.domain.DownloadEta; +import org.iiab.controller.download.domain.Aria2ProgressLine; public class Aria2Manager { private static final String TAG = "IIAB-Aria2-Native"; - private Process aria2Process; + /** + * ADFA-4895: volatile for the same reason as the flag below, and it is the more important of + * the two. It is assigned on the download thread and read by {@code stopDownload()} on the + * caller's, so a stale null there means the process is never destroyed and the user's cancel + * does nothing at all. + */ + private volatile Process aria2Process; /** * ADFA-4895: volatile. It is written by {@code stopDownload()} on the caller's thread and read * by the download thread's loop and its catch block, so without this a stop could go unseen and @@ -238,11 +245,7 @@ public void startDownload(Context context, String url, DownloadListener listener // Regex to capture typical Aria2c output // Example: [#2089b0 400MiB/1.0GiB(39%) CN:4 DL:4.5MiB ETA:2m20s] Pattern pattern = Pattern.compile("\\((\\d+)%\\).*?DL:([^\\s]+).*?ETA:([^\\s\\]]+)"); - // ADFA-4895: the same line also carries "400MiB/1.0GiB" — completed and total. A - // second, separate pattern on purpose: if it fails to match, the estimate is simply - // unknown and the progress line above is untouched. Folding it into the pattern - // that already works would put a working display at the mercy of a new regex. - Pattern sizes = Pattern.compile("([\\d.]+[A-Za-z]*)/([\\d.]+[A-Za-z]*)\\(\\d+%\\)"); + while ((line = reader.readLine()) != null) { if (isCancelled) { @@ -267,17 +270,13 @@ public void startDownload(Context context, String url, DownloadListener listener // string — so nothing downstream could compare it to anything or divide a // remaining size by it. long bytesPerSecond = ByteToken.parse(matcher.group(2)); - long etaSeconds = DownloadEta.UNKNOWN; - Matcher sm = sizes.matcher(line); - if (sm.find()) { - long done = ByteToken.parse(sm.group(1)); - // The Metalink's size is the authority when we have it: it is what the - // integrity gate will check against, so the estimate and the verdict - // are measured against the same number. - long total = (mf != null && mf.sizeBytes() > 0) - ? mf.sizeBytes() : ByteToken.parse(sm.group(2)); - etaSeconds = DownloadEta.secondsRemaining(done, total, bytesPerSecond); - } + // The Metalink's size is the authority when we have it: it is what the + // integrity gate will check against, so the estimate and the verdict are + // measured against the same number. + long done = Aria2ProgressLine.completedBytes(line); + long total = (mf != null && mf.sizeBytes() > 0) + ? mf.sizeBytes() : Aria2ProgressLine.declaredTotalBytes(line); + long etaSeconds = DownloadEta.secondsRemaining(done, total, bytesPerSecond); final long rate = bytesPerSecond; final long secs = etaSeconds; mainHandler.post(() -> listener.onProgress(percent, speed, eta, rate, secs)); diff --git a/controller/app/src/main/java/org/iiab/controller/download/domain/Aria2Exit.java b/controller/app/src/main/java/org/iiab/controller/download/domain/Aria2Exit.java index 462220d20..08e00ba54 100644 --- a/controller/app/src/main/java/org/iiab/controller/download/domain/Aria2Exit.java +++ b/controller/app/src/main/java/org/iiab/controller/download/domain/Aria2Exit.java @@ -111,9 +111,4 @@ public static String label(int exitCode) { } } - /** Whether trying the same download again could plausibly end differently. */ - public static boolean worthAnotherAttempt(int exitCode) { - Kind k = kindOf(exitCode); - return k == Kind.TRANSIENT || k == Kind.STALLED; - } } diff --git a/controller/app/src/main/java/org/iiab/controller/download/domain/Aria2ProgressLine.java b/controller/app/src/main/java/org/iiab/controller/download/domain/Aria2ProgressLine.java new file mode 100644 index 000000000..b00c8525d --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/download/domain/Aria2ProgressLine.java @@ -0,0 +1,70 @@ +/* + * ============================================================================ + * Name : Aria2ProgressLine.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : ADFA-4895. Pure rule: pull the figures out of one line of + * aria2 console output. No Android, no I/O. + * ============================================================================ + */ +package org.iiab.controller.download.domain; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Reads one line of aria2's summary output. + * + *

A real line looks like this: + * + *

[#2089b0 400MiB/1.0GiB(39%) CN:4 DL:4.5MiB ETA:2m20s]
+ * + *

Why this is its own class. It began as a second {@link Pattern} inside + * {@code Aria2Manager}, which is an Android class holding a live process and a Handler — so the + * most breakable part of the change, a regex against a third party's output format, was the one + * part no test could reach. Here it is reachable, and a change to aria2's formatting fails a test + * instead of quietly producing a wrong estimate on a device. + * + *

Deliberately separate from the progress pattern that already worked. The percentage + * and rate the screen has always shown come from a different expression in {@code Aria2Manager}. + * If this one stops matching, the estimate goes unknown and the line the user reads is untouched. + */ +public final class Aria2ProgressLine { + + /** + * The completed/total pair that precedes the percentage. + * + *

Both halves are a number with an optional unit, so {@code 400MiB/1.0GiB(39%)} yields + * {@code 400MiB} and {@code 1.0GiB}. Anchored on the {@code (NN%)} that follows, which is what + * keeps it from matching the {@code CN:4} or a path with a slash in it. + */ + private static final Pattern SIZES = + Pattern.compile("([\\d.]+[A-Za-z]*)/([\\d.]+[A-Za-z]*)\\(\\d+%\\)"); + + private Aria2ProgressLine() { + } + + /** Bytes transferred so far, or {@link ByteToken#UNKNOWN} if the line does not carry them. */ + public static long completedBytes(String line) { + Matcher m = matcher(line); + return m == null ? ByteToken.UNKNOWN : ByteToken.parse(m.group(1)); + } + + /** + * The size aria2 believes it is fetching, or {@link ByteToken#UNKNOWN}. + * + *

Prefer the Metalink's figure over this one where both exist: the Metalink is what the + * integrity gate checks against, so using it keeps the estimate and the verdict measured + * against the same number. + */ + public static long declaredTotalBytes(String line) { + Matcher m = matcher(line); + return m == null ? ByteToken.UNKNOWN : ByteToken.parse(m.group(2)); + } + + private static Matcher matcher(String line) { + if (line == null || line.isEmpty()) return null; + Matcher m = SIZES.matcher(line); + return m.find() ? m : null; + } +} diff --git a/controller/app/src/main/java/org/iiab/controller/download/domain/ByteToken.java b/controller/app/src/main/java/org/iiab/controller/download/domain/ByteToken.java index 6cd998128..20c92330a 100644 --- a/controller/app/src/main/java/org/iiab/controller/download/domain/ByteToken.java +++ b/controller/app/src/main/java/org/iiab/controller/download/domain/ByteToken.java @@ -65,7 +65,9 @@ public static long parse(String token) { } catch (NumberFormatException e) { return UNKNOWN; } - if (value < 0 || Double.isNaN(value) || Double.isInfinite(value)) return UNKNOWN; + // No sign check: the scan above never consumes a '-', so a negative token has + // already been rejected before we get here. + if (Double.isNaN(value) || Double.isInfinite(value)) return UNKNOWN; String unit = t.substring(i).trim(); // aria2 writes a trailing "/s" on some fields; the rate and the size share this parser. diff --git a/controller/app/src/main/java/org/iiab/controller/download/domain/DownloadEta.java b/controller/app/src/main/java/org/iiab/controller/download/domain/DownloadEta.java index 9a60b97bf..8bfb56074 100644 --- a/controller/app/src/main/java/org/iiab/controller/download/domain/DownloadEta.java +++ b/controller/app/src/main/java/org/iiab/controller/download/domain/DownloadEta.java @@ -46,35 +46,4 @@ public static long secondsRemaining(long completedBytes, long totalBytes, long b return (totalBytes - completedBytes) / bytesPerSecond; } - /** - * Whether the estimate is far enough out to be worth telling the user about. - * - *

Deliberately a comparison against a budget the caller supplies rather than a constant - * here: what counts as too long depends on what is being fetched and on what the app intends - * to offer, and this class should not know either. It answers the question; it does not decide - * that the question was worth asking. - * - *

An {@link #UNKNOWN} estimate is never "too long". Not knowing is not the same as knowing - * it is bad, and acting on a rate gap would fire the offer every time a connection hiccups. - */ - public static boolean exceeds(long etaSeconds, long budgetSeconds) { - return etaSeconds != UNKNOWN && etaSeconds > budgetSeconds; - } - - /** - * How the current rate compares with what this same transfer managed at the start, as a - * percentage of the baseline. {@link #UNKNOWN} when either figure is missing. - * - *

This is the reading that makes "20 KiB/s" mean something. On its own the number says - * nothing — it may be all this link has ever done. Against a baseline of three MiB/s measured - * ten minutes ago on the same connection, it says the network changed under us, which is a - * different statement and earns a different offer. - * - *

The baseline is the one {@code Aria2NetworkProfiler} already measures before the transfer - * starts and currently discards after choosing an IP stack. - */ - public static long percentOfBaseline(long bytesPerSecond, long baselineBytesPerSecond) { - if (bytesPerSecond < 0 || baselineBytesPerSecond <= 0) return UNKNOWN; - return (bytesPerSecond * 100L) / baselineBytesPerSecond; - } } diff --git a/controller/app/src/test/java/org/iiab/controller/download/domain/Aria2ExitTest.java b/controller/app/src/test/java/org/iiab/controller/download/domain/Aria2ExitTest.java index 6aac5a2d2..752badc40 100644 --- a/controller/app/src/test/java/org/iiab/controller/download/domain/Aria2ExitTest.java +++ b/controller/app/src/test/java/org/iiab/controller/download/domain/Aria2ExitTest.java @@ -63,26 +63,14 @@ public void codesOutsideTheTableAreUnknown() { } } - // ---- the question the caller actually asks ------------------------------ - - @Test - public void onlyTransientAndStalledAreWorthAnotherAttempt() { - assertTrue(Aria2Exit.worthAnotherAttempt(6)); - assertTrue(Aria2Exit.worthAnotherAttempt(5)); - assertFalse(Aria2Exit.worthAnotherAttempt(0)); - assertFalse(Aria2Exit.worthAnotherAttempt(9)); - assertFalse("unknown must not opt in by default", Aria2Exit.worthAnotherAttempt(1)); - } - /** - * A full disk is the case where retrying is actively harmful: every attempt re-downloads - * gigabytes that cannot be written. Pinned separately because it is the one a generous default - * would get wrong. + * A full disk is the case where retrying would be actively harmful: every attempt re-downloads + * gigabytes that cannot be written, on a connection the user may be paying for by the megabyte. + * Pinned on its own because it is the one a generous default would get wrong. */ @Test - public void aFullDiskIsNeverRetried() { + public void aFullDiskIsPermanentAndNotSomethingToTryAgain() { assertEquals(Kind.PERMANENT, Aria2Exit.kindOf(9)); - assertFalse(Aria2Exit.worthAnotherAttempt(9)); } // ---- labels ------------------------------------------------------------- diff --git a/controller/app/src/test/java/org/iiab/controller/download/domain/DownloadEtaTest.java b/controller/app/src/test/java/org/iiab/controller/download/domain/DownloadEtaTest.java index 5b8bc6481..0ac8d73ad 100644 --- a/controller/app/src/test/java/org/iiab/controller/download/domain/DownloadEtaTest.java +++ b/controller/app/src/test/java/org/iiab/controller/download/domain/DownloadEtaTest.java @@ -107,45 +107,62 @@ public void unknownMatchesTheSmootherSentinel() { (int) DownloadEta.UNKNOWN); } - // ---- the threshold, and what must never trip it ------------------------- + // ---- reading the figures out of a real line ------------------------------ + + private static final String LINE = "[#2089b0 400MiB/1.0GiB(39%) CN:4 DL:4.5MiB ETA:2m20s]"; + + /** + * The whole point of extracting this from Aria2Manager: the most breakable part of the change + * is a regex against a third party's output format, and there it was unreachable by any test. + */ + @Test + public void pullsCompletedAndTotalOutOfARealLine() { + assertEquals(400 * MI, Aria2ProgressLine.completedBytes(LINE)); + assertEquals(GI, Aria2ProgressLine.declaredTotalBytes(LINE)); + } @Test - public void exceedsComparesAgainstTheCallersBudget() { - assertTrue(DownloadEta.exceeds(3601, 3600)); - assertFalse(DownloadEta.exceeds(3600, 3600)); - assertFalse(DownloadEta.exceeds(60, 3600)); + public void theWholeChainFromLineToEstimate() { + long done = Aria2ProgressLine.completedBytes(LINE); + long total = Aria2ProgressLine.declaredTotalBytes(LINE); + long rate = ByteToken.parse("4.5MiB"); + // 1 GiB - 400 MiB left at 4.5 MiB/s + assertEquals((total - done) / rate, DownloadEta.secondsRemaining(done, total, rate)); } /** - * Not knowing is not the same as knowing it is bad. If UNKNOWN tripped the threshold, the offer - * would fire on every connection hiccup — which is the automatic behaviour ADR-4893 rejects. + * The CN:4 is the trap: a bare "4" beside a slash-free field must not be mistaken for a pair. + * The pattern is anchored on the (NN%) that follows the sizes, which is what excludes it. */ @Test - public void noEstimateNeverTripsTheThreshold() { - assertFalse(DownloadEta.exceeds(DownloadEta.UNKNOWN, 0L)); - assertFalse(DownloadEta.exceeds(DownloadEta.UNKNOWN, 3600L)); + public void doesNotMatchTheConnectionCountOrAPath() { + assertEquals(ByteToken.UNKNOWN, Aria2ProgressLine.completedBytes("[#2089b0 CN:4 DL:4.5MiB]")); + assertEquals(ByteToken.UNKNOWN, + Aria2ProgressLine.completedBytes("Downloading /data/foo/bar to /data/baz")); } - // ---- the baseline, which is what makes a rate mean anything ------------- - @Test - public void aRateIsReadAgainstWhatThisLinkAlreadyManaged() { - assertEquals(100L, DownloadEta.percentOfBaseline(3 * MI, 3 * MI)); - assertEquals(50L, DownloadEta.percentOfBaseline(MI, 2 * MI)); - // 20 KiB/s against a 3 MiB/s baseline: under 1%, i.e. the network changed under us. - assertTrue(DownloadEta.percentOfBaseline(20 * KI, 3 * MI) < 1L); + public void aLineWithoutTheFiguresGivesUnknownRatherThanZero() { + for (String l : new String[]{null, "", "[#2089b0 FileAlloc:0B/0B]", "no numbers here"}) { + assertEquals(String.valueOf(l), ByteToken.UNKNOWN, Aria2ProgressLine.completedBytes(l)); + assertEquals(String.valueOf(l), ByteToken.UNKNOWN, Aria2ProgressLine.declaredTotalBytes(l)); + } } + /** + * Documented, not endorsed: a --check-integrity line carries the same shape, so this parser + * would read verification progress as transfer progress. Harmless today because the estimate is + * recomputed on the next real progress line, and noted so it is a known limit rather than a + * surprise. If it ever matters, require DL: on the same line. + */ @Test - public void aMissingBaselineGivesNoComparison() { - assertEquals(DownloadEta.UNKNOWN, DownloadEta.percentOfBaseline(MI, 0L)); - assertEquals(DownloadEta.UNKNOWN, DownloadEta.percentOfBaseline(MI, -1L)); - assertEquals(DownloadEta.UNKNOWN, DownloadEta.percentOfBaseline(-1L, MI)); + public void aChecksumLineIsCurrentlyIndistinguishable() { + String chk = "[#2089b0 CHK:512MiB/1.0GiB(50%)]"; + assertEquals(512 * MI, Aria2ProgressLine.completedBytes(chk)); } - /** A stalled transfer is 0% of its baseline, which is a reading — not a missing one. */ @Test - public void aStalledTransferIsZeroPercentNotUnknown() { - assertEquals(0L, DownloadEta.percentOfBaseline(0L, 3 * MI)); + public void unitsWithoutTheBinaryMarkerStillParse() { + assertEquals(1000_000L, Aria2ProgressLine.completedBytes("[#x 1MB/2MB(50%)]")); } } diff --git a/controller/docs/operation-model-roadmap.svg b/controller/docs/operation-model-roadmap.svg index 0ddb13132..86f4463da 100644 --- a/controller/docs/operation-model-roadmap.svg +++ b/controller/docs/operation-model-roadmap.svg @@ -1,4 +1,4 @@ - + Operation model — ticket map, dependencies, and the standing directive Three columns that mean delivered / in flight / next, with arrows for what directs what. Teal cards are hubs: arrows leave them because the rest of the board reads them. The band at the top is the standing directive and its ledger of facts — every change that touches a fact updates a row. Flip a dot's class as work lands: s-done, s-doing, s-todo.