USB-Meter / Documentation / Charge Session Integrity and Conflict Healing.md
Newer Older
128 lines | 7.306kb
Bogdan Timofte authored a month ago
1
# Charge Session Integrity and Conflict Healing
2

            
3
## Core Invariant
4

            
5
**A meter can have at most one open charge session at any given time.**
6

            
7
"Open" means `statusRawValue` is either `active` or `paused`. This invariant is used throughout the app to look up the active session for a meter without ambiguity.
8

            
9
---
10

            
11
## How the Invariant Is Enforced at Creation
12

            
13
`ChargeInsightsStore.startSession(...)` checks for an existing open session on the same `meterMACAddress` before creating a new one:
14

            
15
```swift
16
guard fetchOpenSessionObject(forMeterMACAddress: snapshot.meterMACAddress) == nil else {
17
    return
18
}
19
```
20

            
21
This check is sufficient when all devices are online and share a consistent view of the CloudKit store. It is **not sufficient** when devices work offline independently.
22

            
23
---
24

            
25
## Scenarios Where the Invariant Can Be Violated
26

            
27
### Scenario A — Forgotten session + new session on another device (primary concern)
28

            
29
1. The user starts a session on **Device A** and forgets about it (walks away, doesn't close the app).
30
2. The user picks up **Device B**, which has not yet synced from Device A.
31
3. Device B finds no open session for the meter (it doesn't know about Device A's session yet).
32
4. Device B creates a new session successfully.
33
5. When both devices come back online and CloudKit syncs, **both sessions are open** for the same meter.
34

            
35
This is the most realistic scenario. Current meters (UM25C, UM34C, TC66C) only support one BT connection at a time, so both sessions cannot be live simultaneously — but the forgotten session remains open in the database.
36

            
37
### Scenario B — Two devices simultaneously offline on meters that support multiple connections
38

            
39
If a future meter model supports multiple concurrent BT connections, two devices could legitimately start sessions for the same meter at the same time, both while offline. The healing mechanism covers this automatically, though the winner selection may be debatable in that case.
40

            
41
### Scenario C — CloudKit conflict on `statusRawValue` itself
42

            
43
`NSMergeByPropertyObjectTrumpMergePolicy` is used throughout: in-memory values win over CloudKit-synced values at the Core Data level. This means a `stopSession` write on Device A while Device B has also written to the same session record could theoretically produce inconsistent `statusRawValue` after sync. This is distinct from the duplicate-session scenario and is considered unlikely in practice, but worth noting.
44

            
45
---
46

            
47
## Healing Mechanism
48

            
49
`ChargeInsightsStore.healDuplicateOpenSessions()` is called from `AppData.reloadChargedDevices()` on every reload cycle, which is triggered by:
50

            
51
- App startup (first device list load)
52
- Every remote CloudKit change (`NSPersistentStoreRemoteChange` notification)
53
- Every local Core Data write (via `NSManagedObjectContextDidSave`)
54

            
55
### Algorithm
56

            
57
1. Fetch all open sessions (status `active` or `paused`).
58
2. Group by `meterMACAddress`.
59
3. For any group with more than one session:
60
   - **Winner** = session with the latest `startedAt`. This represents the user's most recent explicit intent — they chose to start a new session, which means the older one was forgotten.
61
   - Tie-break: higher `measuredEnergyWh` wins (the session that observed more charging is likely more useful).
62
   - **Loser(s)**: closed with status `abandoned`, `endedAt` set to **winner's `startedAt`**.
63
4. Save, then refresh derived metrics for affected devices.
64

            
65
### Why `startedAt` instead of `updatedAt` for winner selection
66

            
67
`updatedAt` reflects the last write to the record, which could be CloudKit metadata or a background observation flush — not necessarily a user action. `startedAt` is set once at creation and directly represents the user's decision to begin a session. The session started later is the one the user *intended* to be active.
68

            
69
### Overlap prevention
70

            
71
The loser's `endedAt` is set to the winner's `startedAt` (not `Date()` / "now"). This ensures the two sessions are contiguous with no gap and no overlap, which is important for:
72

            
73
- Correct total energy accounting across a device's session history
74
- Clean chart rendering (no two sessions claiming the same time range)
75
- Capacity estimation (no double-counting of energy delivered in the same window)
76

            
77
---
78

            
79
## Data Model
80

            
81
`ChargeSession` entity (Core Data model v16) includes:
82

            
83
| Attribute | Type | Purpose |
84
|---|---|---|
85
| `wasConflictHealed` | `Boolean, optional` | `true` on sessions closed by the healing mechanism. `nil`/`false` on normal sessions. |
86

            
87
This attribute is synced via CloudKit so all devices eventually see the flag, even if healing ran on only one of them.
88

            
89
---
90

            
91
## UI Indicators
92

            
93
Sessions with `wasConflictHealed == true` are visually distinguished in `ChargedDeviceSessionsView`:
94

            
95
- An **orange icon** (⟳) appears next to the status badge in the session card header, with a tooltip: *"This session was automatically closed because a newer session was started on another device while offline."*
96
- The secondary info line includes **"Auto-closed (sync conflict)"** alongside other metadata (transport mode, trim, source mode).
97

            
98
The intent is to surface the event without alarming the user — the data is intact and the time range is correctly bounded.
99

            
100
---
101

            
102
## What Is Not Covered
103

            
104
### Detection at session-start time
105

            
106
When Device B starts a session while offline, it cannot know that Device A has an open session. There is no mechanism to warn the user before the conflict occurs. Healing is entirely reactive (post-sync).
107

            
108
A proactive approach would require a "soft lock" written to CloudKit before starting a session, which introduces latency and complexity. Not implemented.
109

            
110
### Manual conflict resolution
111

            
112
Currently the loser is always automatically abandoned. There is no UI for the user to inspect the conflict and choose which session to keep, merge, or adjust. For the current meter lineup (single-connection BT), the automatic resolution is almost always correct.
113

            
114
### Overlapping sessions on the same `chargedDeviceID` across different meters
115

            
116
The invariant is enforced per `meterMACAddress`, not per `chargedDeviceID`. If the same physical device is charged on two different meters simultaneously (unlikely but possible with future hardware), both sessions would have different MAC addresses and the invariant would not catch them. The healing mechanism would not fire because there is no duplicate per MAC.
117

            
118
### Paused session + new session conflict
119

            
120
A paused session is still "open" and is treated the same as an active session for healing purposes. If healing runs on a paused + active pair, the paused session (earlier `startedAt`) becomes the loser. This is correct: the user started a new session, so the paused one was effectively abandoned.
121

            
122
---
123

            
124
## Future Considerations
125

            
126
- If future meters support multiple concurrent connections, the winner-selection strategy (latest `startedAt`) should be re-evaluated — in that case the session with more observed data might be preferable.
127
- If session merging becomes desirable (combine energy from both conflicting sessions into one record), `wasConflictHealed` provides the signal to identify candidates.
128
- A "conflict history" section in the device detail or a one-time notification could be added to inform users when healing has run, especially if conflicts become more frequent with new hardware.