# Keep On-Device LLMs Alive on Real Phones: Lesson 04. Survive downloads and process death

Lesson id: `on-device-llm-survival/04-downloads-and-process-death`
Human lesson: https://edgefde.dev/courses/on-device-llm-survival/04-downloads-and-process-death.html

## Goal

Download a large model in a way that resumes after failures and process death, check it, and restore the chat after the app is killed.

## Prerequisites

- A hosted model file and its SHA-256
- Lesson 02 model owner

## Inputs

- Model URL
- Expected SHA-256 from a manifest

## Outputs and artifacts

- `ModelDownloader` (Swift)
- `ModelDownloadWorker` (Kotlin)
- Saved chat records and an in-progress marker

## Steps

1. Create the checksum on the Mac with `shasum -a 256` and publish it next to the model URL.
2. iOS: create a background `URLSession`, save resume data from `NSURLSessionDownloadTaskResumeData` on failure, and resume with `downloadTask(withResumeData:)`.
3. iOS: in `didFinishDownloadingTo`, hash the file in 8 MB chunks and move it only if the hash matches.
4. Android: run a `CoroutineWorker` that writes to `model.bin.part`, sends `Range: bytes=N-`, appends on 206, and restarts on 200.
5. Android: hash the part file and rename it to `model.bin` only on a match.
6. Save each finished chat message to disk and keep an in-progress record during generation.
7. On launch, show stopped answers with Retry, and load the model lazily through the owner.

## Constraints

- Never load an unchecked file.
- Hash in chunks.
- Do not load the model at app launch.

## Acceptance checks

- Kill the app at 50% download, relaunch, and the download continues from about 50%.
- A file with one changed byte fails the check and is deleted.
- Kill the app during an answer, relaunch, and the chat shows the stopped answer with Retry.

## Key concepts

- Use a background `URLSession` on iOS and WorkManager on Android so downloads survive process death.
- Resume with resume data on iOS and an HTTP `Range` header on Android.
- Check a SHA-256 checksum in chunks before you move the file into place.
- After process death, restore saved messages and mark the cut answer as stopped.

## Takeaways

- Never hand a runtime a file you have not checked.
- Never hash a big model by reading it into memory at once.
- Save chat messages as they finish, and load the model lazily after launch.
