WP-096: Google TV package storage and download reliability

Status: ✅ Done (2026-11-28). Executed on the TCL 65Q77K (EC-014, every step passed); fork PR barefootbetters/scummvm#23, merged 2026-11-28 (b757d503bb). D1–D4 answered 2026-11-28 · pre-flight READY 2026-11-28 (pre-flight-WP-096-2026-11-28) · execution prompt session-WP-096-2026-11-28. Numbering: WP-086 is the Hotspot Magnet research (✅), and WP-095 is held by the open wizard’s-skull PR, so this takes WP-096 and EC-014 (EC-011 has never been used) (wp-lifecycle §Supersession check). Phase: 5 (polish & distribution). Depends on: WP-085 (its installer, merged into the fork in barefootbetters/scummvm#13; WP-085’s one open item, an import route without a computer, isn’t needed here); the ISO-free feasibility study (the sizes this WP plans for). Unblocks: delivering licensed game-data packages to beta testers’ TVs. That also needs a host and access scheme, a separate WP (§Out of scope). Companion EC: EC-014. Pre-flight required: Yes. It changes the fork outside engines/terraglyph/ (the Android advanced mode) and changes network download code. Targets generation(s): none directly. No engine code changes. The installer is game-agnostic, and Showdown (Gen 1) sets the sizes it must handle. Estimated effort: 3–4 days, including the TCL runs.


Goal

Make the WP-085 package installer safe on a storage-constrained Google TV. It should know before it starts whether a package fits, refuse cleanly when it doesn’t, resume an interrupted download instead of starting over, confirm that what it installed is what the package held, and never lose an installed version or a save along the way. The installer is extended, not replaced.

Background

Scope

In scope

All of it lives in the advanced mode (test builds). The release build stays free of it, as WP-085 D4 requires.

1. Storage preflight

  1. Before downloading, the app computes the required space as **package size
    • installed size + headroom** (D3). It compares that with the bytes it can actually allocate on the volume that holds getFilesDir(): StorageManager.getAllocatableBytes on API 26+, and File.getUsableSpace below that. For testing, a debug-only setting can override the free-space figure (D4).
  2. The installed size comes from a new optional manifest field, installedSize (the sum of the zip’s uncompressed entry sizes). If it’s absent, the app checks the download size before downloading. Once the zip is verified, it reads the zip’s central directory for the exact extracted size and checks again before extracting.
  3. An update needs space for the zip and the new version only. The installed old version is already on disk and isn’t counted as free.
  4. If the space isn’t there, the app refuses before writing anything. It shows the bytes needed, the bytes free and the shortfall, and logs the same line (D1).
  5. Running out of space mid-download or mid-extract (ENOSPC as an IOException) deletes that package’s staging files. Any installed version stays where it is, and the log names the cause.

2. Interrupted-download recovery

  1. A network failure or a killed app keeps the partial download as <id>-<version>.zip.part, with a sidecar recording the URL, the bytes written and the server’s ETag/Last-Modified.
  2. A refusal still deletes the partial download: wrong size, wrong SHA-256, a data-only rule, or any RefusedException.
  3. A retry of the same id and version continues the download. The app re-hashes the bytes it already has, then sends Range: bytes=<n>- with If-Range. A 206 appends. A 200, a changed validator or a 416 restarts from 0. The final size and SHA-256 checks are unchanged, so a bad resume can never install.
  4. cleanStaging() keeps the .part and sidecar for the id and version being fetched, and deletes everything else in .staging/.

3. Installation integrity

  1. After extracting, the app writes packages/<id>/<version>.files.json with each entry’s path, size and CRC-32 from the zip. It sits outside the game folder, so ScummVM’s detection never sees it.
  2. The advanced mode gains a Verify action per installed package. It re-reads every file, compares size and CRC-32 with .files.json, and reports pass, or each missing or changed file.

4. Preservation

  1. A refusal, an interruption or a failure at any step never deletes or alters an installed version, its library entry or any save.
  2. Documented in the manifest doc: installedSize, the space rule, resume and Verify.

5. Interrupted installation recovery (a power cut or a killed app during extraction)

WP-085 already covers part of this at bfeaa1c7ba:

So a partly extracted game is never recorded as installed today. What’s missing is durability across a power cut: no file or directory is fsynced before those renames, so file data that hasn’t reached the disk may be lost behind a completed rename. (The staging sweep already runs on every advanced-mode start: PackagesActivity.onCreate calls cleanStaging() and cleanOrphans() (:59-60). The draft said otherwise; the pre-flight corrected it. That sweep deletes everything in .staging/, so as it stands it would also delete a resumable .part.)

  1. Every extracted file is fsynced (FileOutputStream.getFD().sync()) before the staging folder is renamed into place. The written installed.json/pending.json temp file is synced before its rename.
  2. The existing start-up sweep (PackagesActivity.onCreate → cleanStaging(), cleanOrphans()) still runs first on every advanced-mode start. It now deletes every .d extraction folder and temp file in .staging/ but keeps the .part downloads and sidecars that item 9 keeps. Each deletion is logged.
  3. A package is marked installed (installed.json) only after its folder is complete, synced and renamed. An interrupted extraction leaves the previous version recorded, playable and untouched, along with every save.
  4. After an interruption, installing the same package again starts cleanly: the download resumes or is reused if complete and verified, and the extract starts over.

Out of scope

Decisions for Jeff

All four were answered on 2026-11-28, when Jeff relayed a review that approved each recommendation and added safeguards to D3 and D4.

# Decision Recommendation Answer (2026-11-28)
D1 What happens when a package doesn’t fit. (a) Refuse, showing needed, free and shortfall; (b) also offer to remove other installed packages to make room (a) for v1. Choosing which game to delete is a product decision, and test builds don’t need it yet (a), “Approve”
D2 A large test package. (a) A synthetic ~420 MB zip of random data, on the public tv-test-packages release (no rights question, and it matches Showdown’s real size); (b) BASS only (69 MB, too small to stress space or resume); (c) a real Showdown package on a private host (a). (c) waits for the host-and-access WP (a), “Approve”
D3 Headroom added to the required space. (a) A fixed 64 MiB; (b) 5% of the installed size; (c) none (a). It covers filesystem overhead and the sidecars, and is easy to read in a refusal message (a) “for initial testing”. The 64 MiB must be checked against what the TCL actually does, not assumed to be enough everywhere (exit criterion 11)
D4 Testing a full disk on Jeff’s TCL. (a) Fill internal storage with a temporary filler file over adb until the package no longer fits, then delete it; (b) test only through a debug-build override of the free-space figure (a) for the real ENOSPC path, with (b) as well for the quick refusal checks. The filler is deleted in the same step, and the TV’s free space is recorded before and after (a) and (b), “Approve with safeguards”. The safeguards are in §Filler safeguards

Filler safeguards (D4)

  1. One test folder only. Filler files go in /sdcard/wp096-filler/. Nothing is written anywhere else, and the cleanup deletes only that folder.
  2. Never a full device. Each filler is sized to leave a stated floor free: the package’s shortfall target, and never less than 256 MiB of real free space, so the system and other apps keep running. The size is computed from a fresh df /data reading just before the filler is written.
  3. Automatic cleanup, failure included. Fillers are created and removed by one script, tools/Invoke-TvFiller.ps1 (PowerShell). Its try/finally deletes /sdcard/wp096-filler/ however the step ends: a pass, a failure, an adb error or Ctrl+C. Each filler step starts and ends with df /data, and the end reading must be within 1 MiB of the start.
  4. No orphans between sessions. EC-014’s pre-flight removes any /sdcard/wp096-filler/ left from a previous run before anything else.

Engineering calls (Claude’s, for pre-flight review)

  1. getAllocatableBytes over getUsableSpace on API 26+. It counts the cache Android can clear on demand. That matches what an install can really get on a TV whose free space is mostly cache. The TCL runs Android 14.
  2. CRC-32, not SHA-256, for Verify. The zip already carries a CRC-32 for every entry, so it costs no extra manifest data. The zip-level SHA-256 still guards the download itself.
  3. The resume validator comes from the server’s response, not the manifest. If-Range with the stored ETag or Last-Modified stops a changed object from being appended to an old partial file. The final SHA-256 check is the backstop either way.
  4. Hosts that ignore Range (they answer 200) just restart. The pre-flight found GitHub Releases honours it: a 302 to a signed release-assets.githubusercontent.com URL answers 206 with Content-Range and a stable ETag.
  5. Two code facts the pre-flight found (fork 6b5b02c53b):
    • open() refuses every status but 200 (PackageStore.java:155), so it must accept 206 for a range request.
    • The redirect target is signed and short-lived, so a resume always re-requests the manifest URL and follows the redirect afresh. It never stores the redirected URL. The JVM harness checks that HttpURLConnection keeps the Range header across the redirect.

Dependencies

Execution

  1. Pre-flight: pre-flight-WP-096-<date>.md, with D1–D4 answered and the GitHub Releases Range behaviour recorded.
  2. Implement in the order of the scope sections: 1 (preflight), 2 (resume), 3 (integrity), 5 (interrupted install), and 4 (the preservation checks, mostly tests). One commit per section on the fork branch.
  3. Exercise the pure-Java parts on a desktop JVM, as WP-085 did for zip-slip: the space arithmetic, the resume decision table, the .files.json comparison.
  4. Run EC-014 on the TCL, write §Result, and open the fork PR.

Exit criteria

  1. D1–D4 answered (2026-11-28); pre-flight READY (2026-11-28).
  2. With too little space (a filler file, per D4), installing the synthetic package is refused before any byte reaches .staging/. The refusal shows needed, free and shortfall, and the free-space figure before and after the attempt is unchanged (logged).
  3. With exactly enough room for the download but not the extract, and no installedSize in the manifest, the post-download check refuses before extracting and the staging files are gone (logged).
  4. A real ENOSPC mid-extract leaves an installed older version of the same id playable, and .staging/ empty (logged).
  5. A download killed at about 30% (am force-stop) and retried sends Range, gets 206, transfers only the remainder, and installs with a matching SHA-256. The log shows the resume offset and the bytes fetched (logged).
  6. A host or object that answers 200 to a Range request restarts from 0 and still installs. A partial download whose validator changed restarts from 0 too (logged; local test or JVM harness).
  7. Verify passes on a fresh install. After one byte of an installed file is changed through run-as, Verify names that file (logged).
  8. In each of criteria 2–7 and 12, existing saves and library entries are byte-identical before and after (run-as listings, as in WP-085 Milestone 4).
  9. The release APK still has no advanced-mode code (the WP-085 D4 apkanalyzer and dex string checks, returning 0).
  10. The manifest doc documents installedSize, the space rule, resume, Verify and the interrupted-install recovery. The fork PR is open with the section commits, and §Result is written.
  11. The headroom is measured, not assumed (D3). For BASS and the synthetic package, the real free-space drop on the TCL is recorded at three points: after the download, at the extract’s peak, and after install (df /data and getAllocatableBytes). §Result states each package’s overshoot over package size + installed size, and whether 64 MiB covered it. If it didn’t, the headroom is raised to the measured overshoot rounded up, and the change is noted.
  12. Interrupted installation recovery. The app is killed mid-extract (kill -9 of the app process) during an update of the synthetic package, and separately adb reboot is run mid-extract. In each case, after restart:
    1. the previous version is still installed, recorded in installed.json, launches and passes Verify;
    2. every save and library entry is byte-identical to snapshot S;
    3. the log shows the staging sweep removing the incomplete extraction;
    4. installed.json never names the interrupted version;
    5. retrying the update completes and passes Verify.

    One physical power cut at the wall mid-extract is run as well, with Jeff pulling the plug when the run sheet says to. Jeff chose it at pre-flight, 2026-11-28: it’s the only test of the fsync step, because kill -9 and adb reboot both leave the kernel to flush the page cache (logged).

Deliverables

Result

✅ Done, 2026-11-28. All 12 exit criteria hold on the TCL 65Q77K (Android 14). The captures are in EC-014.

What landed:

Evidence by criterion (store-log lines unless noted):

# Evidence
2 Filler leaving 600 MiB: REFUSED … needs 864.0 MB (905970878 bytes), 99.9 MB (104751104 bytes) free, short by 764.1 MB; .staging/ absent and df 614,296 KiB before and after. The override gave the same refusal at 500 MB
3 No installedSize, filler leaving 1,150 MiB: the download was verified, then REFUSED … 249.9 MB … free, short by 214.1 MB … (to extract 400.0 MB); .staging/ empty
4 Update 1.0 → 1.1 with a filler leaving 500 MiB: FAILED wp096-synth 1.1: out of space (ENOSPC) while extracting; deleting its staging files; .staging/ empty; 1.0 recorded and Verify PASS; BASS launched
5 Force-stopped at 31.3%; Range: bytes=131432229- → HTTP 206 … -> APPEND; fetched 287,999,168 B; SHA-256 matched; installed
6 On the TV: codeload.github.com answered 200 → RESTART_WITH_BODY, installed; an edited validator → RESTART_NEW_REQUEST, full 419,431,397 B fetched, installed. Also in the JVM harness (32 passed, 0 failed)
7 Verify … PASS, 6 of 6; after dd changed one byte: FAILED; changed wp096-synthetic/data3.bin (CRC-32 eb6fb321, expected 02d35efb)
8 Each step’s before and after snapshots match for saves, library, installed.json and package files (see the note below)
9 Release APK 17a9bec1…: 0 advanced classes, 0 TestFeatures, 0 PackagesActivity, 0 TVPKG_MANIFEST_URL, 0 debug-free-bytes
10 Manifest doc updated; fork PR #23 opened (merged 2026-11-28); this section
11 The headroom table below
12 kill -9, adb reboot and Jeff’s power cut, each mid-extract during an update: Staging sweep: deleting packages/.staging/wp096-synth-1.1.d (an incomplete extraction); installed.json named 1.0; Verify PASS; snapshots identical; BASS launched; each retry installed 1.1 and passed Verify

Measured headroom (criterion 11). These are drops in getAllocatableBytes from before the install. The once-a-second df /data poll agrees.

Package Zip + installed After download Extract’s end (peak) After install Overshoot 64 MiB enough
BASS 1.2 142,239,592 69,382,144 142,266,368 72,888,320 26,776 B yes
synthetic 1.0 838,862,014 419,483,648 838,889,472 419,454,976 27,458 B yes

The overshoot is ext4 block rounding and metadata, under 30 KB. 64 MiB stays (D3): it’s far more than the TCL needs.

Extract time with fsync. Extracting the 400 MB synthetic package with every file synced took 7.1 to 29.1 s across the run (7,146 to 29,072 ms). Most runs were about 8 s; the slow ones came while the TV was busy. A build without the syncs took 10.6 and 11.3 s, so syncing costs little or nothing here.

Findings:

Follow-ups (not done here):

  1. Sync the .part once its download completes. Done 2026-11-28 in fork PR barefootbetters/scummvm#25, merged 2026-11-28 (6e87dd1788). download() syncs the .part after its last byte, before the sidecar update and the SHA-256 check. On the TCL the sync took 390 ms for a fresh 400 MB download and 1,456 ms for a resumed one; both verified, installed and passed Verify. Power cut, 2026-11-28: Jeff pulled the plug 1–4 s after the download synced, during the extract. After boot the .part was the full 419,431,397 B (before the fix, the same cut left 377,638,912 B). The retry logged Reusing the complete download … not fetching it again, verified and installed. The installed files’ SHA-256s equal the zip’s, and saves and library were identical. That cut also showed store.log isn’t synced: it lost its last lines and kept a zero-filled tail. Fixed with follow-up 2: each log line is now synced, and the log view drops zero bytes left by an earlier cut.
  2. Delete a .part that’s never retried (for example, after a few days or when the manifest no longer lists that version). Done 2026-11-28 in fork PR barefootbetters/scummvm#28, merged 2026-11-28 (d5a7ade9b6), along with syncing store.log.
    • Start-up sweep: deletes a .part with no sidecar, a sidecar with no .part, and any .part unchanged for 7 days.
    • Manifest load: also deletes any .part the manifest doesn’t list, or whose entry changed so it can’t be resumed.
    • Each deletion takes its sidecar and is logged with the reason.
    • On the TCL: one planted case per rule was deleted by the expected sweep, with the expected log line, while a real 30% partial of the synthetic 1.1 survived both sweeps, resumed with 206, installed and passed Verify.
  3. Reinstall WP-085’s bass-cd so Verify can check it (it has no file list). Done 2026-11-28 on the TCL, through the app’s own Remove (keep saves) and install from packages-2026-11-26/manifest-update.json.
    • Before, Verify reported no file list. After, it reports Verify bass-cd 1.2.1: PASS, 5 of 5 files match.
    • The reinstalled files are byte-identical to the old ones (SHA-256), and the SKY-VM saves are unchanged.
    • Re-adding brings [sky] back without the three settings ScummVM writes on launch (FM_medium_quality, FM_high_quality, fullscreen). The first launch wrote them back, and the entry then matched the original exactly. No code change was needed.
  4. Make longer extract windows possible for a power-cut test (a test-only delay), if it’s run again. Done 2026-11-28 in fork PR barefootbetters/scummvm#33.
    • How: a number of milliseconds in files/packages/debug-extract-delay-ms (through run-as) makes the extract pause that long after each file is written and synced, up to 60 s per file. The store log, the “Extracting…” status and the diagnostics show it.
    • Example: 5000 gives the 6-file synthetic package about 30 s of extract instead of 8.
    • Tested: in the desktop JVM harness (33 passed: a 1,500 ms delay on three files took 4,502 ms, with the same files and CRC-32s). The release APK doesn’t contain it.
    • On the TCL, 2026-11-30, with 5000 ms: the diagnostics and the “Extracting…” status showed the delay. The six files appeared 5–8 s apart, and the log said Extracted 6 file(s) … in 38445 ms (each file synced; test delay 5000 ms after each). It verified 6 of 6, and deleting the file turned the delay off.
  5. Out of scope for this WP and still open: the production host and access scheme for licensed packages, a free-up-space UI (D1 b), and the package-building script.

Notes