# Charge Session Integrity and Conflict Healing

## Core Invariant

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

"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.

---

## How the Invariant Is Enforced at Creation

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

```swift
guard fetchOpenSessionObject(forMeterMACAddress: snapshot.meterMACAddress) == nil else {
    return
}
```

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.

---

## Scenarios Where the Invariant Can Be Violated

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

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

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.

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

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.

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

`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.

---

## Healing Mechanism

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

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

### Algorithm

1. Fetch all open sessions (status `active` or `paused`).
2. Group by `meterMACAddress`.
3. For any group with more than one session:
   - **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.
   - Tie-break: higher `measuredEnergyWh` wins (the session that observed more charging is likely more useful).
   - **Loser(s)**: closed with status `abandoned`, `endedAt` set to **winner's `startedAt`**.
4. Save, then refresh derived metrics for affected devices.

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

`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.

### Overlap prevention

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:

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

---

## Data Model

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

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

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

---

## UI Indicators

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

- 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."*
- The secondary info line includes **"Auto-closed (sync conflict)"** alongside other metadata (transport mode, trim, source mode).

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

---

## What Is Not Covered

### Detection at session-start time

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).

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

### Manual conflict resolution

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.

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

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.

### Paused session + new session conflict

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.

---

## Future Considerations

- 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.
- If session merging becomes desirable (combine energy from both conflicting sessions into one record), `wasConflictHealed` provides the signal to identify candidates.
- 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.
