# HealthProbe – Risks, Limitations & Forensic Capabilities

---

## 1. Known Limitations

### 1.1 HealthKit Framework Constraints

**What HealthProbe Cannot Detect:**

| Gap | Why | Mitigation |
|-----|-----|-----------|
| **Modifications without deletion** | HealthKit has no "modified" event, only "added" and "deleted" | Use snapshot comparison to detect value changes |
| **Lost deletions** | If deletion notification arrives while app backgrounded, we may miss it | Monitor both anchored queries AND deleted objects |
| **Timing precision** | Anchored queries may batch multiple changes, lose granular timestamps | Store both sample timestamp AND observation timestamp |
| **Private HealthKit types** | Some data types not accessible to third-party apps | Accept data available only to Health.app |
| **Cross-device sync delays** | Watch-to-phone-to-cloud can take 24+ hours | Extend observation window, don't flag immediate after device sync |
| **Consolidation / downsampling** | Apple Health/iCloud can rewrite high-frequency historical samples in-place (count decreases; values/intervals change) | Store fingerprints + optionally archive raw samples for selected types (local-only forensic backup mode) |

### 1.2 iOS Background Mode Limitations

**Background Fetch Reality:**
- iOS may delay or skip background fetch requests (battery, network state, user activity)
- No guarantee that HealthProbe will run at specified interval
- User can disable background refresh in Settings → HealthProbe
- System may suspend app if device is low on storage

**Impact:** Anomalies may not be detected for 24-72 hours after occurrence

**Mitigation:**
- Encourage users to open app regularly (at least weekly)
- Provide manual "Check Now" button
- Use `HKObserverQuery` for real-time detection when app is running

### 1.3 Data Retention Constraints

**HealthKit Sample Retention:**
- HealthKit automatically deletes some transient data (e.g., minute-level HR after 90 days)
- User can manually delete samples (HealthProbe cannot prevent this)
- Backups may not restore all data (lossy compression, sync state)

**HealthProbe Impact:**
- Cannot reconstruct data that was never observed
- Snapshot from 6 months ago may have samples no longer in HealthKit
- Gap detection assumes continuous observation (may be false positive if app uninstalled then reinstalled)
- If Apple consolidates history, **counts alone can be misleading** (a month can “lose” samples but keep the same totals via aggregation); value-level forensics are required for proof

---

## 2. Risk Assessment

### 2.1 Privacy Risks (Mitigation: Excellent ✅)

| Risk | Impact | Mitigation |
|------|--------|-----------|
| **Raw health data exfiltration** | CRITICAL: user's personal health history exposed | ✅ Local-only storage, never sends raw samples |
| **Device fingerprinting** | HIGH: tracking user across services | ✅ Salted hash of device ID, stored locally only |
| **Timing attacks** (inferring behavior) | MEDIUM: archive/check patterns reveal habits | ✅ No automatic cloud sync; reports are explicit local exports |
| **App crashes leaking data** | LOW: crash logs may contain HealthKit info | ✅ All logging is aggregated (counts, not values) |

### 2.2 Data Integrity Risks (Mitigation: Good ✅)

| Risk | Impact | Mitigation |
|------|--------|-----------|
| **Snapshot corruption** | HIGH: audit trail becomes unreliable | ✅ Use MD5 checksum of snapshots, detect corruption |
| **Lost audit trail on uninstall** | HIGH: forensic data disappears | ⚠️ PARTIAL: Encourage export before uninstall; future: iCloud backup option |
| **Silent rewrites (no deletion events)** | HIGH: history can change without HKDeletedObject evidence | ✅ Detect via fingerprint diffs; **Forensic Backup Mode** can preserve per-sample evidence locally for selected types |
| **Clock skew** (device time wrong) | MEDIUM: timestamps inaccurate, anomaly detection confused | ⚠️ Log both device time + time since boot, detect skew |
| **Concurrent modification** (app + Health.app) | LOW: race conditions during query | ✅ Anchored queries are atomic |

### 2.3 Security Risks (Mitigation: Good ✅)

| Risk | Impact | Mitigation |
|------|--------|-----------|
| **Malicious apps accessing HealthKit** | MEDIUM: third-party apps can read our data | ✅ iOS sandboxing; ask user for HealthKit permission per app |
| **Jailbroken device** | CRITICAL: all bets off | ⚠️ Not defendable; document assumption: standard iOS device |
| **iCloud account compromise** | MEDIUM: Apple Health/iCloud state may still affect source data | ✅ HealthProbe archive remains local; no HealthProbe CloudKit sync |
| **Local device theft** | MEDIUM: thief can see audit trail | ✅ Data encrypted by iOS, requires device unlock |

---

## 3. Forensic Capabilities

### 3.1 Questions HealthProbe Can Answer

**Q1: "Was my data lost?"**
```
Answer method:
  1. Load all snapshots for "Steps" type
  2. Create timeline: date → sample count
  3. Detect gap where count drops significantly
  4. Report: when, how much, which source
  
Example output:
  ✅ Yes — On 2026-03-15, step data dropped from 8,234 to 2,100
     Loss: 6,134 samples (74.3%)
     Source: "iPhone Health App"
     Severity: CRITICAL
```

**Q2: "Why did my data diverge?"**
```
Answer method:
  1. Load historical aggregates (daily sums)
  2. Fit trend line across 30/60/90 day periods
  3. Calculate deviation from baseline
  4. Correlate with sync state changes & OS updates
  
Example output:
  📊 Step count trending down 15% per month
     Baseline (2025): avg 9,200 steps/day (σ = 1,200)
     Recent (2026): avg 7,800 steps/day (σ = 1,800)
     Correlation: Matches iPhone → Apple Watch priority shift
```

**Q3: "When did this data first appear?"**
```
Answer method:
  1. Search anomaly trail for "historical_insertion"
  2. Find sample in audit trail with matching ID
  3. Report exact timestamp (±1 sync cycle)
  
Example output:
  🔍 Workout "Morning Run" (2025-01-15)
     First observed: 2026-05-01 at 14:35:22 UTC
     Age: 471 days
     Context: iCloud sync completed 2 minutes prior
```

**Q4: "Is my device syncing correctly?"**
```
Answer method:
  1. Load sync state changes
  2. Check for state = "icloud_sync_active" frequency
  3. Measure time between sync completions
  4. Compare to baseline (typical: every 2-4 hours)
  
Example output:
  📡 Sync frequency: ABNORMAL
     Expected: sync every 2-4 hours
     Observed: Last sync 6 days ago
     Status: ⚠️ iCloud sync may be stuck
```

**Q5: "Which devices are contributing data?"**
```
Answer method:
  1. Analyze source distribution in snapshots
  2. Track which source each sample came from
  3. Report composition over time
  
Example output:
  📱 Data source composition:
     iPhone Health: 45% (4,532 samples)
     Apple Watch: 50% (5,041 samples)
     Manual entry: 5% (504 samples)
  
  Trend: Watch contribution increased from 30% (Jan) to 50% (Now)
```

### 3.2 Export Formats for Analysis

**Format 1: JSON Forensic Report**
```json
{
  "export_date": "2026-05-01T14:35:22Z",
  "device": "iPhone 15 Pro",
  "ios_version": "18.4.1",
  "app_version": "1.0.0",
  "observation_period": {
    "start": "2026-01-01T00:00:00Z",
    "end": "2026-05-01T14:35:22Z",
    "days": 120
  },
  "anomalies_summary": {
    "total": 12,
    "critical": 2,
    "warning": 3,
    "info": 7,
    "by_type": {
      "historical_insertion": 5,
      "silent_deletion": 2,
      "duplicate": 3,
      "divergence": 2
    }
  },
  "anomalies": [
    {
      "id": "ANML_20260501_001",
      "type": "silent_deletion",
      "severity": "critical",
      "timestamp": "2026-04-15T08:30:00Z",
      "description": "72 step samples lost without deletion notification",
      "evidence": {
        "sample_type": "Steps",
        "loss_count": 72,
        "loss_percent": 23.4,
        "affected_dates": ["2026-04-13", "2026-04-14", "2026-04-15"]
      }
    }
  ],
  "snapshots": [
    {
      "timestamp": "2026-05-01T14:35:00Z",
      "type": "Steps",
      "count": 305_432,
      "sources": {
        "iPhone Health": 152_716,
        "Apple Watch": 152_716
      }
    }
  ]
}
```

**Format 2: CSV Timeline (for Excel/Sheets)**
```csv
Date,Time,Event,Type,Severity,Description,Details
2026-01-01,08:15,Initial Snapshot,snapshot,info,Baseline established,305432 steps
2026-02-15,14:20,Historical Insertion,anomaly,medium,Data appeared retroactively,Workout from 2025-01-15
2026-03-15,09:00,Silent Deletion,anomaly,critical,Data gap detected,72 steps lost
2026-04-20,16:45,Sync State Change,sync,info,iCloud sync completed,Samples added: 87
```

**Format 3: Markdown Report (for Bug Submissions)**
```markdown
# Apple Health Data Integrity Issue Report

## Timeline
- **Start observation:** 2026-01-01
- **Last check:** 2026-05-01
- **Total observations:** 120 days

## Issue Summary
3 critical anomalies detected involving 280+ data samples and 15 days of missing data.

### Critical Finding #1: Silent Deletion (2026-03-15)
- **Type:** 72 step samples disappeared without notification
- **Date affected:** 2026-04-13 to 2026-04-15
- **Detection:** Snapshot comparison (305,432 → 305,360)
- **Severity:** Critical
- **Context:** Occurred 3 days after iOS 18.4 update

### Critical Finding #2: Historical Insertion (2026-02-15)
- **Type:** Workout appears 471 days after original date
- **Sample:** "Morning Run" from 2025-01-15
- **First observed:** 2026-02-15 14:20 UTC
- **Context:** 2 minutes after iCloud sync completed
- **Severity:** Medium (likely restore from backup)

## Recommendations
1. Verify data integrity on other devices
2. Compare with iCloud.com Health export
3. Review iOS 18.4 release notes for HealthKit changes
4. Check if backup restore was interrupted
```

### 3.3 Forensic Techniques Enabled by HealthProbe

**Technique 1: Timeline Reconstruction**
```
Given: Snapshots at [T0, T1, T2, ...]
Compute: Δ_count = snapshot[T_i] - snapshot[T_i-1]
Result: Visual timeline of when data appeared/disappeared
Use: Correlate with sync events, OS updates, app launches
```

**Technique 2: Source Attribution**
```
Given: Source field in each snapshot
Track: iPhone vs. Watch vs. Manual contributions
Result: Identify which device is unreliable
Use: Isolate whether issue is device, OS, or iCloud
```

**Technique 3: Anomaly Clustering**
```
Given: All anomalies with timestamps
Cluster: Group nearby anomalies (e.g., within 24 hours)
Result: Pattern detection — is this systemic or isolated?
Use: Determine if it's device-specific or iOS version issue
```

**Technique 4: Cross-Device Correlation** (Future: macOS)
```
Given: Multiple device's HealthProbe exports
Compare: Are anomalies synchronized across devices?
Result: Distinguish local bug from iCloud sync issue
Use: Report "this affects all devices" vs. "only this device"
```

---

## 4. Comparison: HealthProbe vs. Alternatives

| Feature | HealthProbe | Health.app | Third-party apps |
|---------|------------|-----------|-----------------|
| **Real-time monitoring** | ✅ Yes | ❌ No | ⚠️ Partial |
| **Audit trail** | ✅ Yes | ❌ No | ❌ No |
| **Detects data loss** | ✅ Yes | ❌ No (silent) | ❌ No |
| **Privacy (no exfiltration)** | ✅ Yes | ✅ Yes | ❌ Often sells data |
| **Local-only** | ✅ Yes | ✅ Yes | ❌ Often cloud-based |
| **Open source** | 🔄 Future | ❌ No | ⚠️ Some are |
| **Forensic export** | ✅ Yes | ❌ No | ⚠️ Limited |

---

## 5. Recommended Usage Patterns

### 5.1 For Individual Users (Personal Monitoring)

```
Baseline:
  1. Install HealthProbe
  2. Let it run for 30 days to establish baseline
  3. Export first "clean" snapshot
  
Ongoing:
  1. Check app weekly (or enable background notifications)
  2. If anomaly alert → Screenshot it
  3. If critical → Export full report immediately
  4. Keep exported reports in Notes/Files app as backup
  
Post-incident:
  1. Export complete forensic report
  2. Attach to Apple Feedback Assistant ticket
  3. Include link to DearApple issue #001
```

### 5.2 For Researchers (Data Collection)

```
Setup:
  1. Export anonymized anomaly summaries manually
  2. Keep raw archive local
  
Analysis:
  1. Correlate own data loss with iOS release dates
  2. Compare patterns with other HealthProbe users
  3. Contribute findings to DearApple repository
```

### 5.3 For Apple Support / Developers

```
When submitting feedback:
  1. Include HealthProbe forensic export
  2. Specify device model, iOS version, exact reproduction steps
  3. Include timeline showing when anomalies appeared
  4. Mention if pattern repeats across multiple devices
```

---

## 6. Future Enhancements (Post-MVP)

### 6.1 Machine Learning Anomaly Scoring
```
Current: Binary detection (anomaly or not)
Future: Confidence scoring (0-100%)
  - Low risk: Temporary duplicates, minor drifts
  - High risk: Permanent loss, systematic divergence
  - Enable severity-based alerting
```

### 6.2 Community Pattern Database
```
Current: Single-device observation
Future: Anonymized multi-device dataset
  - iOS 18.4 affected 23% of users
  - "Morning Run" workout loses 15% post-sync (systematic)
  - Identify if issue is iOS, device model, or iCloud region specific
```

### 6.3 Predictive Detection
```
Current: Detect after anomaly occurs
Future: Alert before data is lost
  - Watch for sync stall patterns
  - Pre-loss indicators (e.g., rapid duplicates → deletion)
```

---

## 7. Troubleshooting HealthProbe Itself

### Common Issues

| Issue | Cause | Fix |
|-------|-------|-----|
| **No anomalies detected for weeks** | Background fetch disabled | Settings → HealthProbe → Background Refresh |
| **Snapshots not being saved** | Insufficient storage or archive write failure | Free up space; verify local archive health and SwiftData cache rebuild |
| **Sync state not updating** | iCloud token check failing | Sign out/in to iCloud; restart device |
| **Old audit trail entries missing** | SwiftData cache/log retention policy or migration issue | Rebuild derived views from archive where possible; export reports before uninstall |

---

## 8. References

- **iOS HealthKit Framework:** https://developer.apple.com/documentation/healthkit/
- **HKAnchoredObjectQuery:** https://developer.apple.com/documentation/healthkit/hkanchoredrobjectquery
- **SwiftData Persistence:** https://developer.apple.com/documentation/swiftdata
- **DearApple Issue #001:** Apple Health mass data loss investigation
- **Apple Privacy:** https://www.apple.com/privacy/

---

*HealthProbe — Forensics for Your Health Data*  
*Document v1.0 — 2026-05-01*
