Triage Lab

33 real bugs in one Xcode project. Find each root cause with Xcode tools. Then check your answer.
TTell: who, how many, since when?
RReal? Is the number right?
IIsolate: which group, screen, switch?
AAct: stop the damage
GGuess, then reproduce
EEliminate: fix, test, prove, prevent

Set up in 3 minutes

  1. Unzip. Open TriageLab.xcodeproj in Xcode 16 or newer.
  2. Pick an iPhone Simulator. Press ⌘R. Tap a case.
  3. For the cases marked real phone (C02, C14, C31, C32, C30) use an iPhone. Set your Team in Signing.
  4. Do not read the Swift files first. Read the report, trigger the bug, then investigate. Hints are in the app and here.
  5. If a build error appears, open an issue with the error text. Parts of this project were written without running Xcode.

Where to click in Xcode (your tools map)

Run the appPress ⌘R. Pick an iPhone Simulator. For memory-left, MetricKit and background tasks use a real iPhone.
Debug bar (bottom of Xcode)Pause/Continue, Debug Memory Graph (three connected circles), View Hierarchy, Environment Overrides (text size, dark mode).
Gauges⌘7 opens the Debug Navigator. Click CPU, Memory, Disk, Network, Energy. Watch them while you trigger a case.
Pause and read the stackMenu Debug > Pause (⌃⌘Y). In the Debug Navigator click Thread 1 (main). Is it running code or waiting?
Breakpoints⌘8 Breakpoint Navigator. Click + at the bottom: Exception Breakpoint or Symbolic Breakpoint. Click a line number gutter for a normal one.
InstrumentsMenu Product > Profile (⌘I). Templates: Time Profiler, Allocations, Leaks, Animation Hitches, SwiftUI, Energy Log, File Activity, App Launch.
Scheme diagnosticsProduct > Scheme > Edit Scheme > Run > Diagnostics: Main Thread Checker, Thread Sanitizer, Address Sanitizer (not together with Thread Sanitizer), Zombie Objects, Malloc Stack Logging.
Launch arguments and languageEdit Scheme > Run > Arguments: add -resetLabConfig or -fixSlowLaunch. Options > App Language: Right to Left and Double-Length pseudolanguages.
Device logs and filesWindow > Devices and Simulators > select the device: Open Console, View Device Logs (crash logs), gear icon on the app > Download Container (see the files the app wrote).
Mac Console appPlug in the iPhone. Open Console. Select the device. Filter by TriageLab or a category like network.
Accessibility InspectorMenu Xcode > Open Developer Tool > Accessibility Inspector. Choose the Simulator. Press Audit.
MetricKitApp on a real device. Menu Debug > Simulate MetricKit Payloads. Then open the app's Black Box screen to see the files.
OrganizerWindow > Organizer: Crashes and Terminations for App Store and TestFlight builds.
Terminal toolsdwarfdump --uuid X.dSYM shows the UUID. atos turns an address into a function name.
In-app toolsTop-right Console: the black-box log, readable, with a filter box. Top-left Black Box: last-run report, live memory numbers, MetricKit files.

Tool did not work? Quick fixes

Memory Graph error: "failed to create a VMUTaskMemoryScanner ... libmalloc hasn't been initialized"
  1. Edit Scheme > Run > Diagnostics: turn OFF Thread Sanitizer, Address Sanitizer and Guard Malloc. Memory Graph does not work with them. Run again.
  2. Wait until the first screen shows. Do not capture at a launch breakpoint.
  3. Capture BEFORE you trigger a freeze (C12, C13).
  4. Stop, Clean Build Folder (⇧⌘K), quit the Simulator, run again.
  5. Still failing? Use Black Box > Live objects in the app (no Xcode tool needed), the in-app Console (count init and deinit lines), or Instruments Allocations.
Instruments Leaks: "Unable to instantiate loader for target"The heap tools cannot attach. Update Xcode so it matches your iOS version. Try another Simulator or re-download its runtime (Xcode > Settings > Components). On a phone, turn on Developer Mode and reconnect. Try Allocations instead of Leaks. Only C01, C02 and C03 need heap tools.
Thread Sanitizer shows nothingEdit Scheme > Run > Diagnostics > tick Thread Sanitizer. Do not tick Address Sanitizer at the same time. Run the case several times.
Pause shows no useful stackClick Thread 1 (main) in the Debug Navigator. Look for the first line with the app name.
Memory left shows n/aYou are on the Simulator. Use a real iPhone.
Console is emptyTap Refresh. Clear the filter box. Logs are written a moment after the event.
Instruments cannot attachProduct > Profile again. Pick a real device or the Simulator that is running the app. Stop the debug session first.

Three questions for EVERY case

  1. What do I see? (symptom, thread, CPU, memory, log lines)
  2. Which tool shows the cause? (stack, graph, profiler, sanitizer, log)
  3. How do I PROVE it? (a number or line that changes after the fix)
Solved: 0 / 33

All cases

Ward 1: Memory and silent kills 3 cases

C01

Memory climbs on the vitals screen

HIGH
Field report: Nurses say the app gets slower and warmer each time they check vitals. Memory keeps climbing.

1. Reproduce

  1. Open the Vitals monitor, go back. Repeat 5 times.
  2. Watch the memory number on the screen and in Xcode (Debug Navigator, Memory).
  3. No heap tool? Open Black Box > Live objects. Count VitalsMonitor.

2. Tools to try

Xcode Memory gaugeDebug Memory Graph buttonInstruments: Allocations or LeaksBlack Box > Live objects (works without any tool)Console log (init / deinit lines)

3. Files

Logic/L01_VitalsMonitor.swiftCaseViews/W1_Memory.swift

Stuck? Open one hint at a time

Hint 1

Use the Memory gauge, then press the Debug Memory Graph button (three connected circles) in the debug bar.

Hint 2

In the memory graph filter for VitalsMonitor. Count them. In the Console search the log for 'VitalsMonitor'.

Hint 3

Something keeps each monitor alive after you leave the screen. Look at the timer and what its closure captures.

Show the answer (try first!)
Root cause
  • A repeating Timer keeps its closure. The closure captures self strongly. The timer is never stopped.
  • The run loop holds the timer. The timer holds the closure. The closure holds the monitor. So the monitor never leaves memory.
How to PROVE it (what you should see)
  • Black Box > Live objects: VitalsMonitor: 5 alive after 5 visits. It should be 0 or 1.
  • Console: filter VitalsMonitor. You see 5 init lines and 0 deinit lines.
  • Debug Memory Graph: 5 VitalsMonitor objects. Click one. The arrows lead to a Timer and a closure.
  • Memory gauge grows about 400 KB per second for every leaked monitor.
Fix
timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { [weak self] _ in
    guard let self else { return }
    self.chartBuffers.append(Data(repeating: 1, count: 200_000))
    self.onTick?()
}

func stop() {
    timer?.invalidate()
    timer = nil
}
// call monitor.stop() from .onDisappear
Prevent it next time
  • Log deinit for long-lived objects.
  • Stop timers and tasks when the screen goes away.
  • Run the Leaks instrument before release.
One-line summary

I filtered the memory graph for the type, saw 5 leaked instances, and followed the arrows to a timer closure that captured self strongly.

C02

App closes on the photo gallery

CRITICAL
Field report: Nurses on older iPhones say the app closes by itself when they open the scan gallery. Our crash tool shows nothing.

1. Reproduce

  1. Set Photos to 8, tap Load photos. Watch memory.
  2. Raise to 24 and load again. On a real iPhone iOS will close the app. Reopen it and open the Black Box screen.

2. Tools to try

Xcode Memory gaugeInstruments: Allocations + VM TrackerBlack Box: last-run reportXcode Organizer > Terminations (real apps)

3. Files

Logic/L02_PhotoLoader.swiftCaseViews/W1_Memory.swift

Stuck? Open one hint at a time

Hint 1

There is no crash report. Think: who else can close an app? Check the Black Box screen after the app closes.

Hint 2

Look at how many photos are held in memory at once and how big each one is (4032 x 3024 pixels, 4 bytes per pixel).

Hint 3

Every photo is decoded at full size and all are kept in an array. 24 photos is more than 1 GB.

Show the answer (try first!)
Root cause
  • Each photo is decoded at full size: 4032 x 3024 x 4 bytes is about 48.8 MB.
  • All photos are kept at once. 24 photos is about 1.1 GB. iOS closes the app when it passes its memory limit. No crash report is made.
How to PROVE it (what you should see)
  • Memory gauge jumps by about 49 MB per photo.
  • Instruments > Allocations: big [UInt8] buffers. VM Tracker shows dirty memory growing.
  • Real phone: after the kill, Black Box says unknown_in_foreground with the last memory numbers. The log has silent_end_suspected.
Fix
// Do not decode full size. Make a small thumbnail with ImageIO.
let options: [CFString: Any] = [
    kCGImageSourceCreateThumbnailFromImageAlways: true,
    kCGImageSourceThumbnailMaxPixelSize: 600,
    kCGImageSourceCreateThumbnailWithTransform: true
]
let thumbnail = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary)
// Keep only the visible photos. Load 2 or 3 at a time.
Prevent it next time
  • Check memory left before heavy work.
  • Test with 50 photos on the oldest phone.
  • Alert on unknown_in_foreground per app version.
One-line summary

No crash report means iOS closed it. I read the last-run log, did the memory math (48 MB per decoded photo), and fixed it by downsampling.

C03

Memory grows all day on the live feed

HIGH
Field report: Charge nurses keep the live feed open all shift. After a few hours the app closes.

1. Reproduce

  1. Tap Refresh live feed 20 times. Watch the memory numbers go up in steps.

2. Tools to try

Xcode Memory gaugeInstruments: Allocations (Mark Generation)VM Tracker

3. Files

Logic/L03_FeedCache.swift

Stuck? Open one hint at a time

Hint 1

The curve looks like a staircase. Something grows with every refresh and never shrinks.

Hint 2

In Allocations press Mark Generation, tap Refresh 5 times, press it again. See what survived.

Hint 3

Look at how FeedCache stores items and what key it uses.

Show the answer (try first!)
Root cause
  • Each refresh saves 3 MB under a new key (the key has the time in it). Nothing is ever removed.
How to PROVE it (what you should see)
  • Allocations > Generations: each refresh adds about 3 MB that stays alive.
  • Memory gauge is a staircase.
Fix
private let cache = NSCache<NSString, NSData>()

init() {
    cache.countLimit = 20
    cache.totalCostLimit = 30_000_000
}

func save(_ data: Data, for key: String) {
    cache.setObject(data as NSData, forKey: key as NSString, cost: data.count)
}
Prevent it next time
  • Every cache needs a size limit.
  • Clear caches on memory warning and when the app goes to background.
One-line summary

A staircase memory curve points to an unbounded cache. I used Mark Generation to see what survives each refresh.

Ward 2: Crashes 8 cases

C04

Crash opening one patient

HIGH
Field report: Crash when a nurse opens patient C. Das. Other patients are fine.

1. Reproduce

  1. Tap patients A. Rao and B. Singh. Then tap C. Das.

2. Tools to try

Xcode debugger stop + Debug Navigator stackException breakpointConsole

3. Files

Logic/L04_Patients.swift

Stuck? Open one hint at a time

Hint 1

Run from Xcode. It stops on a line. Read the stack in the Debug Navigator.

Hint 2

Compare the data of patient 3 with patients 1 and 2 (PatientService has the JSON).

Hint 3

A field is missing for one patient and the code uses !.

Show the answer (try first!)
Root cause
  • Patient 3 has no doctor. The model says doctor is optional, which is correct.
  • The code does record.doctor!.name. A force unwrap of nil traps.
How to PROVE it (what you should see)
  • Xcode stops on record.doctor!.name. Console says: Unexpectedly found nil while unwrapping an Optional value.
  • Print the record: doctor is nil.
Fix
func doctorName(forPatient id: Int) -> String {
    guard let record = records.first(where: { $0.id == id }) else {
        return "Unknown patient"
    }
    guard let doctor = record.doctor else {
        Log.error(.data, "doctor_missing", ["patient": String(id)])
        return "Not assigned"
    }
    return doctor.name
}
Prevent it next time
  • No ! on data that comes from outside the app.
  • Test with missing, null and extra fields.
One-line summary

Nil force unwrap. The server left a field out. I used guard-let, logged it, and showed a clear fallback.

C05

Crash on the third page

MEDIUM
Field report: Crash when a nurse taps Next page for the third time.

1. Reproduce

  1. Tap Next page twice.

2. Tools to try

Xcode stack traceBreakpoint on page(_:)Console

3. Files

Logic/L05_Pager.swift

Stuck? Open one hint at a time

Hint 1

Read the crashed line and the error message.

Hint 2

Print start and end for each page. There are 25 readings.

Hint 3

Page 3 asks for items 20 to 29. The list stops at 24.

Show the answer (try first!)
Root cause
  • start..<end goes past the end of the array on the last page (20..<30 with 25 items).
How to PROVE it (what you should see)
  • Xcode stops at Array(readings[start..<end]). Error: Index out of range.
Fix
func page(_ number: Int) -> [String] {
    let start = number * pageSize
    guard start < readings.count else { return [] }
    let end = min(start + pageSize, readings.count)
    return Array(readings[start..<end])
}
Prevent it next time
  • Unit test the last page and an empty page.
  • Never trust a computed index.
One-line summary

Off-by-one at the last page. I clamped the end index and added a unit test for the edge.

C06

Crash after going back quickly

HIGH
Field report: Crash a few seconds after a nurse opens the lab result and goes back.

1. Reproduce

  1. Open lab result. Tap Load. Go back within 3 seconds. Wait.

2. Tools to try

Xcode stack traceConsole messageLog (slow_load_start / slow_load_done)

3. Files

Logic/L06_SlowLoader.swiftCaseViews/W2_Crashes.swift

Stuck? Open one hint at a time

Hint 1

Read the error message in the console. It names the problem.

Hint 2

Which object is gone when the closure runs? Look at the capture list.

Hint 3

[unowned self] plus a delayed closure plus a screen that closed.

Show the answer (try first!)
Root cause
  • The closure waits 3 seconds. It captures self as unowned.
  • The screen closed, so the loader was freed. When the closure runs, self is gone and the app traps.
How to PROVE it (what you should see)
  • Console: Attempted to read an unowned reference but object was already deallocated.
  • Log has slow_load_start but no slow_load_done.
Fix
DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [weak self] in
    guard let self else { return }
    self.result = "loaded"
    self.onDone?()
}
// or cancel the work in deinit
Prevent it next time
  • Use weak for work that can outlive the screen.
  • Cancel pending work when the screen goes away.
One-line summary

A delayed closure used unowned self and the screen was gone. Fix: weak self with a guard, and cancel the work.

C07

Crash when syncing in a lift

HIGH
Field report: Nurses report a crash when syncing favorites in lifts and tunnels.

1. Reproduce

  1. Turn on Poor network. Tap Sync favorites. Wait 3 seconds.

2. Tools to try

Xcode stack trace (which thread?)Console logNetwork Link Conditioner (idea)

3. Files

Logic/L07_SyncService.swift

Stuck? Open one hint at a time

Hint 1

Check which thread crashed. Read the message.

Hint 2

How long does the code wait? How long can a poor network take?

Hint 3

The code treats a slow network as a bug.

Show the answer (try first!)
Root cause
  • The code waits at most 3 seconds, then calls fatalError.
  • A slow network is normal. The timeout is not a bug.
How to PROVE it (what you should see)
  • Crash is on a background thread. Message: Sync took too long.
  • Log shows sync_start with network_delay_s=5 and no sync_ok.
Fix
func syncFavorites(simulatedNetworkDelay: Double, completion: @escaping (Bool) -> Void) {
    // Never wait on a thread. Use a completion and a longer timeout.
    DispatchQueue.global().asyncAfter(deadline: .now() + simulatedNetworkDelay) {
        completion(true)
    }
}
// On timeout: call completion(false) and show 'Will retry later'.
Prevent it next time
  • fatalError is for bugs, not for slow networks.
  • Test with Network Link Conditioner.
One-line summary

A timeout turned into fatalError. I handled the timeout, gave slow networks more time, and showed a retry message.

C08

Purple warning: publishing from background

LOW
Field report: Developers see a purple warning in Xcode. Sometimes the screen does not update.

1. Reproduce

  1. Tap Scan. Open the Issue Navigator (triangle icon) and the console.

2. Tools to try

Xcode Issue Navigator (Runtime Issues)Main Thread Checker (Edit Scheme > Run > Diagnostics)Console

3. Files

CaseViews/W2_Crashes.swift

Stuck? Open one hint at a time

Hint 1

Open the Issue Navigator. Look for a purple item.

Hint 2

Which thread changes status?

Hint 3

@Published must change on the main thread.

Show the answer (try first!)
Root cause
  • status is changed inside DispatchQueue.global().async. UI state must change on the main thread.
How to PROVE it (what you should see)
  • Issue Navigator: Publishing changes from background threads is not allowed.
  • Turn on Main Thread Checker for stricter reports.
Fix
@MainActor
final class ScanViewModel: ObservableObject {
    @Published var status = "idle"

    func scan() {
        status = "scanning"
        Task {
            try? await Task.sleep(nanoseconds: 1_000_000_000)
            status = "done"
        }
    }
}
Prevent it next time
  • Mark view models @MainActor.
  • Keep Main Thread Checker on in debug.
One-line summary

UI state changed off the main thread. I made the view model @MainActor and used async work.

C09

Wrong count, sometimes a crash

HIGH
Field report: The reading count is sometimes lower than expected. Rarely the app crashes with a malloc error.

1. Reproduce

  1. Tap Collect readings several times. Compare Expected and Got.
  2. Then turn on Thread Sanitizer and run again.

2. Tools to try

Thread Sanitizer (Edit Scheme > Run > Diagnostics)Console

3. Files

Logic/L09_ReadingBuffer.swift

Stuck? Open one hint at a time

Hint 1

Turn on Thread Sanitizer and run again.

Hint 2

How many threads add to the same array?

Hint 3

An array is not safe for many writers.

Show the answer (try first!)
Root cause
  • concurrentPerform runs many threads. They all call values.append on one array without a lock. This is a data race.
How to PROVE it (what you should see)
  • Thread Sanitizer: Data race detected (Issue Navigator). Two threads write the same address. It reports this on every run.
  • Without the Sanitizer the count may look right on some runs. On a Mac with many cores it is often lower, and sometimes the app crashes. A race does not fail every time. That is why it is dangerous.
Fix
final class ReadingBuffer {
    private let queue = DispatchQueue(label: "readings")
    private var values: [Int] = []

    func add(_ value: Int) {
        queue.sync {
            values.append(value)
        }
    }

    var count: Int {
        queue.sync {
            values.count
        }
    }
}
Prevent it next time
  • One owner for shared data: a lock, a serial queue, or an actor.
  • Run Thread Sanitizer in CI.
One-line summary

Random wrong counts and malloc crashes mean a data race. Thread Sanitizer pointed at the array. I gave the data one owner.

C10

Crash: incorrect actor executor

HIGH
Field report: Crash after refreshing from the bedside device. Message mentions an actor executor.

1. Reproduce

  1. Tap Refresh from device.

2. Tools to try

Xcode stack traceConsole message

3. Files

Logic/L10_Bedside.swift

Stuck? Open one hint at a time

Hint 1

Read the message. It says which executor was expected.

Hint 2

Which thread runs the callback of the old device API?

Hint 3

MainActor.assumeIsolated does not move you to the main thread. It only checks.

Show the answer (try first!)
Root cause
  • The old API calls back on a background queue.
  • The code uses MainActor.assumeIsolated. It promises 'I am on main'. The promise is false, so the app traps.
How to PROVE it (what you should see)
  • Console: Incorrect actor executor assumption. The stack shows the background queue.
Fix
LegacyDeviceApi.fetch {
    Task { @MainActor in
        model.markUpdated()
        onDone()
    }
}
Prevent it next time
  • Do not use assumeIsolated as a shortcut.
  • Fix the caller. Hop to the main actor properly.
One-line summary

assumeIsolated is a check, not a hop. The callback was on a background queue. I used a MainActor task.

C11

Crash at every launch after a download

CRITICAL
Field report: After tapping 'Download new config', the app crashes at every launch. Reinstall fixes it.

1. Reproduce

  1. Tap Download new config. Stop the app in Xcode. Run again.
  2. To recover: Edit Scheme > Run > Arguments > add -resetLabConfig.

2. Tools to try

Xcode stack trace at launchConsoleWindow > Devices and Simulators > Download Container

3. Files

Logic/L11_ConfigStore.swiftApp/AppBootstrap.swift

Stuck? Open one hint at a time

Hint 1

The crash is before any screen. Read the stack and the message.

Hint 2

What does the app read at launch? Find the file. Download the container and open it.

Hint 3

The settings file has a wrong value type and the code uses try!.

Show the answer (try first!)
Root cause
  • The server wrote "refreshSeconds": "fast" (text, not a number).
  • ConfigStore.load() uses try!. It crashes on every launch, so the app cannot start. This is a crash loop.
How to PROVE it (what you should see)
  • Xcode: Fatal error: 'try!' expression unexpectedly raised an error: typeMismatch(Int...).
  • Device container > Library/Caches/lab-config.json shows the bad value.
  • Black Box (after recovery): last run is unknown_in_foreground several times in a row.
Fix
static func load() -> LabConfig {
    guard let data = try? Data(contentsOf: url) else { return .defaults }
    do {
        return try JSONDecoder().decode(LabConfig.self, from: data)
    } catch {
        Log.error(.lifecycle, "config_bad_deleted")
        try? FileManager.default.removeItem(at: url)   // delete the bad file
        return .defaults
    }
}
// Also: crash loop breaker. After 3 bad launches in a row start in safe mode.
Prevent it next time
  • Never try! on data from disk or network.
  • Safe defaults. Crash loop breaker.
  • Validate config before saving it.
One-line summary

A crash at launch every time: bad config on disk plus try!. I read the file from the device container, fixed the decode with safe defaults, and added a crash loop breaker.

Ward 3: Hangs, launch, speed 5 cases

C12

App freezes forever

CRITICAL
Field report: The app freezes completely when building the daily report. No crash.

1. Reproduce

  1. Tap Build report. The app freezes. In Xcode use Debug > Pause (or the pause button).

2. Tools to try

Xcode Pause + Debug Navigator main thread stackConsole (main_thread_hang)Instruments: Hangs

3. Files

Logic/L12_ReportBuilder.swift

Stuck? Open one hint at a time

Hint 1

Pause the app and read what the main thread is doing.

Hint 2

Is the CPU high or low? A frozen app with low CPU is waiting.

Hint 3

The main thread waits for a result. The worker needs the main thread to deliver it.

Show the answer (try first!)
Root cause
  • buildReport() runs on the main thread and calls semaphore.wait().
  • The worker thread sends the result with DispatchQueue.main.async. The main thread is blocked, so that block never runs. Deadlock.
How to PROVE it (what you should see)
  • Pause: main thread is in semaphore_wait_trap. CPU is near 0%.
  • Console: main_thread_hang from the live hang detector.
Fix
func buildReport(completion: @escaping (String) -> Void) {
    DispatchQueue.global().async {
        let text = self.collectNumbers()
        DispatchQueue.main.async {
            completion(text)
        }
    }
}
// The caller shows a spinner and updates when the completion runs.
Prevent it next time
  • Never wait for another thread on the main thread.
  • Main Thread Checker and a hang detector in debug.
One-line summary

Low CPU freeze means waiting, not working. I paused the app and saw the main thread blocked on a semaphore while the worker needed main.

C13

Freeze for a few seconds, CPU high

MEDIUM
Field report: The app freezes for several seconds when building the summary. The phone gets warm.

1. Reproduce

  1. Tap Build daily summary. Try to scroll or tap during the freeze.

2. Tools to try

Xcode CPU gaugeInstruments: Time ProfilerConsole (main_thread_hang)

3. Files

Logic/L13_Sorter.swift

Stuck? Open one hint at a time

Hint 1

Is the CPU high or low? Compare with the previous case.

Hint 2

Profile with Time Profiler (Product > Profile). Look at the heaviest function.

Hint 3

A lot of sorting runs on the main thread.

Show the answer (try first!)
Root cause
  • Eight sorts of 1,000,000 numbers run on the main thread. The main thread is busy, not waiting.
How to PROVE it (what you should see)
  • Time Profiler: ReadingSorter.buildSummary and sort at the top. Main thread 100% busy.
  • Hang detector logs main_thread_hang.
Fix
Button("Build daily summary") {
    isWorking = true
    Task.detached {
        let total = ReadingSorter.buildSummary()
        await MainActor.run {
            message = "Summary ready: \(total)"
            isWorking = false
        }
    }
}
Prevent it next time
  • Heavy work goes off the main thread, with a spinner.
  • Profile with Time Profiler before release.
One-line summary

High CPU: the main thread was busy. Time Profiler showed the sort at the top. I moved it off main.

C14

First screen takes 10 seconds

CRITICAL
Field report: After enabling Slow start-up, the first screen takes more than 10 seconds. On real phones iOS closes the app at launch.

1. Reproduce

  1. Turn on Slow start-up. Stop. Run again and time the first screen.
  2. To recover: Edit Scheme > Run > Arguments > add -fixSlowLaunch.

2. Tools to try

Console (startup_config_fetch_begin / end, time_to_first_screen)Xcode Pause during launchInstruments: App Launch

3. Files

Logic/L14_LaunchWork.swiftApp/AppBootstrap.swift

Stuck? Open one hint at a time

Hint 1

Read the launch lines in the Console. Where is the time lost?

Hint 2

Pause during the freeze. What is the main thread doing?

Hint 3

Something waits for a 'server' before the first screen.

Show the answer (try first!)
Root cause
  • Start-up code waits on a semaphore for a fake server reply, on the main thread, before the first screen.
  • On a real phone the watchdog kills the app (about 20 seconds). It is not enforced in the Simulator or with the debugger.
How to PROVE it (what you should see)
  • Console: time_to_first_screen is more than 10000 ms.
  • Pause: main thread in semaphore_wait, called from AppBootstrap.start.
Fix
// 1. Show the first screen first.
// 2. Load config later, with a short timeout and a cached default.
Task {
    let config = await ConfigLoader.loadWithTimeout(seconds: 3)
    apply(config)
}
Prevent it next time
  • Launch never waits for the network.
  • Budget for time to first screen in CI.
One-line summary

Launch waited on the network. I showed the first screen first, loaded config later with a timeout, and used cached defaults.

C15

List stutters while scrolling

MEDIUM
Field report: The vitals list stutters when scrolling fast.

1. Reproduce

  1. Scroll the list quickly up and down.

2. Tools to try

Xcode CPU gaugeInstruments: Time Profiler / Animation Hitches

3. Files

Logic/L15_RowCost.swiftCaseViews/W3_Hangs.swift

Stuck? Open one hint at a time

Hint 1

Check the CPU gauge while scrolling.

Hint 2

Profile it. What function is called for every row?

Hint 3

Each row does a lot of work while the view is drawn.

Show the answer (try first!)
Root cause
  • RowCost.label runs a 200,000-step loop for every row, on the main thread, inside body.
How to PROVE it (what you should see)
  • Time Profiler: RowCost.label dominates the main thread while scrolling.
Fix
// Compute once, off the main thread, and keep body cheap.
@State private var labels: [Int: String] = [:]

.task {
    labels = await Task.detached {
        Dictionary(uniqueKeysWithValues: (0..<300).map { ($0, RowCost.label($0)) })
    }.value
}
Prevent it next time
  • body must be cheap.
  • Profile scrolling on the oldest phone.
One-line summary

Hitches came from heavy work inside body for each row. Time Profiler showed it. I precomputed off main.

C16

Expanded rows close by themselves

MEDIUM
Field report: Rows that a nurse expands close again after one second.

1. Reproduce

  1. Tap Patient 2 to expand. Watch for a second.

2. Tools to try

let _ = Self._printChanges() in bodyInstruments: SwiftUIBreakpoint in the rows property

3. Files

CaseViews/W3_Hangs.swift

Stuck? Open one hint at a time

Hint 1

The clock tick changes every second. What does that re-run?

Hint 2

Print the ids of the rows on each tick.

Hint 3

The row ids are random on every render.

Show the answer (try first!)
Root cause
  • rows creates new rows with UUID() as the id every time body runs. SwiftUI sees brand-new rows, so the @State isOpen resets.
How to PROVE it (what you should see)
  • Add let _ = Self._printChanges() to body: it re-runs every second.
  • Print rows.map(\.id): different on every tick.
Fix
private let rows: [RowItem] = (1...5).map { number in
    RowItem(id: number, title: "Patient \(number)")   // stable id
}
// RowItem.id is now an Int.
Prevent it next time
  • Use stable ids.
  • Keep model data in state, not rebuilt in body.
One-line summary

Unstable identity. New UUIDs each render made SwiftUI rebuild rows and reset state. Stable ids fixed it.

Ward 4: Network 4 cases

C17

Outage: server flooded by retries

CRITICAL
Field report: During a server outage, the backend received 10 times more requests than normal.

1. Reproduce

  1. Set 100 phones. Tap Simulate outage. Read the result.

2. Tools to try

Console (retry_lab)Code reading: PhoneClientNetwork instrument (idea)

3. Files

Logic/L17_RetryLab.swift

Stuck? Open one hint at a time

Hint 1

Compare phones to requests. What is the ratio?

Hint 2

Read what a phone does after an error.

Hint 3

Retries are instant, unlimited by wait time, and cover every error.

Show the answer (try first!)
Root cause
  • Each phone retries 10 times immediately for any failure. No wait, no randomness, no stop for hopeless errors.
How to PROVE it (what you should see)
  • Result: 100 phones send 1000 requests. Log line retry_lab shows the same.
Fix
static func fetchWithRetry(server: OutageServer) async {
    for attempt in 1...3 {                                  // small cap
        if server.call() == 200 { return }
        let ceiling = min(4.0, 0.5 * pow(2.0, Double(attempt - 1)))
        let wait = Double.random(in: 0...ceiling)           // backoff + jitter
        try? await Task.sleep(nanoseconds: UInt64(wait * 1_000_000_000))
    }
}
// Retry only timeouts and 5xx. Never retry 4xx. Keep a remote kill switch.
Prevent it next time
  • Backoff with jitter. Max attempts.
  • A flag to turn retries off.
One-line summary

A retry storm. I capped attempts, added exponential backoff with jitter, retried only transient errors, and kept a kill switch.

C18

Patient got two refill orders

CRITICAL
Field report: A patient received two refills after one nervous double tap.

1. Reproduce

  1. Tap Order refill twice quickly. Read the message.

2. Tools to try

Console (order_submit, order_created)Breakpoint in submit

3. Files

Logic/L18_Orders.swiftCaseViews/W4_Network.swift

Stuck? Open one hint at a time

Hint 1

Count order_submit and order_created lines.

Hint 2

Is anything stopping the second tap?

Hint 3

The server cannot tell a retry from a new order.

Show the answer (try first!)
Root cause
  • The button is never disabled. There is no idempotency key. The server creates one order for every request.
How to PROVE it (what you should see)
  • Log: two order_submit, then order_created order=1 and order=2.
Fix
// App: disable the button while sending, and send ONE key per order.
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue(orderID.uuidString, forHTTPHeaderField: "Idempotency-Key")

// Server: if the key was seen, return the first result.
Prevent it next time
  • Idempotency key on every request that creates something.
  • Disable buttons while a request runs.
One-line summary

Duplicate orders: no idempotency key. Same key on every retry, server dedupes, button disabled while sending.

C19

Users logged out at random

HIGH
Field report: Users are logged out randomly after the app wakes up.

1. Reproduce

  1. Tap Fire 5 API calls at once. Read the result and the Console.

2. Tools to try

Console (got_401, refresh_ok, refresh_failed_logged_out)Timeline reading

3. Files

Logic/L19_Auth.swift

Stuck? Open one hint at a time

Hint 1

Filter the Console for refresh. Count the lines.

Hint 2

How many refresh calls happen for 5 failed requests?

Hint 3

The server rotates the refresh token on every use.

Show the answer (try first!)
Root cause
  • Five calls get 401 at the same time. Each one refreshes the token on its own.
  • The refresh token works once. The first refresh wins. The other four fail and the client logs the user out.
How to PROVE it (what you should see)
  • Log: five got_401, one refresh_ok, four refresh_failed_logged_out.
Fix
actor TokenRefresher {
    private var inFlight: Task<Tokens, Error>?

    func refresh() async throws -> Tokens {
        if let running = inFlight {
            return try await running.value        // join the running refresh
        }
        let task = Task { try await callRefreshEndpoint() }
        inFlight = task
        defer { inFlight = nil }
        return try await task.value
    }
}
Prevent it next time
  • Single-flight refresh.
  • Log request IDs and timing.
One-line summary

Many 401s caused many refreshes with a rotating token. I made refresh single-flight with an actor so all callers share one refresh.

C20

Dashboard shows heart rate 0 after update

HIGH
Field report: After the app update some users see heart rate 0 on the dashboard.

1. Reproduce

  1. Tap Install cache from old app version. Tap Open dashboard.

2. Tools to try

Breakpoint in loadHeartRatepo / print of the decode errorSearch code for try?

3. Files

Logic/L20_VitalsCache.swift

Stuck? Open one hint at a time

Hint 1

No crash and no log. Where can an error disappear?

Hint 2

Step through loadHeartRate with a breakpoint.

Hint 3

The old file uses another field name and errors are swallowed.

Show the answer (try first!)
Root cause
  • The old file has bpm. The new code expects heartRate.
  • try? hides the decode error. The code returns 0 silently. The cache has no schema version.
How to PROVE it (what you should see)
  • Breakpoint: vitals is nil. Replace try? with try and print the error: keyNotFound(heartRate).
  • The file content is {"bpm":72}.
Fix
static func loadHeartRate() -> Int {
    guard let data = try? Data(contentsOf: url) else { return 0 }
    do {
        return try JSONDecoder().decode(VitalsV2.self, from: data).heartRate
    } catch {
        Log.error(.data, "vitals_cache_decode_failed", ["error": "\(error)"])
        try? FileManager.default.removeItem(at: url)   // drop the old-format file
        return 0
    }
}
// Better: store a schemaVersion in the file name or content.
Prevent it next time
  • Never swallow errors with try? without a log.
  • Version your cache.
One-line summary

Silent wrong data: try? hid a decode error from an old cache file. I logged the error, dropped old files, and versioned the cache.

Ward 5: Data, time, location 3 cases

C21

Nurse note vanishes after app ends

HIGH
Field report: A nurse's note disappeared after the app ended during a save.

1. Reproduce

  1. Type a note. Tap Save note, mid-write end. Run again. Tap Load note.

2. Tools to try

Console (note_save_start without note_save_end)Devices and Simulators > Download ContainerBreakpoint in load()

3. Files

Logic/L21_NotesStore.swift

Stuck? Open one hint at a time

Hint 1

Compare note_save_start and note_save_end in the log.

Hint 2

Download the container and open Documents/note.json.

Hint 3

The file was written in two parts, not in one safe step.

Show the answer (try first!)
Root cause
  • The file is written in a way that is not atomic. The app ended after half the data was on disk.
  • Half a JSON file cannot be decoded. load() returns nil, so the note looks lost.
How to PROVE it (what you should see)
  • Log: note_save_start with no note_save_end.
  • note.json in the container is cut in the middle.
Fix
let data = try JSONEncoder().encode(note)
try data.write(to: url, options: [.atomic])     // all or nothing
// Keep the last good file as a backup and log decode errors on load.
Prevent it next time
  • Write atomically.
  • Log load failures.
  • Test by ending the app during save.
One-line summary

Half-written file after the app ended. Atomic writes make it all or nothing. I also keep a backup and log load errors.

C22

Negative minutes around the clock change

MEDIUM
Field report: A New York hospital sees '-30 min' between readings on 1 November.

1. Reproduce

  1. Tap Show time between readings.

2. Tools to try

Print the parsed datesReasoning about time zonesPlayground / breakpoint

3. Files

Logic/L22_DstTimeline.swift

Stuck? Open one hint at a time

Hint 1

Print the real dates (with time zone) for each text.

Hint 2

On 1 November 2026 the clocks in New York go back one hour at 2:00.

Hint 3

Local time text without an offset is ambiguous.

Show the answer (try first!)
Root cause
  • Readings are saved as local time text. The hour from 1:00 to 2:00 happens twice that night.
  • '01:20' can mean two different moments. The app picks one and the order breaks.
How to PROVE it (what you should see)
  • Report shows 01:50 -> 01:20 as -30 min. The real gap is +30 min.
Fix
// Store UTC (ISO 8601 with offset). Show local time only on screen.
let formatter = ISO8601DateFormatter()
let saved = formatter.string(from: Date())          // 2026-11-01T05:20:00Z
let date = formatter.date(from: saved)

// Use a monotonic clock for durations on the device.
Prevent it next time
  • Never store local time text.
  • Test around DST changes.
One-line summary

Local time strings are ambiguous during the DST fall-back hour. Store UTC with offset, display local.

C23

Walk distance shows thousands of km

MEDIUM
Field report: A nurse walked about 100 metres. The app says thousands of kilometres.

1. Reproduce

  1. Tap Calculate distance walked.

2. Tools to try

Print each GPS fixBreakpoint in totalKmReasoning: Fresh, Accurate, Frugal

3. Files

Logic/L23_GpsTrack.swift

Stuck? Open one hint at a time

Hint 1

Print each fix: accuracy and age.

Hint 2

Which point is far away from the others?

Hint 3

Old, weak and invalid points are used.

Show the answer (try first!)
Root cause
  • First point is an old saved fix (age 3600 s) from New York. One point has accuracy 800 m. One has accuracy -1 (invalid).
  • All are used in the sum.
How to PROVE it (what you should see)
  • Print fixes: the first jump is about 13,000 km.
Fix
func isUsable(_ fix: GpsFix) -> Bool {
    return fix.accuracy >= 0              // negative means invalid
        && fix.accuracy < 100             // not too weak
        && fix.ageSeconds < 10            // not an old saved fix
}

let good = fixes.filter(isUsable)
Prevent it next time
  • Filter by accuracy and age.
  • Reject impossible speeds.
  • Test on a real phone outdoors.
One-line summary

Fresh, Accurate, Frugal. I filtered stale, weak and invalid fixes before adding distances.

Ward 6: Threads and queues 2 cases

C24

Balance went negative

HIGH
Field report: After two quick purchases the balance is negative.

1. Reproduce

  1. Tap Buy two tests at once.

2. Tools to try

Breakpoint inside buy()Console (wallet_lab)Reading: where is the await?

3. Files

Logic/L24_Wallet.swift

Stuck? Open one hint at a time

Hint 1

Both purchases returned true. Why?

Hint 2

Look for an await between the check and the change.

Hint 3

Actors are reentrant at every await.

Show the answer (try first!)
Root cause
  • The balance is checked, then the code awaits, then it subtracts.
  • While the first call waits, the second one enters the actor and passes the same check.
How to PROVE it (what you should see)
  • Result: [true, true], balance -60.
Fix
func buy(price: Int) async -> Bool {
    guard balance >= price else { return false }
    balance -= price                                 // reserve FIRST
    let ok = await charge(price)                     // the await is a door
    if !ok {
        balance += price                             // undo
    }
    return ok
}
Prevent it next time
  • After every await, check state again.
  • Change state before awaiting.
One-line summary

Actor reentrancy: state changed across an await. I reserved the money first and undid it on failure.

C25

Uploads stop at scan 3

HIGH
Field report: Uploads stop at scan 3. Scans 4 and 5 never upload.

1. Reproduce

  1. Tap Upload 5 scans. Wait 10 seconds.

2. Tools to try

Xcode Pause + Debug NavigatorConsole (upload_failed, upload_ok)Breakpoint in UploadOperation.main

3. Files

Logic/L25_Uploads.swift

Stuck? Open one hint at a time

Hint 1

Read the order of lines in the console.

Hint 2

The queue runs one operation at a time. What makes an operation 'done'?

Hint 3

The failure path returns without finishing.

Show the answer (try first!)
Root cause
  • The queue runs one operation at a time. An async operation must call finish() on every path.
  • Scan 3 fails and returns without finish(). The queue waits forever.
How to PROVE it (what you should see)
  • Log: upload_ok 1, upload_ok 2, upload_failed 3, then nothing.
  • Debugger: operation 3 isFinished is false.
Fix
DispatchQueue.global().asyncAfter(deadline: .now() + 0.4) {
    defer {
        self.finish()                 // runs on EVERY path
    }
    if self.index == 3 {
        self.onResult(self.index, false)
        return
    }
    self.onResult(self.index, true)
}
Prevent it next time
  • LOCF: Limit, Order, Cancel, Finish.
  • Use defer { finish() }.
One-line summary

A serial queue stalls if one async operation never finishes. I used defer so finish runs on every path.

Ward 7: Bluetooth (fake band) 2 cases

C26

Band found but never connects

HIGH
Field report: The heart band is found but never connects. No error is shown.

1. Reproduce

  1. Tap Connect to heart band. Wait 10 seconds.

2. Tools to try

Console filter: bleBreakpoint in didConnect (never hit)Debug Memory Graph (is the peripheral alive?)

3. Files

Logic/L26_FakeBLE.swiftLogic/L26_BleClients.swift

Stuck? Open one hint at a time

Hint 1

Filter the Console for ble. What step is missing?

Hint 2

Who keeps a strong reference to the peripheral?

Hint 3

Core Bluetooth keeps peripherals weakly. The app must keep them.

Show the answer (try first!)
Root cause
  • The client calls connect(peripheral) but stores the peripheral nowhere. The central holds it weakly, so it is freed.
  • The connection is dropped silently. There is no timeout, so the screen waits forever.
How to PROVE it (what you should see)
  • Log: ble_connect_start, then nothing. No ble_connected.
  • Breakpoint in central(didConnect:) is never reached.
Fix
private var band: FakePeripheral?                    // strong reference

func central(didDiscover peripheral: FakePeripheral) {
    band = peripheral
    central.connect(peripheral)
    DispatchQueue.main.asyncAfter(deadline: .now() + 10) { [weak self] in
        guard let self, self.band?.isConnected != true else { return }
        self.onStatus?("Could not connect. Try again.")     // own timeout
    }
}
Prevent it next time
  • Keep the peripheral in a strong property.
  • Add your own connect timeout.
One-line summary

Connect never finished: the peripheral was not retained and connect has no timeout. I stored it and added my own timer.

C27

Heart rate frozen but 'Connected'

CRITICAL
Field report: The heart rate on screen froze at one number while the status still says Connected.

1. Reproduce

  1. Tap Connect. Watch for 20 seconds. The fake band drops the link at 6 seconds.

2. Tools to try

Console filter: bleBreakpoint in didConnectReading: what resets on disconnect?

3. Files

Logic/L26_BleClients.swiftLogic/L26_FakeBLE.swift

Stuck? Open one hint at a time

Hint 1

Find ble_link_lost and what follows it.

Hint 2

After reconnect, do notifications come back? Look for ble_subscribe.

Hint 3

Subscriptions reset when the link drops. The app subscribes only once.

Show the answer (try first!)
Root cause
  • The link is lost and the band forgets the subscription.
  • The app reconnects but subscribes only the first time. No new readings arrive. The screen keeps showing the old number as if it were live.
How to PROVE it (what you should see)
  • Log: one ble_subscribe, then ble_link_lost, then ble_connected and no second ble_subscribe.
  • Screen shows the same bpm while status says Connected.
Fix
func central(didConnect peripheral: FakePeripheral) {
    onStatus?("Connected")
    peripheral.subscribeToHeartRate()          // EVERY connect, not only the first
}

// UI: keep a timestamp for each reading.
// If it is older than 5 seconds: grey it out and show 'NO SIGNAL'.
Prevent it next time
  • Subscribe again after every reconnect.
  • Never show an old reading as live.
  • Alarm on no signal.
One-line summary

After reconnect the subscription was gone. I subscribed on every connect and added a freshness label so old readings cannot look live.

Ward 8: Accessibility and language 2 cases

C28

Accessibility audit fails

MEDIUM
Field report: A hospital accessibility audit failed on the dose card.

1. Reproduce

  1. Pick the biggest text size. Run Xcode > Open Developer Tool > Accessibility Inspector > Audit on the Simulator. Turn on VoiceOver.

2. Tools to try

Accessibility Inspector > AuditVoiceOverDynamic Type size picker in the case

3. Files

CaseViews/W8_UI.swift

Stuck? Open one hint at a time

Hint 1

Run the Audit and read every warning.

Hint 2

Increase the text size. What gets cut off?

Hint 3

Unlabeled buttons, a fixed height, status shown only by color, small touch targets.

Show the answer (try first!)
Root cause
  • Two buttons have no label (VoiceOver says only 'button').
  • The text has a fixed height, so it is clipped at big sizes.
  • Status is shown only by a red dot.
  • Touch targets are 28 pt (minimum is 44).
How to PROVE it (what you should see)
  • Audit lists: element has no description, hit area too small, text clipped.
Fix
Button {
    decreaseDose()
} label: {
    Image(systemName: "minus.circle")
        .frame(minWidth: 44, minHeight: 44)
}
.accessibilityLabel("Decrease dose")

Text("Give 5000 units every 8 hours.")
    .fixedSize(horizontal: false, vertical: true)   // no fixed height

Label("Needs review", systemImage: "exclamationmark.circle")   // icon + text, not color only
Prevent it next time
  • Run the Audit in review.
  • Test with the biggest text and VoiceOver.
One-line summary

Label, Order, Text size, Size of touch, Motion. I fixed labels, removed fixed heights, added text with the color, and made targets 44 pt.

C29

Wrong arrows and raw keys in Arabic

LOW
Field report: Arabic and Hebrew testers say arrows point the wrong way and some text looks like a code.

1. Reproduce

  1. Switch on Right-to-left layout. Set Readings to 1.

2. Tools to try

Edit Scheme > Run > Options > App Language: Right to Left Pseudolanguage and Double-Length PseudolanguageXcode Previews

3. Files

CaseViews/W8_UI.swift

Stuck? Open one hint at a time

Hint 1

Switch the layout direction and compare.

Hint 2

Which symbol does not flip? Which text is not translated?

Hint 3

Hard-coded left arrow, missing string key, no plural rule, fixed date format.

Show the answer (try first!)
Root cause
  • chevron.left is hard-coded and does not flip.
  • vitals.title has no entry in a strings file, so the key shows.
  • '1 readings' has no plural rule.
  • The date format is fixed to US style.
How to PROVE it (what you should see)
  • In right-to-left mode the arrow still points left. The key text appears on screen.
Fix
Image(systemName: "chevron.backward")                 // flips with the language

Text("vitals.title")                                   // add this key to Localizable.xcstrings
Text("readings_today \(count)")                        // plural variations in the String Catalog

Text(Date(), format: .dateTime.day().month().year())   // follows the user's region
Prevent it next time
  • Use leading and trailing, never left and right.
  • String Catalog with plurals.
  • Test with pseudolanguages.
One-line summary

I tested with the right-to-left and double-length pseudolanguages. I used backward chevrons, string catalog plurals, and locale-aware dates.

Ward 9: Release and tools (real phone) 4 cases

C30

Crash log with only hex addresses

MEDIUM
Field report: A TestFlight crash shows only hex addresses. Nobody can read it.

1. Reproduce

  1. Use a real device. Product > Archive (Release). Install it. Tap Crash for symbolication practice. Get the crash log: Xcode > Window > Devices and Simulators > View Device Logs.
  2. Then match the UUID and symbolicate.

2. Tools to try

Window > Devices and Simulators > View Device Logsdwarfdump --uuidatosXcode Organizer > Crashes

3. Files

Logic/L30_SymbolPractice.swift

Stuck? Open one hint at a time

Hint 1

Find the 'Binary Images' section in the log. Note the UUID of your app.

Hint 2

Run dwarfdump --uuid TriageLab.app.dSYM. Do the UUIDs match? A different build has a different UUID.

Hint 3

Use atos -o <dSYM binary> -arch arm64 -l <load address> <crash address> to turn an address into a function name.

Show the answer (try first!)
Root cause
  • Without the dSYM for that exact build, addresses cannot be turned into names.
  • The crash is values[5] on an empty array, three functions deep.
How to PROVE it (what you should see)
  • atos prints SymbolPractice.readLastValue(_:) and the line, then buildSection and startReport.
  • Organizer shows the same stack, readable, if the dSYM is available.
Fix
# In CI after every release archive:
# 1. keep the .xcarchive (it holds the dSYMs)
# 2. check the UUIDs
dwarfdump --uuid TriageLab.app.dSYM

# 3. upload the dSYM to your crash tool
# 4. fail the build if the upload fails
Prevent it next time
  • Upload the dSYM for every build in CI.
  • Keep the archive for every build number.
One-line summary

Missing dSYM means hex stacks. I match UUIDs with dwarfdump, symbolicate with atos, and automate the upload in CI.

C31

Silent kill on an iPhone 11

CRITICAL
Field report: Nurses say the app closes while scanning on an iPhone 11. The crash dashboard is empty.

1. Reproduce

  1. Use a real iPhone. Tap Allocate 50 MB again and again. Watch Memory left fall. iOS closes the app.
  2. Reopen the app. Open Black Box.

2. Tools to try

Black Box: last-run reportConsole (silent_end_suspected)Xcode Organizer > TerminationsDebug > Simulate MetricKit Payloads

3. Files

BlackBox/RunTracker.swiftBlackBox/Memory.swiftApp/AppBootstrap.swift

Stuck? Open one hint at a time

Hint 1

There is no crash report. Open Black Box after the app returns.

Hint 2

Read the last memory used and memory left values.

Hint 3

iOS closes apps that go over their memory limit.

Show the answer (try first!)
Root cause
  • The app grew until iOS closed it (memory limit). iOS gives no crash report for that.
How to PROVE it (what you should see)
  • Black Box: unknown_in_foreground, last screen C31, last memory left close to 0.
  • Log: silent_end_suspected.
Fix
// Detection (already in this app):
// 1. save heartbeat values every few seconds
// 2. on next launch compare: clean exit? updated? reboot? background?
// 3. otherwise: unknown_in_foreground  = hidden crash

// Fix the cause: use less memory (thumbnails, caches with limits).
Prevent it next time
  • Count unknown_in_foreground per version.
  • Watch Organizer Terminations.
One-line summary

No crash report means iOS closed it. My last-run log showed a foreground end with almost no memory left, which proved a memory kill.

C32

Nightly sync is 'scheduled' but never runs

MEDIUM
Field report: The log says the nightly sync was scheduled. It never runs.

1. Reproduce

  1. Use a real iPhone. Tap Schedule nightly sync. Read the log. Then find out why nothing runs.

2. Tools to try

ConsoleInfo.plist (BGTaskSchedulerPermittedIdentifiers)Breakpoint on the submit lineDebug: simulate a background task launch

3. Files

CaseViews/W9_Release.swift (NightlySync)Info.plist

Stuck? Open one hint at a time

Hint 1

Remove the try? from the submit line and print the error.

Hint 2

Compare the identifier in code with the one in Info.plist.

Hint 3

The identifiers differ by a few letters. The error was hidden.

Show the answer (try first!)
Root cause
  • The code uses .nightly. Info.plist allows .nightly-sync. The system refuses the request.
  • try? hides the error, so the log still says 'scheduled'.
How to PROVE it (what you should see)
  • Replace try? with do/catch: error BGTaskSchedulerErrorDomain, not permitted. (On the Simulator the error is 'unavailable'. Background tasks are not supported there.)
Fix
do {
    try BGTaskScheduler.shared.submit(request)
    Log.info(.background, "nightly_sync_scheduled")
} catch {
    Log.error(.background, "nightly_sync_schedule_failed", ["error": "\(error)"])
}
// Make the identifier in code match Info.plist exactly.
Prevent it next time
  • Never hide scheduling errors.
  • Log scheduled, started, time-up, finished.
  • Always add catch-up sync on app open.
One-line summary

try? hid a notPermitted error. The identifier in code did not match Info.plist. I logged the error and fixed the identifier.

C33

Battery drain and a warm phone

HIGH
Field report: After using fall detection the battery drains fast and the phone gets warm.

1. Reproduce

  1. Tap Start fall-detection sensor. Leave the screen. Watch the CPU and Disk gauges in Xcode for one minute.

2. Tools to try

Xcode CPU, Disk and Energy gaugesInstruments: Time Profiler, File Activity, Energy LogConsole

3. Files

Logic/L33_SensorPoller.swift

Stuck? Open one hint at a time

Hint 1

Look at the CPU and Disk gauges after you leave the screen. Do they go down?

Hint 2

Profile it. What runs 100 times a second?

Hint 3

A fast timer writes to a file every time and nothing stops it.

Show the answer (try first!)
Root cause
  • A timer runs every 10 ms (100 times a second). Each tick opens a file and writes one line.
  • Nothing stops it when you leave the screen.
How to PROVE it (what you should see)
  • Time Profiler: poll() and file I/O. File Activity: constant writes. CPU never drops.
Fix
func start() {
    // 10 times a second is enough, and batch the writes.
    timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { [weak self] _ in
        self?.collect()
    }
}

func stop() {
    timer?.invalidate()
    timer = nil
    flushBufferToDisk()
}
// Write in batches. Call stop() when the feature is not needed.
Prevent it next time
  • Lowest rate that works.
  • Batch disk writes.
  • Stop work when the screen is gone.
One-line summary

Battery drain: a 100 Hz timer writing to disk and never stopping. I lowered the rate, batched writes, and stopped it when not needed.

What is NOT in this lab