[BW-DL-04] Project WorkManager waiting and retry state into Downloads UX #19
Loading…
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Classification
Active follow-up from #15 / GitHub PR #106.
Problem / opportunity
BookDownloadermarks a retryable transfer attempt Failed beforeBookDownloadWorkerreturnsResult.retry(). WorkManager then owns backoff/retry. Network constraints can also hold a request waiting for Wi-Fi/unmetered service. The current Downloads UI reads only the durable manifest, so it can say Failed while WorkManager is already retrying, or merely Incomplete while work is intentionally waiting for network conditions.User value
Listeners can tell the difference between 'BookWave will continue automatically', 'waiting for Wi-Fi', and 'this needs me to retry'.
Scope
(server,item).Explicitly out of scope
Dependencies
Architecture seams affected
WorkManagerDownloadScheduler/ unique work naming contract.Server / API assumptions
None. This is Android execution-state evidence only.
Storage / migration implications
None. WorkManager remains the execution source; Room remains the durable manifest/file source.
Privacy / security
WorkInfo tags/input data include profile/server/item identity internally. UI/logging must not expose raw server IDs, item IDs, titles or profile identifiers when the active profile cannot see them. Presentation should use generic state text on title-hidden rows.
Automated-test level
Device / platform acceptance
Estimated effort
Medium.
Implementation risk
Medium. WorkManager observation can become lifecycle-heavy or state-duplicative if its types leak upward.
Recommended sequence
After #17/#18.
Acceptance criteria
Links
BW-DL-04 canonical implementation-readiness record
Status of this record: canonical investigation result. It supersedes the broad implementation sketch in the migrated issue body where current main is more specific.
Investigated main:
88ae231ddcNo branch, production code, PR or CI run was created for this investigation.
1. Prerequisite and overlap status
df949add9d. Running -> Pause, Paused -> Resume, Failed -> Retry; Queued/Waiting/Retrying/Complete are actionless.One stale specification detail must not drive this implementation: PRODUCT_SPEC DL-005 still contains a candidate-algorithm line describing uniqueness by profile/server/item. Current production code and ADR-0018 intentionally use one physical work identity per server/item, with profile identity captured only as authorization input. #19 must follow the current code/ADR ownership model.
2. Confirmed current architecture
Current flow is:
User Download/Resume/Retry
→ DownloadsViewModel / DownloadBookUseCase
→ DownloadRepository.request + durable manifest
→ DownloadRepository.markQueued only when resuming durable Paused
→ DownloadScheduler
→ WorkManagerDownloadScheduler
→ unique OneTimeWorkRequest
→ BookDownloadWorker
→ BookDownloader / FileDownloader
→ Room manifest + file rows
→ DownloadsViewModel
→ DownloadRecoveryPolicy
→ DownloadRow / DownloadsScreen
Current seams and ownership:
Important current-main correction: production code does not currently write the book-level durable DownloadState.Running. File rows move while the book row normally remains Queued until Complete, Failed or Paused. Therefore truthful “Downloading” is genuinely transient execution evidence today. Keep support for durable Running because the enum and compatibility policy contain it, but do not add a Room write merely to make Running appear.
The root defect is now exact: BookDownloader records durable Failed whenever a transfer attempt fails. BookDownloadWorker then returns Result.retry() for a retryable AppError. The same logical download is therefore legitimately durable Failed + WorkManager ENQUEUED for another attempt. Current DownloadsViewModel omits executionEvidence when calling DownloadRecoveryPolicy, so it shows terminal Failed even though WorkManager will continue. Constraints have the analogous gap.
3. Unique-work identity contract
The authoritative physical-download identity is BookDownloadWorker.nameFor(serverId, itemId):
download::
Current request contract:
Profile identity is not part of physical work identity. A later profile switch must not make the adapter look for a different job. The work request’s profileId is the credential/authorization owner for that attempt.
WorkManager lifecycle implications verified against AndroidX WorkManager APIs:
4. Chosen ownership model
The ownership invariant is unchanged:
Room / OfflineBook owns durable physical truth. WorkManager owns transient execution truth. DownloadRecoveryPolicy combines them for presentation. Neither is allowed to impersonate the other.
Consequences:
5. Chosen domain adapter contract
Create:
domain/src/main/kotlin/com/example/shelfplayer/domain/download/DownloadExecutionObserver.kt
with the exact platform-neutral shape:
Semantics:
The existing transient model in domain/download/DownloadRecovery.kt is already the correct narrow model and should be reused unchanged:
Do not add Succeeded or Failed as durable-like execution evidence in #19. WorkInfo terminal status says what happened to a WorkRequest, not whether the durable media manifest is valid. BookDownloadWorker also deliberately returns success for malformed/missing identity input, so WorkInfo SUCCEEDED is not sufficient authority for “Downloaded”.
6. Exact WorkInfo mapping
Android WorkManager does not expose “waiting for Wi-Fi” as a WorkInfo.State reason. ENQUEUED only says the work is eligible when constraints/resources allow it. BLOCKED means unfinished prerequisite work, not “constraints are unmet”.
Map WorkInfo as follows:
If an ENQUEUED request has runAttemptCount > 0 and its network constraint is currently unmet, Waiting wins because the present reason BookWave can prove is “cannot run on this network”; when the network becomes allowed it naturally becomes Retrying until WorkManager starts it.
Current scheduler creates only CONNECTED or UNMETERED download constraints. If a future/foreign constraint value appears, #19 must not guess a waiting reason it cannot prove; treat network as not proven-blocking and continue with Queued/Retrying classification, plus a generic non-identifying diagnostic if useful.
Do not use stopReason as the core contract. It is not needed for this distinction, has platform-version limitations, and Result.retry() is not represented as a useful “retry reason” there.
Do not expose nextScheduleTimeMillis as an ETA. Android defines it as the earliest scheduling time after delay/period/backoff, and it does not include every constraint/system condition. It may be useful in adapter tests/diagnostics but not user copy.
Platform references checked during this investigation:
Repository WorkManager version at this SHA is 2.11.2. The APIs required above exist in that version. Do not turn #19 into a WorkManager dependency-upgrade task.
7. Observation and lifecycle design
Forward identity metadata
Modify WorkManagerDownloadScheduler so every new BookDownloadWorker request adds one explicit tag equal to the already-authoritative unique work name:
tag = BookDownloadWorker.nameFor(serverId, itemId)
Compute the name once and use that exact string for both addTag(name) and enqueueUniqueWork(name, ...).
This does not create a second identity scheme and does not change scheduling behavior. It only makes the logical identity recoverable from WorkInfo.tags, because WorkInfo does not expose inputData or the unique-work name itself.
Do not put profileId in tags.
Aggregate observation
The Android implementation belongs in:
app/src/main/kotlin/com/example/shelfplayer/download/WorkManagerDownloadExecutionObserver.kt
It should:
Reduction if multiple WorkInfo records are returned for one key:
Running > Waiting > Retrying > Queued > Finished > Cancelled
Unique work should prevent multiple active requests. The reduction exists only to be deterministic around retained terminal history/replacement. If multiple simultaneously active records are ever observed, log a generic anomaly count without identities.
This produces one long-lived WorkManager observer for tagged current work, not one observer per row.
Upgrade compatibility for work already enqueued before #19
Current main requests have no explicit identity tag, and a waiting/retrying job may survive an app upgrade/process restart. Do not ignore that case.
At observer start or whenever the requested key set changes:
No legacy UUID/name mapping is persisted. After a replacement/re-enqueue on #19 code, the new request has the identity tag and naturally moves to the normal aggregate path.
Rejected alternatives:
ViewModel lifecycle
Inject DownloadExecutionObserver into DownloadsViewModel.
Use downloads.observeAll() as the durable row source. For each durable emission, derive the set of keys needing transient refinement and flatMapLatest into executionObserver.observe(keys). Combine the resulting durable rows + execution map with existing totalBytes and active-profile visibleBooks.
Collection remains governed by the existing Downloads uiState:
viewModelScope + SharingStarted.WhileSubscribed(5_000)
Expected lifecycle:
A profile switch should normally not change the execution key set, because this screen is device-wide. It changes visibleBooks/title access only.
8. Durable × transient presentation truth table
This is the complete required policy. It matches the existing DownloadRecoveryPolicy and should remain the single owner.
Required scenario interpretations:
Invalid/unexpected combinations degrade conservatively rather than writing state back:
9. User-facing copy and actions
Do not redesign the row. Replace the generic “incomplete” projection with explicit recovery-state copy.
Exact English semantic copy for this slice:
“Waiting for an allowed network” is deliberate. The project already treats Android metering state as source of truth: Wi-Fi can be metered and cellular can be unmetered. Literal “Waiting for Wi-Fi” can therefore be false even when the UNMETERED constraint is the real rule.
Add equivalent Norwegian Bokmål strings in values-nb.
Keep #18 row actions exactly:
Automatic continuation must not expose Retry while BookWave/WorkManager is already going to continue.
No percent/bytes/live progress, no queue section redesign, no notification changes. Those belong to #29.
10. Privacy and profile isolation
The Downloads screen intentionally shows device-wide physical rows, while title/author visibility comes from the active profile. #19 must preserve this exact split.
Rules:
11. Process-death and stale-state acceptance model
12. Exact implementation surface
13. Ordered coding sequence
14. Automated test contract
Existing coverage already audited includes:
Required new/expanded deterministic proof:
Use WorkManagerTestInitHelper / WorkManager work-testing where it proves WorkManager query/tag/reconstruction behavior. Keep the precedence policy and most state mapping cheap/pure.
Mutation-style proof is valuable in two places and does not require introducing a mutation framework: the domain truth-table tests must fail if active Retrying stops overriding durable Failed or if Paused stops overriding stale execution; the adapter tests must fail if runAttemptCount polarity is reversed or Waiting no longer outranks Retrying when the required network is unmet.
15. Physical/device acceptance plan
No removable-SD acceptance belongs here; #20 owns it. No multi-download live progress/notification acceptance belongs here; #29 owns it.
16. Explicit non-goals
17. Known risks and guardrails
18. Unresolved questions
None blocking implementation.
The apparent “Waiting for Wi-Fi” wording ambiguity is resolved in favor of “Waiting for an allowed network” because current BookWave policy and AndroidNetworkMonitor already define Android metering state—not transport name—as the source of truth.
The historical #17 Forgejo-PR provenance gap is documentary only. The prerequisite implementation is present and tested on the exact current main investigated here.
#19 IMPLEMENTATION READY