Skip to content

Commit 3429c22

Browse files
committed
Add explanation about BG execution of Loop mode
1 parent 9540ad3 commit 3429c22

File tree

1 file changed

+328
-0
lines changed

1 file changed

+328
-0
lines changed
Lines changed: 328 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,328 @@
1+
# Loop Mode Background Execution: Constraints and Solutions
2+
3+
## Overview
4+
5+
Loop Mode performs repeated network speed tests with configurable waiting periods between tests (time-based and/or distance-based). Unlike Network Coverage, which measures lightweight pings continuously, Loop Mode runs full throughput tests (ping, download, upload, QoS) that involve sustained multi-threaded socket I/O. This document explains why Loop Mode tests cannot run in the background and proposes a minimal, App Review-compliant solution that allows the waiting period to progress while backgrounded.
6+
7+
---
8+
9+
## Why Loop Mode Tests Cannot Run in Background
10+
11+
### 1. Technical Constraints: Socket Connection Lifecycle
12+
13+
Loop Mode's measurement architecture (`RMBTTestRunner`, `RMBTTestWorker`) relies on:
14+
15+
- **CocoaAsyncSocket** for TCP connections to measurement servers
16+
- **Multiple parallel worker threads** (typically 3–4) for concurrent downloads/uploads
17+
- **Sustained high-bandwidth transfers** lasting 7–10 seconds per phase
18+
- **Stateful socket connections** that must remain open throughout measurement
19+
20+
| Aspect | Foreground | Background (even with `CLBackgroundActivitySession`) |
21+
|--------|------------|------------------------------------------------------|
22+
| Socket lifecycle | Full control; connections persist | iOS throttles/tears down connections |
23+
| Thread scheduling | Workers run continuously | Threads suspended or deprioritized |
24+
| Bandwidth allocation | Full radio budget | Duty-cycled; throttled to save power |
25+
| Test reliability | High | **Low: frequent failures, corrupted results** |
26+
27+
**Technical reality:** iOS routinely terminates or throttles long-running socket connections in the background, even when an app holds `CLBackgroundActivitySession`. Background modes are designed for lightweight tasks (location updates, small network requests), not sustained throughput measurements.
28+
29+
### 2. App Store Policy: Abuse of Background Location
30+
31+
The app already declares `UIBackgroundModes = ["location"]` for Network Coverage, which is legitimate because:
32+
33+
- **Primary purpose:** Location tracking (WHERE the user is)
34+
- **Secondary network activity:** Small ICMP pings (~64 bytes, periodic)
35+
- **Intent alignment:** Measuring cellular coverage at different locations
36+
37+
If Loop Mode were to run speed tests in the background:
38+
39+
- **Primary purpose:** Network throughput testing (NOT location-based)
40+
- **Network activity:** Megabytes of sustained TCP transfers
41+
- **Intent mismatch:** Using location mode as a loophole to run bandwidth tests
42+
43+
**App Review risk:** Apple rejects apps that abuse background location for non-location purposes. Running multi-megabyte speed tests while claiming "location-based service" is a clear violation.
44+
45+
### 3. Comparison to Network Coverage
46+
47+
| Feature | Network Coverage | Loop Mode Speed Tests |
48+
|---------|------------------|----------------------|
49+
| **Network load** | ~64 bytes per ping, every 2s | Megabytes per test, sustained |
50+
| **Connection type** | UDP (connectionless) | TCP (stateful, multi-threaded) |
51+
| **Duration** | Continuous background OK | 7–10s bursts, foreground only |
52+
| **iOS compatibility** | ✅ Works with `CLBackgroundActivitySession` | ❌ iOS kills sockets |
53+
| **App Review legitimacy** | ✅ Location-based service | ❌ Network testing disguised as location |
54+
55+
**Key insight:** The Network Coverage implementation (Sources/NetworkCoverage/) cannot be directly applied to Loop Mode because the underlying workload is fundamentally different.
56+
57+
---
58+
59+
## Current Behavior (Foreground-Only)
60+
61+
### Implementation (Sources/RMBTTestRunner.swift:568-573)
62+
63+
```swift
64+
@objc func applicationDidSwitchToBackground(_ notification: Notification) {
65+
Log.logger.error("App backgrounded, aborting \(notification)")
66+
workerQueue.async {
67+
self.cancel(with: .appBackgrounded)
68+
}
69+
}
70+
```
71+
72+
When the app backgrounds during a Loop Mode test:
73+
74+
1. **Active test cancelled** (Sources/RMBTTestRunner.swift:259-287)
75+
2. **TestViewController handles cancellation** (Sources/Test/RMBTTestViewController.swift:802-807)
76+
3. **Loop session transitions to waiting state** (already implemented, line 805)
77+
4. **Waiting logic uses timers/location tracker** (RMBTTestViewController.swift:569-620)
78+
- Timer runs every 0.3s to check time elapsed (line 589)
79+
- Location tracker monitors distance traveled (line 592-620)
80+
- **Problem:** Timers don't fire when app is suspended; location tracker is stopped by AppDelegate
81+
82+
### Why Waiting Fails in Background
83+
84+
From RMBTAppDelegate.swift:
85+
86+
```swift
87+
func applicationDidEnterBackground(_ application: UIApplication) {
88+
RMBTLocationTracker.shared.stop() // ← Stops location updates
89+
NetworkReachability.shared.stopMonitoring()
90+
}
91+
```
92+
93+
From RMBTTestViewController.swift:
94+
95+
```swift
96+
private func startWaitingNextTest() {
97+
// ← Timer-based waiting: won't run while suspended
98+
timer = Timer.scheduledTimer(timeInterval: 0.3, target: self, selector: #selector(tick), userInfo: nil, repeats: true)
99+
}
100+
```
101+
102+
**Result:** When app backgrounds during waiting, both time and distance tracking stop. User must keep app in foreground for entire loop duration.
103+
104+
---
105+
106+
## Proposed Solution: Background Waiting (Tests Remain Foreground-Only)
107+
108+
### Strategy
109+
110+
1. **Tests run in foreground only** (keep existing cancellation behavior)
111+
2. **Waiting period continues in background**
112+
- Time-based: Compute elapsed on resume (no active timer)
113+
- Distance-based: Subscribe to Network Coverage location stream
114+
3. **User notified when ready** via local notification
115+
4. **Next test starts only when app is foregrounded**
116+
117+
### Architecture
118+
119+
```
120+
Loop Mode Flow (with background waiting):
121+
122+
┌─────────────────────────────────────────────────────────────┐
123+
│ Foreground: Speed Test Running │
124+
│ - RMBTTestRunner active │
125+
│ - CocoaAsyncSocket workers running │
126+
│ - NO background activity session │
127+
└─────────────────────────────────────────────────────────────┘
128+
129+
│ Test completes
130+
131+
┌─────────────────────────────────────────────────────────────┐
132+
│ Waiting State (can background) │
133+
│ - START: BackgroundActivityActor.shared.startActivity() │
134+
│ - Time tracking: Store waitingStartedAt, compute on resume │
135+
│ - Distance tracking: Subscribe to Coverage location stream │
136+
│ - Ready detection: Post notification, wait for foreground │
137+
│ - STOP: BackgroundActivityActor.shared.stopActivity() │
138+
└─────────────────────────────────────────────────────────────┘
139+
140+
│ Time/distance reached + app foregrounded
141+
142+
┌─────────────────────────────────────────────────────────────┐
143+
│ Foreground: Next Speed Test Starting │
144+
│ (cycle repeats) │
145+
└─────────────────────────────────────────────────────────────┘
146+
```
147+
148+
### Implementation Plan
149+
150+
#### 1. Create Loop Waiting Coordinator
151+
152+
**New file:** `Sources/Test/LoopMode/LoopWaitingCoordinator.swift`
153+
154+
**Responsibilities:**
155+
- Start/stop `BackgroundActivityActor` during waiting lifecycle
156+
- Subscribe to `RealLocationUpdatesService().locations()` (reuse Network Coverage stream)
157+
- Compute time-based readiness without active timers
158+
- Post local notification when conditions met
159+
160+
**Key methods:**
161+
```swift
162+
@MainActor
163+
class LoopWaitingCoordinator {
164+
func startWaiting(minutes: UInt, meters: UInt, startLocation: CLLocation?) async
165+
func stopWaiting() async
166+
func checkTimeReached() -> Bool // Compute elapsed, no timer
167+
func checkDistanceReached(currentLocation: CLLocation) -> Bool
168+
private func notifyReady(reason: String) // Local notification
169+
}
170+
```
171+
172+
#### 2. Integrate in RMBTTestViewController
173+
174+
**Modified methods:**
175+
176+
- `goToWaitingState()` (line 622):
177+
- Create `LoopWaitingCoordinator` instance
178+
- Call `await coordinator.startWaiting(...)`
179+
- Remove call to `startWaitingNextTest()` (timer-based approach)
180+
181+
- `cleanup()` (line 545):
182+
- Call `await coordinator.stopWaiting()`
183+
- Stop background activity session
184+
185+
- `didBecomeActive(_:)` (line 416):
186+
- Check if waiting completed in background
187+
- If ready, call `startTest()` to begin next test
188+
189+
**Deleted methods:**
190+
- `startWaitingNextTest()` (line 588) – replaced by coordinator
191+
- `tick()` (line 569) – no longer needed (time computed on demand)
192+
193+
#### 3. Request Notification Permission
194+
195+
**File:** `Sources/RMBTAppDelegate.swift`
196+
197+
Add to `applicationDidFinishLaunching`:
198+
```swift
199+
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { granted, _ in
200+
Log.logger.info("Loop Mode notification permission: \(granted)")
201+
}
202+
```
203+
204+
#### 4. NO Changes to RMBTTestRunner
205+
206+
**Keep existing background cancellation:**
207+
- Tests cancelled when backgrounded (line 568-573)
208+
- Loop session survives via existing `onTestCancelled` logic (line 802-807)
209+
- TestViewController transitions to waiting automatically
210+
211+
---
212+
213+
## Benefits of This Approach
214+
215+
### ✅ Compliance & Reliability
216+
217+
| Aspect | Status |
218+
|--------|--------|
219+
| **App Store guidelines** | ✅ Only location tracking in background (legitimate use) |
220+
| **iOS socket constraints** | ✅ No sockets active in background (tests foreground-only) |
221+
| **Test result integrity** | ✅ All measurements in foreground (full system resources) |
222+
| **Background execution budget** | ✅ Minimal (location updates only, proven by Coverage) |
223+
224+
### ✅ User Experience
225+
226+
- **Passive waiting:** User can background app between tests
227+
- **Notification:** Clear prompt to return when next test is ready
228+
- **Transparency:** User understands tests run in foreground, waiting can background
229+
- **Battery efficiency:** No sustained network I/O in background
230+
231+
### ✅ Code Reuse
232+
233+
- **BackgroundActivityActor:** Already implemented for Network Coverage
234+
- **Location stream:** Reuse `RealLocationUpdatesService().locations()`
235+
- **Persistence patterns:** Optional future enhancement (not required for MVP)
236+
237+
---
238+
239+
## Limitations & Trade-offs
240+
241+
### What This Does NOT Solve
242+
243+
1. **App termination:** If iOS kills app during waiting, loop session is lost
244+
- **Mitigation:** Future enhancement with SwiftData persistence (like Coverage)
245+
246+
2. **Test execution:** Tests still require foreground
247+
- **Mitigation:** Clear user notification; acceptable UX for measurement app
248+
249+
3. **Instant start:** User must manually open app when notified
250+
- **Mitigation:** Standard iOS behavior; users are accustomed to this
251+
252+
### Alternative: Make Tests Background-Compatible?
253+
254+
**Not feasible because:**
255+
- Would require rewriting entire test engine (RMBTTestRunner + workers)
256+
- Still subject to iOS socket throttling (unreliable results)
257+
- App Review would likely reject (abuse of background location)
258+
- Network Coverage approach (UDP pings) not applicable to TCP throughput tests
259+
260+
---
261+
262+
## Files to Modify (Minimal Implementation)
263+
264+
| File | Changes | Lines |
265+
|------|---------|-------|
266+
| **New:** `Sources/Test/LoopMode/LoopWaitingCoordinator.swift` | Create waiting coordinator | ~100 |
267+
| `Sources/Test/RMBTTestViewController.swift` | Integrate coordinator, remove timer logic | ~50 |
268+
| `Sources/RMBTAppDelegate.swift` | Request notification permission | ~5 |
269+
| **No change:** `Sources/RMBTTestRunner.swift` | Keep existing background cancellation | 0 |
270+
271+
**Total:** 1 new file, 2 modified files, ~155 lines of code
272+
273+
---
274+
275+
## Testing Checklist
276+
277+
### Basic Flow
278+
- [ ] Start loop with 3 tests, 2-minute wait, 100-meter distance
279+
- [ ] Background app during test #1 → verify test cancelled, transitions to waiting
280+
- [ ] Leave backgrounded for 2 minutes → verify notification posted
281+
- [ ] Foreground app → verify test #2 starts automatically
282+
283+
### Edge Cases
284+
- [ ] Background during waiting → foreground before time/distance reached → verify still waiting
285+
- [ ] Achieve distance threshold while backgrounded → verify notification
286+
- [ ] Revoke location permission during waiting → verify graceful error
287+
- [ ] Toggle airplane mode during waiting → verify loop handles mixed connectivity
288+
- [ ] Force-quit app during waiting → verify no crash on relaunch (session lost, expected)
289+
290+
### Background Execution
291+
- [ ] Monitor `BackgroundActivityActor.isActive()` during waiting (should be true)
292+
- [ ] Verify location updates continue via Coverage stream
293+
- [ ] Verify no socket connections active during waiting
294+
- [ ] Check battery usage (should be comparable to Coverage feature)
295+
296+
---
297+
298+
## Future Enhancements (Out of Scope for Minimal Implementation)
299+
300+
### Persistence for Crash Recovery
301+
Add SwiftData models similar to `PersistentCoverageSession`:
302+
- Store `PersistentLoopSession` (loop UUID, current test count, waiting state)
303+
- On app relaunch, check for incomplete session
304+
- Prompt user: "Resume previous loop test?"
305+
306+
### Progress UI While Backgrounded
307+
- Notification extensions showing "Test 3/10 completed, waiting..."
308+
- Today widget with loop progress bar
309+
310+
### Adaptive Notification Timing
311+
- If user repeatedly ignores notifications, delay or suppress
312+
- If user always responds immediately, be more proactive
313+
314+
---
315+
316+
## References
317+
318+
- **Network Coverage implementation:** Sources/NetworkCoverage/BackgroundActivityActor.swift
319+
- **Current loop waiting logic:** Sources/Test/RMBTTestViewController.swift:569-620
320+
- **Test cancellation:** Sources/RMBTTestRunner.swift:568-573
321+
- **Location stream:** Sources/NetworkCoverage/LocationUpdates/LocationUpdatesService.swift
322+
- **Apple docs:** [Background Execution](https://developer.apple.com/documentation/uikit/app_and_environment/scenes/preparing_your_ui_to_run_in_the_background)
323+
324+
---
325+
326+
## Summary
327+
328+
Loop Mode speed tests **cannot** run in background due to iOS socket lifecycle constraints and App Store policy. The minimal viable solution is to keep tests foreground-only while allowing the **waiting period** to progress in background using `CLBackgroundActivitySession` and the proven Network Coverage location stream. This approach is App Review-compliant, technically reliable, and requires minimal code changes (~155 lines across 3 files).

0 commit comments

Comments
 (0)