wallmonitor 0.3.0__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: wallmonitor
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Local-only monitoring and recording UI for a Tesla Wall Connector Gen 3
5
5
  Keywords: tesla,wall-connector,ev-charging,monitoring,self-hosted,thermal-model
6
6
  Author: Fernando Gonzalez
@@ -59,18 +59,29 @@ On first contact the monitor pins the charger's serial number: if a
59
59
  different unit ever answers at that address, it alarms and pauses recording
60
60
  rather than blending two chargers' histories.
61
61
 
62
+ More than one Wall Connector? Run one instance per charger — `--label` names
63
+ each in the header and notifications, `--peer` links them so the header hops
64
+ between dashboards, and the service installer's `--name` does it all per
65
+ charger in one command. See [More than one Wall Connector](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md#more-than-one-wall-connector).
66
+
62
67
  All history lands in a single `wallmonitor.db` SQLite file — back up that
63
68
  one file and you have everything. For every option, and for running it as a
64
69
  systemd service on an always-on box, see [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md).
65
70
 
66
71
  ## At a glance
67
72
 
73
+ - Zero-config setup — `--discover` finds the charger on your LAN; the
74
+ serial is pinned on first contact so a swapped or second unit can never
75
+ blend into your history
68
76
  - Full-fidelity recording — every response stored with its complete raw JSON
77
+ (optional retention trims old raw blobs so the database stays near-flat)
69
78
  - Live dashboard (SSE) with rolling charts, an active-alert banner, and a
70
79
  live derate-forecast chart: measured handle temperature against the
71
80
  model's projected plateau and the trip threshold, projection drawn
72
81
  forward so the predicted trip intercept is visible on the chart
73
- - Session review: energy, peak/average power, per-phase telemetry, drillable charts
82
+ - Session review: energy, peak/average power, per-phase telemetry, drillable
83
+ charts, and forecast hindsight — what the model predicted at each tick
84
+ against what the handle actually did
74
85
  - Event timeline with range presets, category filters, and paging
75
86
  - Alert decoding and EVSE-state labels, each marked verified vs community-reported
76
87
  - Wi-Fi health history and connectivity events
@@ -86,6 +97,8 @@ systemd service on an always-on box, see [Running wallmonitor](https://github.co
86
97
  webhook/self-hosted ntfy for phones, with a systemd + Docker deploy recipe
87
98
  - Resilience: seamless restarts, downtime recorded as explicit gap events,
88
99
  sensor-glitch quarantine
100
+ - Several chargers: one labeled instance each, linked by a header switcher;
101
+ per-install thermal models stay separate by construction
89
102
 
90
103
  ## Works out of the box — everything else is additive
91
104
 
@@ -100,7 +113,7 @@ plain LAN webhook, a REST call) rather than being wired into the core.
100
113
 
101
114
  | Page | What's in it |
102
115
  |---|---|
103
- | [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md) | Every option, systemd service install, tests |
116
+ | [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md) | Every option, finding your charger, device identity, multiple chargers, systemd service install |
104
117
  | [What gets recorded](https://github.com/zebraengine/wallmonitor/blob/main/docs/recording.md) | Recording fidelity, sessions, events, alert/EVSE label verification, resilience |
105
118
  | [Thermal model](https://github.com/zebraengine/wallmonitor/blob/main/docs/thermal-model.md) | The derate forecast and the degradation watch, in full detail |
106
119
  | [Amp control](https://github.com/zebraengine/wallmonitor/blob/main/docs/amp-control.md) | Automatic derate prevention over BLE: design, guards, backtesting |
@@ -36,18 +36,29 @@ On first contact the monitor pins the charger's serial number: if a
36
36
  different unit ever answers at that address, it alarms and pauses recording
37
37
  rather than blending two chargers' histories.
38
38
 
39
+ More than one Wall Connector? Run one instance per charger — `--label` names
40
+ each in the header and notifications, `--peer` links them so the header hops
41
+ between dashboards, and the service installer's `--name` does it all per
42
+ charger in one command. See [More than one Wall Connector](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md#more-than-one-wall-connector).
43
+
39
44
  All history lands in a single `wallmonitor.db` SQLite file — back up that
40
45
  one file and you have everything. For every option, and for running it as a
41
46
  systemd service on an always-on box, see [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md).
42
47
 
43
48
  ## At a glance
44
49
 
50
+ - Zero-config setup — `--discover` finds the charger on your LAN; the
51
+ serial is pinned on first contact so a swapped or second unit can never
52
+ blend into your history
45
53
  - Full-fidelity recording — every response stored with its complete raw JSON
54
+ (optional retention trims old raw blobs so the database stays near-flat)
46
55
  - Live dashboard (SSE) with rolling charts, an active-alert banner, and a
47
56
  live derate-forecast chart: measured handle temperature against the
48
57
  model's projected plateau and the trip threshold, projection drawn
49
58
  forward so the predicted trip intercept is visible on the chart
50
- - Session review: energy, peak/average power, per-phase telemetry, drillable charts
59
+ - Session review: energy, peak/average power, per-phase telemetry, drillable
60
+ charts, and forecast hindsight — what the model predicted at each tick
61
+ against what the handle actually did
51
62
  - Event timeline with range presets, category filters, and paging
52
63
  - Alert decoding and EVSE-state labels, each marked verified vs community-reported
53
64
  - Wi-Fi health history and connectivity events
@@ -63,6 +74,8 @@ systemd service on an always-on box, see [Running wallmonitor](https://github.co
63
74
  webhook/self-hosted ntfy for phones, with a systemd + Docker deploy recipe
64
75
  - Resilience: seamless restarts, downtime recorded as explicit gap events,
65
76
  sensor-glitch quarantine
77
+ - Several chargers: one labeled instance each, linked by a header switcher;
78
+ per-install thermal models stay separate by construction
66
79
 
67
80
  ## Works out of the box — everything else is additive
68
81
 
@@ -77,7 +90,7 @@ plain LAN webhook, a REST call) rather than being wired into the core.
77
90
 
78
91
  | Page | What's in it |
79
92
  |---|---|
80
- | [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md) | Every option, systemd service install, tests |
93
+ | [Running wallmonitor](https://github.com/zebraengine/wallmonitor/blob/main/docs/running.md) | Every option, finding your charger, device identity, multiple chargers, systemd service install |
81
94
  | [What gets recorded](https://github.com/zebraengine/wallmonitor/blob/main/docs/recording.md) | Recording fidelity, sessions, events, alert/EVSE label verification, resilience |
82
95
  | [Thermal model](https://github.com/zebraengine/wallmonitor/blob/main/docs/thermal-model.md) | The derate forecast and the degradation watch, in full detail |
83
96
  | [Amp control](https://github.com/zebraengine/wallmonitor/blob/main/docs/amp-control.md) | Automatic derate prevention over BLE: design, guards, backtesting |
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "wallmonitor"
3
- version = "0.3.0"
3
+ version = "0.4.0"
4
4
  description = "Local-only monitoring and recording UI for a Tesla Wall Connector Gen 3"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "wallmonitor"
3
- version = "0.3.0"
3
+ version = "0.4.0"
4
4
  description = "Local-only monitoring and recording UI for a Tesla Wall Connector Gen 3"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -30,10 +30,13 @@ from .web import make_app
30
30
  log = logging.getLogger("wallmonitor")
31
31
 
32
32
 
33
- async def _backfill(db: Database) -> None:
34
- """One-time, in the background: fill diagnostics columns for rows
35
- recorded before those columns existed. Chunked, so live polling only
36
- ever waits a moment; a settings flag makes later startups a no-op."""
33
+ async def _maintenance(db: Database, cfg) -> None:
34
+ """Background housekeeping: the one-time diagnostics backfill, then —
35
+ when retention is enabled — a daily raw-JSON trim of samples older
36
+ than the retention window. Chunked throughout, so live polling only
37
+ ever waits a moment."""
38
+ import time as _time
39
+
37
40
  def report(done: int, total: int) -> None:
38
41
  if done % 200_000 < 10_000 or done >= total:
39
42
  log.info("diagnostics backfill: %d / %d rows", done, total)
@@ -41,6 +44,16 @@ async def _backfill(db: Database) -> None:
41
44
  touched = await asyncio.to_thread(db.backfill_diag_columns, 10_000, report)
42
45
  if touched:
43
46
  log.info("diagnostics backfill complete: %d rows", touched)
47
+ if not cfg.retain_raw_days:
48
+ return
49
+ while True:
50
+ cutoff = _time.time() - cfg.retain_raw_days * 86400.0
51
+ counts = await asyncio.to_thread(db.trim_raw, cutoff)
52
+ total = sum(counts.values())
53
+ if total:
54
+ log.info("retention: trimmed raw JSON from %d rows (%s)", total,
55
+ ", ".join(f"{k}={v}" for k, v in counts.items() if v))
56
+ await asyncio.sleep(24 * 3600.0)
44
57
 
45
58
 
46
59
  async def run(argv: list[str] | None = None) -> None:
@@ -52,6 +65,15 @@ async def run(argv: list[str] | None = None) -> None:
52
65
  cfg = parse_args(argv)
53
66
  if cfg.discover is not None:
54
67
  raise SystemExit(await run_discovery(cfg.discover, split_phase_hint=cfg.split_phase))
68
+ if cfg.compact:
69
+ db = Database(cfg.db_path)
70
+ try:
71
+ before, after = db.vacuum()
72
+ finally:
73
+ db.close()
74
+ print(f"{cfg.db_path}: {before / 1e6:.1f} MB -> {after / 1e6:.1f} MB "
75
+ f"({(before - after) / 1e6:.1f} MB reclaimed)")
76
+ raise SystemExit(0)
55
77
  logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(levelname)s %(message)s")
56
78
 
57
79
  sim_runner = None
@@ -65,7 +87,7 @@ async def run(argv: list[str] | None = None) -> None:
65
87
  client = aiohttp.ClientSession()
66
88
  poller = Poller(cfg, db, bus, client)
67
89
  await poller.start()
68
- backfill = asyncio.create_task(_backfill(db), name="wallmonitor-backfill")
90
+ backfill = asyncio.create_task(_maintenance(db, cfg), name="wallmonitor-maintenance")
69
91
 
70
92
  app = make_app(db, bus, poller)
71
93
  runner = web.AppRunner(app)
@@ -33,6 +33,12 @@ class Config:
33
33
  # Human name for this charger, shown in the UI header, tab title and
34
34
  # notifications so several instances side by side stay attributable.
35
35
  label: str = ""
36
+ # Optional retention: rows older than this many days keep every extracted
37
+ # column forever but have their raw JSON blob trimmed to "". 0 = never
38
+ # trim (the default — full re-interpretability retained indefinitely).
39
+ retain_raw_days: float = 0.0
40
+ # One-shot: VACUUM the database to reclaim trimmed space, print sizes, exit.
41
+ compact: bool = False
36
42
  # Sibling instances watching other chargers, as (label, url) pairs;
37
43
  # rendered as a switcher in the header so one browser hops between them.
38
44
  peers: tuple[tuple[str, str], ...] = ()
@@ -149,6 +155,20 @@ def parse_args(argv: list[str] | None = None) -> Config:
149
155
  help="Name for this charger, shown in the UI and notifications — useful when "
150
156
  "running one instance per Wall Connector (env: WM_LABEL)",
151
157
  )
158
+ parser.add_argument(
159
+ "--retain-raw-days",
160
+ type=float,
161
+ default=_env("WM_RETAIN_RAW_DAYS", 0.0),
162
+ help="Trim the raw JSON blob from samples older than this many days (columns are "
163
+ "kept forever; 0 disables — the default). Minimum 7. (env: WM_RETAIN_RAW_DAYS)",
164
+ )
165
+ parser.add_argument(
166
+ "--compact",
167
+ action="store_true",
168
+ default=False,
169
+ help="VACUUM the database to reclaim space freed by retention, print sizes, and exit. "
170
+ "Run it while the monitor service is stopped.",
171
+ )
152
172
  parser.add_argument(
153
173
  "--peer",
154
174
  action="append",
@@ -195,7 +215,10 @@ def parse_args(argv: list[str] | None = None) -> Config:
195
215
  except ValueError as ex:
196
216
  parser.error(str(ex))
197
217
 
198
- if not args.demo and not args.host and args.discover is None:
218
+ if args.retain_raw_days and args.retain_raw_days < 7:
219
+ parser.error("--retain-raw-days must be at least 7 (or 0 to disable)")
220
+
221
+ if not args.demo and not args.host and args.discover is None and not args.compact:
199
222
  parser.error(
200
223
  "--host (or WM_WC_HOST) is required — run `wallmonitor --discover` to find "
201
224
  "your Wall Connector's address, or --demo for the built-in simulator"
@@ -209,6 +232,8 @@ def parse_args(argv: list[str] | None = None) -> Config:
209
232
  demo=bool(args.demo),
210
233
  split_phase=bool(args.split_phase),
211
234
  label=args.label,
235
+ retain_raw_days=float(args.retain_raw_days),
236
+ compact=bool(args.compact),
212
237
  peers=peers,
213
238
  discover=args.discover,
214
239
  notify_url=args.notify_url,
@@ -221,6 +221,7 @@ class Database:
221
221
  telemetry). The schema is pure CREATE IF NOT EXISTS, re-run on
222
222
  every startup: "migrations" are additive statements appended here.
223
223
  """
224
+ self.path = path
224
225
  self._conn = sqlite3.connect(path, check_same_thread=False)
225
226
  self._conn.row_factory = sqlite3.Row
226
227
  self._lock = threading.Lock()
@@ -245,6 +246,73 @@ class Database:
245
246
  self._conn.execute(f"ALTER TABLE vitals_samples ADD COLUMN {col} REAL")
246
247
  self._conn.commit()
247
248
 
249
+ # Tables whose raw JSON blob is trimmed by the retention policy. The
250
+ # extracted columns stay forever; forecast_samples and version_info are
251
+ # exempt (tiny, and their raw payloads carry fields with no column).
252
+ RAW_TRIM_TABLES = ("vitals_samples", "wifi_samples", "lifetime_samples", "ambient_samples")
253
+
254
+ def trim_raw(self, cutoff_ts: float, chunk: int = 10_000) -> dict[str, int]:
255
+ """Retention: blank the raw JSON on samples older than cutoff_ts.
256
+
257
+ Columns are untouched, so charts, fits and the degradation watch see
258
+ exactly the same history — what is given up is re-interpreting old
259
+ rows for fields that were never extracted. Vitals are only trimmed
260
+ once the diagnostics backfill has finished (its json_extract source
261
+ is the raw blob). A per-table timestamp cursor in settings makes the
262
+ daily run scan only rows that newly aged past the cutoff, and the
263
+ chunked updates hold the write lock briefly each. Freed pages are
264
+ reused by new inserts, so the file stops growing; a one-shot VACUUM
265
+ (--compact) reclaims the space for the filesystem.
266
+ """
267
+ counts: dict[str, int] = {}
268
+ for table in self.RAW_TRIM_TABLES:
269
+ if table == "vitals_samples" and self.get_setting(DIAG_BACKFILL_SETTING) != "1":
270
+ continue
271
+ cursor_key = f"raw_trim_ts:{table}"
272
+ start_ts = float(self.get_setting(cursor_key) or 0.0)
273
+ trimmed = 0
274
+ while True:
275
+ with self._lock:
276
+ rows = self._conn.execute(
277
+ f"SELECT id, ts FROM {table} WHERE ts >= ? AND ts < ? "
278
+ "ORDER BY ts LIMIT ?",
279
+ (start_ts, cutoff_ts, chunk),
280
+ ).fetchall()
281
+ if not rows:
282
+ break
283
+ ids = [row[0] for row in rows]
284
+ placeholders = ",".join("?" for _ in ids)
285
+ cur = self._execute(
286
+ f"UPDATE {table} SET raw = '' WHERE id IN ({placeholders}) AND raw != ''",
287
+ tuple(ids),
288
+ )
289
+ trimmed += cur.rowcount
290
+ start_ts = rows[-1][1]
291
+ self._execute(
292
+ "INSERT INTO settings(key, value) VALUES (?, ?) "
293
+ "ON CONFLICT(key) DO UPDATE SET value = excluded.value",
294
+ (cursor_key, repr(start_ts)),
295
+ )
296
+ if len(rows) < chunk:
297
+ break
298
+ counts[table] = trimmed
299
+ return counts
300
+
301
+ def vacuum(self) -> tuple[int, int]:
302
+ """VACUUM, returning (bytes_before, bytes_after). Exclusive — run
303
+ while nothing else is writing (the --compact command exists so this
304
+ never happens implicitly under a live poller)."""
305
+ import os
306
+
307
+ with self._lock:
308
+ self._conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
309
+ before = os.path.getsize(self.path)
310
+ with self._lock:
311
+ self._conn.execute("VACUUM")
312
+ self._conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
313
+ after = os.path.getsize(self.path)
314
+ return before, after
315
+
248
316
  def backfill_diag_columns(self, chunk: int = 10_000, progress=None) -> int:
249
317
  """Fill the diagnostics columns for rows recorded before they
250
318
  existed, from each row's raw JSON, in id-ordered chunks so the
@@ -274,7 +342,7 @@ class Database:
274
342
  relay_k1_v = COALESCE(json_extract(raw, '$.relay_k1_v'),
275
343
  json_extract(raw, '$.relay_coil_v')),
276
344
  relay_k2_v = json_extract(raw, '$.relay_k2_v')
277
- WHERE id > ? AND id <= ? AND prox_v IS NULL""",
345
+ WHERE id > ? AND id <= ? AND prox_v IS NULL AND raw != ''""",
278
346
  (last, upto),
279
347
  )
280
348
  touched += cur.rowcount
@@ -617,13 +685,18 @@ class Database:
617
685
  if self._diag_backfilled:
618
686
  d = {col: col for col in VITALS_LATER_COLUMNS}
619
687
  else:
688
+ # CASE-guarded: a retention-trimmed row has raw = '' and
689
+ # json_extract('') is a hard error, not NULL — and SQLite does
690
+ # not promise to short-circuit COALESCE past it even when the
691
+ # column is populated.
692
+ j = "CASE WHEN raw = '' THEN NULL ELSE json_extract(raw, '{key}') END"
620
693
  d = {
621
- "pilot_high_v": "COALESCE(pilot_high_v, json_extract(raw, '$.pilot_high_v'))",
622
- "pilot_low_v": "COALESCE(pilot_low_v, json_extract(raw, '$.pilot_low_v'))",
623
- "prox_v": "COALESCE(prox_v, json_extract(raw, '$.prox_v'))",
624
- "relay_k1_v": "COALESCE(relay_k1_v, json_extract(raw, '$.relay_k1_v'), "
625
- "json_extract(raw, '$.relay_coil_v'))",
626
- "relay_k2_v": "COALESCE(relay_k2_v, json_extract(raw, '$.relay_k2_v'))",
694
+ "pilot_high_v": f"COALESCE(pilot_high_v, {j.format(key='$.pilot_high_v')})",
695
+ "pilot_low_v": f"COALESCE(pilot_low_v, {j.format(key='$.pilot_low_v')})",
696
+ "prox_v": f"COALESCE(prox_v, {j.format(key='$.prox_v')})",
697
+ "relay_k1_v": f"COALESCE(relay_k1_v, {j.format(key='$.relay_k1_v')}, "
698
+ f"{j.format(key='$.relay_coil_v')})",
699
+ "relay_k2_v": f"COALESCE(relay_k2_v, {j.format(key='$.relay_k2_v')})",
627
700
  }
628
701
  diag = ", ".join(f"{expr} AS {col}" for col, expr in d.items())
629
702
  if sample_count <= max_points:
@@ -125,6 +125,7 @@ class Poller:
125
125
  # Thermal params for the in-poller derate forecast: fitted lazily,
126
126
  # refreshed whenever a session closes (the only time fits change).
127
127
  self._params: thermal.ThermalParams | None = None
128
+ self._drift_lead_active = False # latch: push a lead once per episode, not per session
128
129
  self._next_forecast_ts = 0.0
129
130
  self._derate_active = False
130
131
  self._alert_labels: dict | None = None
@@ -514,32 +515,50 @@ class Poller:
514
515
  # No verdict — the comparable history got too thin (sessions aged
515
516
  # out of the lookback, or off-current sessions were set aside). An
516
517
  # active alert can no longer be justified either, so let it clear.
518
+ self._drift_lead_active = False
517
519
  cleared = await asyncio.to_thread(self.db.clear_alert, ts, thermal.DRIFT_ALERT, "monitor")
518
520
  if cleared:
519
521
  await self._event(ts, "thermal_drift_cleared", {"reason": "insufficient_history"})
520
522
  return
523
+ ci_lo, ci_hi = drift["delta_ci95_c"]
524
+ body = (
525
+ f"Recent sessions run +{drift['recent_rise_c']:.1f} °C vs a +{drift['baseline_rise_c']:.1f} °C "
526
+ f"baseline at the same current (Δ {drift['delta_c']:.1f} °C, 95% CI {ci_lo:.1f}..{ci_hi:.1f}, "
527
+ f"n={drift['baseline_n']}+{drift['recent_n']}"
528
+ )
521
529
  if drift["drifting"]:
530
+ # Confirmed: the interval clears zero and the delta is material.
531
+ self._drift_lead_active = False
522
532
  _, newly = await asyncio.to_thread(self.db.raise_alert, ts, thermal.DRIFT_ALERT, "monitor")
523
533
  if newly:
524
534
  await self._event(ts, "thermal_drift", drift)
525
- ci_lo, ci_hi = drift["delta_ci95_c"]
526
- sureness = (
527
- "statistically confirmed"
528
- if drift["confident"]
529
- else f"not yet confirmed at n={drift['baseline_n']}+{drift['recent_n']} — treat as a lead"
530
- )
531
535
  await self._notify(
532
536
  "thermal_drift",
533
537
  "Heat rise climbing vs baseline",
534
- f"Recent sessions run +{drift['recent_rise_c']:.1f} °C vs a +{drift['baseline_rise_c']:.1f} °C "
535
- f"baseline at the same current (Δ {drift['delta_c']:.1f} °C, 95% CI {ci_lo:.1f}..{ci_hi:.1f}, "
536
- f"{sureness}) — inspect the handle and charge-port pins, and have the terminal torque checked.",
538
+ body + ", statistically confirmed) — inspect the handle and charge-port pins, "
539
+ "and have the terminal torque checked.",
540
+ drift,
541
+ )
542
+ return
543
+ # Not confirmed: whatever alert was latched can no longer be justified.
544
+ cleared = await asyncio.to_thread(self.db.clear_alert, ts, thermal.DRIFT_ALERT, "monitor")
545
+ if cleared:
546
+ await self._event(ts, "thermal_drift_cleared", drift)
547
+ if drift["lead"]:
548
+ # Past the floor but inside this install's own scatter: a lead
549
+ # for the dashboard and a quiet push, once per episode — no alert.
550
+ if not self._drift_lead_active:
551
+ self._drift_lead_active = True
552
+ await self._event(ts, "thermal_drift_lead", drift)
553
+ await self._notify(
554
+ "thermal_drift_lead",
555
+ "Heat rise may be climbing — a lead, not yet confirmed",
556
+ body + f"; needs Δ ≥ {drift['threshold_c']:.1f} °C at this install's scatter to confirm) "
557
+ "— worth a look at the handle and pins next time you're there; more sessions will settle it.",
537
558
  drift,
538
559
  )
539
560
  else:
540
- cleared = await asyncio.to_thread(self.db.clear_alert, ts, thermal.DRIFT_ALERT, "monitor")
541
- if cleared:
542
- await self._event(ts, "thermal_drift_cleared", drift)
561
+ self._drift_lead_active = False
543
562
 
544
563
  async def _check_derate_forecast(self, ts: float, raw: dict) -> None:
545
564
  """While charging: warn while the user can still act — a capped
@@ -627,13 +646,15 @@ class Poller:
627
646
  NTFY_PRIORITY = {
628
647
  "derate_warning": "urgent", # actionable *now* — lower the amps
629
648
  "alert_raised": "high",
630
- "thermal_drift": "high",
649
+ "thermal_drift": "high", # confidence interval clears zero
650
+ "thermal_drift_lead": "default", # tripwire only — a lead, not a conviction
631
651
  "poll_error": "default",
632
652
  }
633
653
  NTFY_TAGS = {
634
654
  "derate_warning": "zap,warning",
635
655
  "alert_raised": "rotating_light",
636
656
  "thermal_drift": "wrench",
657
+ "thermal_drift_lead": "wrench,mag",
637
658
  "poll_error": "electric_plug,x",
638
659
  }
639
660
 
@@ -689,6 +710,7 @@ class Poller:
689
710
  "host": self.cfg.host,
690
711
  "label": self.cfg.label,
691
712
  "peers": [{"label": label, "url": url} for label, url in self.cfg.peers],
713
+ "retain_raw_days": self.cfg.retain_raw_days,
692
714
  "device_serial": self.device_serial,
693
715
  "serial_mismatch": self.serial_mismatch,
694
716
  "offline": self._offline,
@@ -1085,7 +1085,14 @@ async function viewLive(root) {
1085
1085
  // same current means added resistance somewhere in the current path.
1086
1086
  const drift = data.drift;
1087
1087
  let driftLine = null;
1088
- if (drift && drift.drifting) {
1088
+ if (drift && drift.lead) {
1089
+ driftLine = el("div", { class: "note" },
1090
+ chipFor("warning", "heat rise: lead"),
1091
+ ` Recent sessions average +${fmtNum(drift.recent_rise_c, 1)} °C at ${fmtNum(model.ref_current_a, 0)} A vs a ` +
1092
+ `+${fmtNum(drift.baseline_rise_c, 1)} °C baseline (Δ ${fmtNum(drift.delta_c, 1)} °C) — past the ` +
1093
+ `${fmtNum(drift.floor_c, 1)} °C floor but within this install's session-to-session scatter, which needs ` +
1094
+ `Δ ≥ ${fmtNum(drift.threshold_c, 1)} °C to confirm. Not an alert; worth a look at the handle and pins.`);
1095
+ } else if (drift && drift.drifting) {
1089
1096
  driftLine = el("div", { class: "note" },
1090
1097
  chipFor("serious", "heat rise increasing"),
1091
1098
  ` Recent sessions average +${fmtNum(drift.recent_rise_c, 1)} °C at ${fmtNum(model.ref_current_a, 0)} A vs a ` +
@@ -1094,10 +1101,27 @@ async function viewLive(root) {
1094
1101
  (drift.off_current_n ? ` (${drift.off_current_n} session${drift.off_current_n === 1 ? "" : "s"} away from the usual ` +
1095
1102
  `~${fmtNum(drift.typical_current_a, 0)} A excluded from the comparison.)` : ""));
1096
1103
  }
1104
+ // The defaults come from one verified install. Once this install has
1105
+ // fits of its own, say plainly when they landed far from those priors:
1106
+ // the forecast before the first fit was governed by numbers that did
1107
+ // not describe this charger, and a fast tau has a standing cost — the
1108
+ // fitter's identifiability gate is floored at the default tau, so short
1109
+ // charges on such an install never teach the model.
1110
+ const dev = model.prior_deviation;
1111
+ let priorNote = "";
1112
+ if (model.fitted && dev && dev.notable) {
1113
+ const parts = [];
1114
+ if (Math.abs(dev.tau_frac) > 0.3) parts.push(`τ ${fmtNum(model.tau_min, 1)} min vs the ${fmtNum(dev.default_tau_min, 0)} min default`);
1115
+ if (Math.abs(dev.rise_frac) > 0.3) parts.push(`rise +${fmtNum(model.rise_ref_c, 0)} °C vs the +${fmtNum(dev.default_rise_ref_c, 0)} °C default`);
1116
+ priorNote = ` This install differs from the built-in priors (${parts.join("; ")}) — forecasts before its first ` +
1117
+ `fitted session were rough` +
1118
+ (dev.tau_frac < -0.3 ? `, and with a τ this fast only charges of ≥ ${fmtNum(1.8 * dev.default_tau_min, 0)} min ` +
1119
+ "at steady current teach the model." : ".");
1120
+ }
1097
1121
  const modelNote = `Model: τ ≈ ${fmtNum(model.tau_min, 1)} min, +${fmtNum(model.rise_ref_c, 0)} °C at ${fmtNum(model.ref_current_a, 0)} A — ` +
1098
- (model.fitted ? `fitted from ${model.tau_fits} recorded session ramp${model.tau_fits === 1 ? "" : "s"}.`
1099
- : "defaults from the verified alert-40 event; refits automatically as sessions accumulate.") +
1100
- (drift && !drift.drifting ? ` Heat rise stable across the last ${drift.recent_n + drift.baseline_n} fitted sessions` +
1122
+ (model.fitted ? `fitted from ${model.tau_fits} recorded session ramp${model.tau_fits === 1 ? "" : "s"}.` + priorNote
1123
+ : "defaults from one verified install, used until this charger has fits of its own; refits automatically as sessions accumulate.") +
1124
+ (drift && !drift.drifting && !drift.lead ? ` Heat rise stable across the last ${drift.recent_n + drift.baseline_n} fitted sessions` +
1101
1125
  `${drift.off_current_n ? ` (${drift.off_current_n} off-current session${drift.off_current_n === 1 ? "" : "s"} excluded)` : ""}.` : "");
1102
1126
  thermalCard.append(el("div", { class: "chart-card" },
1103
1127
  el("div", { class: "chart-title" }, "Thermal derate forecast", chip ? " " : null, chip),
@@ -1709,17 +1733,25 @@ async function viewAlerts(root, rangeKey = "7d") {
1709
1733
  // fits is a lead, not a conviction, and the note must show which.
1710
1734
  const [ciLo, ciHi] = drift.delta_ci95_c || [null, null];
1711
1735
  const sureness = ciLo == null ? "" :
1712
- ` · 95% CI ${fmtNum(ciLo, 1)}..${fmtNum(ciHi, 1)} °C from n=${drift.baseline_n}+${drift.recent_n}` +
1713
- (drift.confident ? "" : " — not yet statistically confirmed; more sessions will tighten this");
1736
+ ` · 95% CI ${fmtNum(ciLo, 1)}..${fmtNum(ciHi, 1)} °C from n=${drift.baseline_n}+${drift.recent_n}`;
1714
1737
  const pooled = drift.cross_current_n
1715
1738
  ? ` (${drift.cross_current_n} ambient-bracketed fit${drift.cross_current_n > 1 ? "s" : ""} pooled from other charge currents)`
1716
1739
  : "";
1740
+ // The alert threshold is the larger of the materiality floor and
1741
+ // what this install's own scatter needs to clear zero — so the same
1742
+ // delta is an alert on a quiet install and a lead on a noisy one.
1743
+ const thresholdNote = `alert threshold Δ ≥ ${fmtNum(drift.threshold_c, 1)} °C` +
1744
+ (drift.threshold_c > drift.floor_c + 0.05
1745
+ ? ` (the ${fmtNum(drift.floor_c, 1)} °C floor, raised to what this install's scatter needs to confirm)`
1746
+ : ` (the ${fmtNum(drift.floor_c, 1)} °C floor)`);
1747
+ const summary = `recent median +${fmtNum(drift.recent_rise_c, 1)} °C vs baseline +${fmtNum(drift.baseline_rise_c, 1)} °C`;
1717
1748
  rise.card.append(el("div", { class: "note" },
1718
1749
  (drift.drifting
1719
- ? `Recent median +${fmtNum(drift.recent_rise_c, 1)} °C vs baseline +${fmtNum(drift.baseline_rise_c, 1)} °C ` +
1720
- `(Δ ${fmtNum(drift.delta_c, 1)} °C ≥ ${fmtNum(drift.threshold_c, 1)} °C threshold) — a monitor alert is active`
1721
- : `Stable: recent median +${fmtNum(drift.recent_rise_c, 1)} °C vs baseline +${fmtNum(drift.baseline_rise_c, 1)} °C ` +
1722
- `(alert threshold Δ ≥ ${fmtNum(drift.threshold_c, 1)} °C)`) + sureness + pooled + "."));
1750
+ ? `Confirmed: ${summary} (Δ ${fmtNum(drift.delta_c, 1)} °C; ${thresholdNote}) — a monitor alert is active`
1751
+ : drift.lead
1752
+ ? `Lead: ${summary} (Δ ${fmtNum(drift.delta_c, 1)} °C, past the floor but not yet confirmed; ${thresholdNote}) — ` +
1753
+ "no alert; more sessions will settle it"
1754
+ : `Stable: ${summary} (${thresholdNote})`) + sureness + pooled + "."));
1723
1755
  }
1724
1756
  // Ambient bracketing: fits that read ambient at both ends of the load
1725
1757
  // window are de-trended for weather that moved during the charge — the
@@ -105,6 +105,20 @@ MIN_RISE_SEEN_C = 4.0
105
105
  MAX_FIT_RMSE_C = 0.6
106
106
  TAU_RANGE_MIN = (3.0, 40.0)
107
107
  RISE_RANGE_C = (10.0, 80.0)
108
+ # The steady-current window must be long against the install's time
109
+ # constant, or rise and tau are not separately identifiable: a window that
110
+ # ends before the plateau shows lets the fitter trade a lower rise for a
111
+ # faster tau and pass every other gate with a fine RMSE. Judged against the
112
+ # install's median tau (not this fit's own, which is exactly the biased
113
+ # quantity), so a truncated segment can't vouch for itself — and floored at
114
+ # DEFAULT_TAU_MIN, so on a fresh install the very first fit is judged
115
+ # against a sane prior rather than its own possibly-truncated tau. At 1.8
116
+ # tau the handle has covered ~83% of its rise. The steady-prefix window
117
+ # scales with the same tau estimate (PREFIX_SPAN_TAU) so a slow-tau install
118
+ # is not starved of fits by a fixed cap it can never clear.
119
+ MIN_SPAN_TAU = 1.8
120
+ PREFIX_SPAN_TAU = 2.5
121
+ PREFIX_SPAN_MIN_S = 1800.0
108
122
 
109
123
  # Live-forecast gate: a steady-current window must hold this many samples
110
124
  # over this much time before its trajectory is projected.
@@ -139,6 +153,32 @@ class ThermalParams:
139
153
  def fitted(self) -> bool:
140
154
  return self.tau_fits > 0 and self.rise_fits > 0
141
155
 
156
+ # How far a fitted value may sit from the default before the dashboard
157
+ # says the priors were a poor fit for this install. A heuristic, not a
158
+ # statistic: 30% is roughly where the default-driven forecast's plateau
159
+ # error exceeds the fit's own noise and early-session predictions were
160
+ # materially off.
161
+ PRIOR_DEVIATION_FRAC = 0.30
162
+
163
+ def prior_deviation(self) -> dict | None:
164
+ """How this install's fitted tau and rise compare to the defaults
165
+ that governed the forecast before its first fit landed — None until
166
+ fitted. The frontend renders it as an honesty note: the priors are
167
+ from one verified install, and a user whose charger differs should
168
+ know that early forecasts were rough and (for a fast tau) that short
169
+ charges no longer teach the model."""
170
+ if not self.fitted:
171
+ return None
172
+ tau_frac = self.tau_min / DEFAULT_TAU_MIN - 1.0
173
+ rise_frac = self.rise_ref_c / DEFAULT_RISE_REF_C - 1.0
174
+ return {
175
+ "default_tau_min": DEFAULT_TAU_MIN,
176
+ "default_rise_ref_c": DEFAULT_RISE_REF_C,
177
+ "tau_frac": round(tau_frac, 3),
178
+ "rise_frac": round(rise_frac, 3),
179
+ "notable": max(abs(tau_frac), abs(rise_frac)) > self.PRIOR_DEVIATION_FRAC,
180
+ }
181
+
142
182
  def as_dict(self) -> dict:
143
183
  """The `model` object served by /api/thermal and the SSE thermal
144
184
  frame — fitted values plus the fixed thresholds."""
@@ -154,6 +194,7 @@ class ThermalParams:
154
194
  "rise_fits": self.rise_fits,
155
195
  "fit_rmse_c": round(self.fit_rmse_c, 3) if self.fit_rmse_c is not None else None,
156
196
  "fitted": self.fitted,
197
+ "prior_deviation": self.prior_deviation(),
157
198
  }
158
199
 
159
200
 
@@ -185,8 +226,8 @@ def _fit_exponential(points: list[tuple[float, float]]) -> tuple[float, float, f
185
226
  return best
186
227
 
187
228
 
188
- def _steady_current_prefix(samples: list[dict]) -> list[dict]:
189
- """The session's first steady-current run.
229
+ def _steady_current_prefix(samples: list[dict], max_span_s: float = PREFIX_SPAN_MIN_S) -> list[dict]:
230
+ """The session's first steady-current run, capped at max_span_s.
190
231
 
191
232
  The reference current is the median of the first 10 minutes of charging,
192
233
  not of the whole session: a session that derates midway spends most of
@@ -218,7 +259,7 @@ def _steady_current_prefix(samples: list[dict]) -> list[dict]:
218
259
  break # the steady run ended (derate or charge stop)
219
260
  continue # still ramping up to the plateau
220
261
  prefix.append(sample)
221
- if sample["ts"] - prefix[0]["ts"] > 1800: # first 30 min is where the ramp lives
262
+ if sample["ts"] - prefix[0]["ts"] > max_span_s: # the ramp lives in the first few tau
222
263
  break
223
264
  return prefix
224
265
 
@@ -454,26 +495,47 @@ def fit_sessions(db: Database, now: float, lookback_days: float = 120.0) -> list
454
495
  segments = _segments(coarse)[:MAX_SEGMENTS_PER_SESSION]
455
496
  for idx, (seg_start, seg_end) in enumerate(segments):
456
497
  next_start = segments[idx + 1][0] if idx + 1 < len(segments) else sess["end_ts"] + 1
457
- t_hi = min(sess["end_ts"], seg_start + 2700, next_start - 1)
458
- samples = db.vitals_range(seg_start - 1, t_hi + 1, 5000)
459
- prefix = _steady_current_prefix(samples)
460
- seg = [
461
- (sample["ts"], sample["handle_temp_c"])
462
- for sample in prefix
463
- if sample.get("handle_temp_c") is not None
464
- ]
465
- if len(seg) < MIN_SEGMENT_SAMPLES or seg[-1][0] - seg[0][0] < MIN_SEGMENT_S:
466
- continue
467
- if max(temp for _, temp in seg) - seg[0][1] < MIN_RISE_SEEN_C:
468
- continue
469
- fit = _fit_exponential(seg)
470
- if fit is None:
498
+ # The install's tau so far (the default until fits exist) sizes
499
+ # the window: a fixed cap that suits an 11 min tau would leave
500
+ # a 20 min tau install unable to clear the identifiability gate.
501
+ tau_prior = median(fit["tau_min"] for fit in fits) if fits else DEFAULT_TAU_MIN
502
+ fit = None
503
+ for _pass in range(2):
504
+ fit = None
505
+ span_cap_s = max(PREFIX_SPAN_MIN_S, PREFIX_SPAN_TAU * tau_prior * 60.0)
506
+ t_hi = min(sess["end_ts"], seg_start + span_cap_s + 900, next_start - 1)
507
+ samples = db.vitals_range(seg_start - 1, t_hi + 1, 5000)
508
+ prefix = _steady_current_prefix(samples, span_cap_s)
509
+ seg = [
510
+ (sample["ts"], sample["handle_temp_c"])
511
+ for sample in prefix
512
+ if sample.get("handle_temp_c") is not None
513
+ ]
514
+ if len(seg) < MIN_SEGMENT_SAMPLES or seg[-1][0] - seg[0][0] < MIN_SEGMENT_S:
515
+ break
516
+ if max(temp for _, temp in seg) - seg[0][1] < MIN_RISE_SEEN_C:
517
+ break
518
+ fit = _fit_exponential(seg)
519
+ if fit is None:
520
+ break
521
+ # The window was sized from the tau prior. If this segment
522
+ # fits slower than that, the prior under-sized it: widen to
523
+ # the fitted tau and refit once, so a slow-tau install (or
524
+ # the first fit on a fresh one) isn't stuck behind a window
525
+ # it can never clear.
526
+ slower = fit[0] / 60.0 > tau_prior * 1.1
527
+ if not slower or prefix[-1]["ts"] - prefix[0]["ts"] < span_cap_s - 60:
528
+ break # window is tau-sized, or the run ended on its own
529
+ tau_prior = fit[0] / 60.0
530
+ if fit is None or len(seg) < MIN_SEGMENT_SAMPLES:
471
531
  continue
472
532
  tau_s, t_inf, rmse = fit
473
533
  if rmse > MAX_FIT_RMSE_C or t_inf <= seg[0][1] + 3.0:
474
534
  continue
475
535
  i_med = median(sample["vehicle_current_a"] for sample in prefix)
476
536
  tau_est = median([tau_s / 60.0] + [fit["tau_min"] for fit in fits])
537
+ if seg[-1][0] - seg[0][0] < MIN_SPAN_TAU * max(tau_est, DEFAULT_TAU_MIN) * 60.0:
538
+ continue # plateau never observed: rise/tau not identifiable
477
539
  measured = _measured_ambient(db, seg_start - MEASURED_AMBIENT_WINDOW_S, seg_start + 60)
478
540
  ambient, ambient_source = measured if measured is not None else (None, None)
479
541
  if ambient is None:
@@ -568,7 +630,7 @@ def fit_history(db: Database, now: float, lookback_days: float = 120.0,
568
630
  # earlier baseline and flags a sustained increase.
569
631
  DRIFT_RECENT_N = 3
570
632
  DRIFT_MIN_BASELINE_N = 3
571
- DRIFT_WARN_C = 2.5
633
+ DRIFT_WARN_C = 2.5 # materiality floor, not the trigger — see detect_drift
572
634
  DRIFT_ALERT = "Handle heat rise increasing (check connector/wiring)"
573
635
 
574
636
  # Cross-current pooling: fits whose ambient was bracketed at both ends are
@@ -632,10 +694,16 @@ def detect_drift(fits: list[dict], anchor_ts: float | None = None) -> dict | Non
632
694
  from that moment, not "the first charges the monitor happened to see".
633
695
 
634
696
  The verdict carries its own uncertainty: MAD spread per side and a
635
- Student-t ~95% confidence interval on the delta. "drifting" stays a
636
- plain threshold tripwire; "confident" says whether the interval clears
637
- zero — a Δ from a four-fit baseline is a lead, not a conviction, and the
638
- UI should show the difference.
697
+ Student-t ~95% confidence interval on the delta. "drifting" — the alert
698
+ — needs both: the interval clears zero ("confident") *and* the delta is
699
+ material (>= DRIFT_WARN_C, the floor below which a real increase isn't
700
+ worth an inspection). A delta past the floor whose interval still
701
+ straddles zero is a "lead": shown, pushed quietly, but no alert. The
702
+ effective threshold ("threshold_c") is therefore the larger of the floor
703
+ and what this install's own scatter requires, so a noisy install must
704
+ show more before the watch alarms and a quiet one less — the fixed
705
+ 2.5 °C tripwire sat near one sigma on a real install and fired on
706
+ scatter.
639
707
  """
640
708
  usable = [fit for fit in fits if fit["rise_ref_c"] is not None]
641
709
  if anchor_ts is not None:
@@ -667,10 +735,14 @@ def detect_drift(fits: list[dict], anchor_ts: float | None = None) -> dict | Non
667
735
  delta_se = math.sqrt(recent_se**2 + baseline_se**2)
668
736
  t_mult = _T95.get(len(recent) + len(baseline) - 2, 2.0)
669
737
  ci_lo, ci_hi = delta - t_mult * delta_se, delta + t_mult * delta_se
738
+ confident = ci_lo > 0.0
739
+ threshold = max(DRIFT_WARN_C, t_mult * delta_se)
740
+ drifting = confident and delta >= DRIFT_WARN_C
670
741
  cross_current = sum(1 for fit in comparable if abs(fit["current_a"] - typical_a) > band)
671
742
  return {
672
- "drifting": delta >= DRIFT_WARN_C,
673
- "confident": ci_lo > 0.0,
743
+ "drifting": drifting,
744
+ "lead": delta >= DRIFT_WARN_C and not drifting,
745
+ "confident": confident,
674
746
  "recent_rise_c": round(recent_med, 2),
675
747
  "baseline_rise_c": round(baseline_med, 2),
676
748
  "delta_c": round(delta, 2),
@@ -683,7 +755,8 @@ def detect_drift(fits: list[dict], anchor_ts: float | None = None) -> dict | Non
683
755
  "off_current_n": len(usable) - len(comparable),
684
756
  "cross_current_n": cross_current,
685
757
  "anchor_ts": anchor_ts,
686
- "threshold_c": DRIFT_WARN_C,
758
+ "threshold_c": round(threshold, 2),
759
+ "floor_c": DRIFT_WARN_C,
687
760
  }
688
761
 
689
762
 
@@ -730,14 +803,25 @@ def suggest_max_current(ambient_c: float, params: ThermalParams) -> float | None
730
803
  return float(amps)
731
804
 
732
805
 
733
- def _project_t_inf(window: list[tuple[float, float]], tau_min: float) -> float:
734
- """Steady state projected from a steady-current window's trajectory.
806
+ def _project_t_inf(window: list[tuple[float, float]], tau_min: float) -> tuple[float, float | None]:
807
+ """Steady state projected from a steady-current window's trajectory,
808
+ with the standard error of that projection.
735
809
 
736
810
  With tau known, T(t) = T_inf - C*exp(-t/tau) is linear in (T_inf, C), so
737
811
  an ordinary least-squares line on x = exp(-t/tau) gives an unbiased T_inf
738
812
  (a straight-line slope would read the window's average rate and overshoot
739
813
  during a fast ramp). No ambient input needed. A flat window (variance ~0,
740
814
  i.e. already converged) reads as the latest temperature.
815
+
816
+ T_inf is the fitted line's intercept at decay = 0 (t -> infinity), so its
817
+ standard error comes from the OLS intercept formula:
818
+ SE = s * sqrt(1/n + mean_x^2 / Sxx) with s^2 = SSE / (n - 2). Early in a
819
+ window, before much curvature is visible, mean_x is near 1 and Sxx is
820
+ tiny — the extrapolation is honest about being wild; near the plateau
821
+ it tightens. That is the per-projection uncertainty the amp controller's
822
+ confidence guard wants (issue #4) — fit_rmse_c is a model-adequacy score
823
+ across historical sessions and carries none of this variation. SE is
824
+ None when it cannot be computed (flat window, n <= 2).
741
825
  """
742
826
  count = len(window)
743
827
  decays = [math.exp(-(ts - window[0][0]) / (tau_min * 60.0)) for ts, _ in window]
@@ -748,7 +832,18 @@ def _project_t_inf(window: list[tuple[float, float]], tau_min: float) -> float:
748
832
  (decay - mean_decay) * (temp - mean_temp)
749
833
  for decay, (_, temp) in zip(decays, window)
750
834
  )
751
- return mean_temp - (cov / var) * mean_decay if var > 1e-9 else window[-1][1]
835
+ if var <= 1e-9:
836
+ return window[-1][1], None
837
+ slope = cov / var
838
+ t_inf = mean_temp - slope * mean_decay
839
+ if count <= 2:
840
+ return t_inf, None
841
+ sse = sum(
842
+ (temp - (t_inf + slope * decay)) ** 2
843
+ for decay, (_, temp) in zip(decays, window)
844
+ )
845
+ se = math.sqrt(sse / (count - 2)) * math.sqrt(1.0 / count + mean_decay**2 / var)
846
+ return t_inf, se
752
847
 
753
848
 
754
849
  def _recent_steady_ambient(recent: list[dict], params: ThermalParams) -> float | None:
@@ -778,7 +873,7 @@ def _recent_steady_ambient(recent: list[dict], params: ThermalParams) -> float |
778
873
  if len(run) < TRAJECTORY_MIN_SAMPLES or run[-1]["ts"] - run[0]["ts"] < TRAJECTORY_MIN_SPAN_S:
779
874
  continue
780
875
  window = [(sample["ts"], sample["handle_temp_c"]) for sample in run]
781
- t_inf = _project_t_inf(window, params.tau_min)
876
+ t_inf, _se = _project_t_inf(window, params.tau_min)
782
877
  run_current = median(sample["vehicle_current_a"] for sample in run)
783
878
  ambient = t_inf - params.rise_ref_c * (run_current / REF_CURRENT_A) ** 2
784
879
  if -30.0 <= ambient <= TRIP_HANDLE_C:
@@ -828,8 +923,14 @@ def predict(db: Database, now: float, params: ThermalParams) -> dict:
828
923
  window.reverse()
829
924
  forecast: dict = {}
830
925
  if len(window) >= TRAJECTORY_MIN_SAMPLES and window[-1][0] - window[0][0] >= TRAJECTORY_MIN_SPAN_S:
831
- t_inf = _project_t_inf(window, tau_min)
926
+ t_inf, t_inf_se = _project_t_inf(window, tau_min)
832
927
  forecast["basis"] = "trajectory"
928
+ # This projection's own uncertainty — what the amp controller's
929
+ # confidence guard compares the margin against. Floored at the
930
+ # handle sensor's 0.1 C quantization: a perfectly smooth window
931
+ # can drive the raw SE below the sensor's resolution, and a
932
+ # guard fed that would claim more confidence than the data has.
933
+ forecast["steady_state_se_c"] = round(max(t_inf_se, 0.1), 2) if t_inf_se is not None else None
833
934
  else:
834
935
  # Too early at this current for a slope: model from ambient and
835
936
  # the present current scaled by I^2. Ambient comes from the LAN