From d0468f7380058e08913c1d66127cda20bb86ebc8 Mon Sep 17 00:00:00 2001 From: lollox80 <52501164+lollox80@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:46:00 +0100 Subject: [PATCH] enquire_archive daily: read each archive file once verbosity daily without a limit opened every archive file in the range on every call - 13 s for a month (about 6,900 files) on a Raspberry Pi class host. Archive files are written once and never changed, so the part the daily totals and the list filters need (created, outcome, priority, deliveries sent/failed, scenario names) is now kept in memory by file name; the next call opens only the files archived since. Names gone from the directory (purge_archive) drop out of the cache on the next scan. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Xb3AAHgGH8CosCCseNn4yt --- custom_components/supernotify/actions.py | 6 ++ custom_components/supernotify/archive.py | 65 +++++++++++-- docs/usage/actions.md | 4 +- .../supernotify/test_enquire_archive_daily.py | 92 +++++++++++++++++++ 4 files changed, 159 insertions(+), 8 deletions(-) diff --git a/custom_components/supernotify/actions.py b/custom_components/supernotify/actions.py index eb023f7f40..37e6f7ed84 100644 --- a/custom_components/supernotify/actions.py +++ b/custom_components/supernotify/actions.py @@ -441,6 +441,12 @@ def at_verbosity(contents: dict[str, Any]) -> dict[str, Any]: before: dt.datetime | None = dt_util.as_local(call.data["before"]) if "before" in call.data else None if after is None and period: after = dt_util.now() - ARCHIVE_PERIODS[period] + if daily and "limit" not in call.data: + # each file read once, then its daily record from memory: a month of archive in a moment + records = await archive.archive_directory.list_daily_records( + after=after, before=before, outcome=outcome, priority=priority + ) + return summarize_by_day(records) entries = await archive.archive_directory.list_entries( limit=limit, after=after, before=before, outcome=outcome, priority=priority ) diff --git a/custom_components/supernotify/archive.py b/custom_components/supernotify/archive.py index ec7682e16c..c2e0e2c095 100644 --- a/custom_components/supernotify/archive.py +++ b/custom_components/supernotify/archive.py @@ -5,6 +5,7 @@ import logging import math import os +import sys from abc import abstractmethod from typing import TYPE_CHECKING, Any @@ -77,6 +78,22 @@ def _filename_period(filename: str) -> tuple[float, float] | None: return min(stamps), max(stamps) + 60 +def _daily_record(data: dict[str, Any]) -> dict[str, Any]: + """The part of an archived notification that ``summarize_by_day`` and the list filters read: + a few hundred bytes instead of the whole file.""" + deliveries: dict[str, dict[str, bool]] = {} + for name, outcomes in (data.get("deliveries") or {}).items(): + if isinstance(outcomes, dict): + deliveries[name] = {"success": bool(outcomes.get("success")), "error": bool(outcomes.get("error"))} + return { + "created": data.get("created"), + "outcome": data.get("outcome"), + "priority": data.get("priority"), + "deliveries": deliveries, + "enabled_scenarios": _scenario_names(data.get("enabled_scenarios")), + } + + def _list_entries_sync( archive_path: str, limit: int, @@ -84,14 +101,23 @@ def _list_entries_sync( before: dt.datetime | None, outcome: str | None, priority: list[str] | None = None, + daily_cache: dict[str, dict[str, Any]] | None = None, ) -> list[dict[str, Any]]: - """The body of ``ArchiveDirectory.list_entries``, run in the executor as one job.""" + """The body of ``ArchiveDirectory.list_entries``, run in the executor as one job. + + With *daily_cache* the entries are daily records (``_daily_record``), kept in that cache by + file name: an archive file is written once and never changed, so only files not seen before + are opened. Names no longer in the directory (purged) are dropped from the cache.""" entries: list[dict[str, Any]] = [] priorities: set[str] | None = {str(p).lower() for p in priority} if priority else None try: with os.scandir(archive_path) as scan: files = [e for e in scan if e.name.endswith(".json") and e.name != WRITE_TEST] files.sort(key=lambda e: e.stat().st_ctime, reverse=True) + if daily_cache is not None: + present: set[str] = {e.name for e in files} + for gone in [name for name in daily_cache if name not in present]: + del daily_cache[gone] earliest: float = after.timestamp() if after else -math.inf latest: float = before.timestamp() if before else math.inf for entry in files: @@ -99,12 +125,17 @@ def _list_entries_sync( break if (after or before) and (named := _filename_period(entry.name)) and (named[1] < earliest or named[0] > latest): continue - try: - with open(entry.path, encoding="utf-8") as fh: - data: dict[str, Any] = json.load(fh) - except Exception as exc: - _LOGGER.debug("SUPERNOTIFY Skipping unreadable archive file %s: %s", entry.name, exc) - continue + data: dict[str, Any] | None = daily_cache.get(entry.name) if daily_cache is not None else None + if data is None: + try: + with open(entry.path, encoding="utf-8") as fh: + data = json.load(fh) + except Exception as exc: + _LOGGER.debug("SUPERNOTIFY Skipping unreadable archive file %s: %s", entry.name, exc) + continue + if daily_cache is not None: + data = _daily_record(data) + daily_cache[entry.name] = data created: dt.datetime | None = dt_util.parse_datetime(data.get("created") or "") if after is not None and created is not None and created < after: continue @@ -242,6 +273,8 @@ def __init__( # why the path can't be used, if it can't self.error: str | None = None self.diagnostics: OutcomeSelection = diagnostics + # daily records by file name, for enquire_archive verbosity daily (see _list_entries_sync) + self.daily_cache: dict[str, dict[str, Any]] = {} async def initialize(self) -> None: verify_archive_path: Path = Path(self.configured_path) @@ -324,6 +357,24 @@ async def list_entries( ) return entries + async def list_daily_records( + self, + after: dt.datetime | None = None, + before: dt.datetime | None = None, + outcome: str | None = None, + priority: list[str] | None = None, + ) -> list[dict[str, Any]]: + """Like ``list_entries`` with no limit, but each notification as its daily record + (``_daily_record``), which is what ``summarize_by_day`` needs. Records are kept in memory + by file name, so a file is opened only the first time it is asked for.""" + if not self.archive_path or not await self.archive_path.exists(): + return [] + args = (str(self.archive_path), sys.maxsize, after, before, outcome, priority, self.daily_cache) + if self.hass_api is None: # only a directory made outside Home Assistant, as in some tests + return _list_entries_sync(*args) + records: list[dict[str, Any]] = await self.hass_api.create_job(_list_entries_sync, *args) + return records + async def read_entry(self, notification_id: str) -> dict[str, Any] | None: """Return the full JSON of one archived notification by its id, or ``None``.""" if not self.archive_path or not await self.archive_path.exists(): diff --git a/docs/usage/actions.md b/docs/usage/actions.md index 6b1a941122..2cd5ffeb1b 100644 --- a/docs/usage/actions.md +++ b/docs/usage/actions.md @@ -54,7 +54,9 @@ button (`button.supernotify_reset_overrides`) on the SuperNotify device. `enquire_archive` with `verbosity: daily` gives totals for each local day instead of the notifications themselves, for usage charts or a template sensor. Every notification in the range is counted unless a `limit` -is given, so a month is a few kilobytes however busy it was. +is given, so a month is a few kilobytes however busy it was. Without a `limit`, each archive file is read +once and what the totals need of it is kept in memory, so asking again only reads the notifications archived +since; files removed by `purge_archive` drop out on the next ask. ```yaml action: supernotify.enquire_archive diff --git a/tests/components/supernotify/test_enquire_archive_daily.py b/tests/components/supernotify/test_enquire_archive_daily.py index 5d4af72e09..a3e8b653e3 100644 --- a/tests/components/supernotify/test_enquire_archive_daily.py +++ b/tests/components/supernotify/test_enquire_archive_daily.py @@ -199,3 +199,95 @@ async def test_summary_lists_scenarios_however_they_were_stored( assert response is not None assert response["notifications"][0]["scenarios"] == names + + +async def test_action_reads_each_file_once( + hass: HomeAssistant, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch +) -> None: + import builtins + + await hass.config.async_set_time_zone("Europe/Rome") + now = dt_util.now() + for i in range(6): + _write(tmp_path, now - dt.timedelta(hours=i * 5)) + await _setup(hass, str(tmp_path)) + opened: list[str] = [] + real_open = builtins.open + + def counting_open(file: Any, *args: Any, **kwargs: Any) -> Any: # noqa: ANN401 - as builtins.open + if str(file).endswith(".json") and str(tmp_path) in str(file): + opened.append(str(file)) + return real_open(file, *args, **kwargs) + + monkeypatch.setattr(builtins, "open", counting_open) + + first = await _daily(hass, {}) + assert len(opened) == 6 + second = await _daily(hass, {}) + assert len(opened) == 6, "the second time every file comes from memory" + assert second == first + + _write(tmp_path, now + dt.timedelta(minutes=1), "latest") + third = await _daily(hass, {}) + assert len(opened) == 7, "only the new file is read" + assert third["count"] == 7 + + +async def test_action_cached_matches_filters_and_purge(hass: HomeAssistant, tmp_path: pathlib.Path) -> None: + await hass.config.async_set_time_zone("Europe/Rome") + now = dt_util.now() + names: list[pathlib.Path] = [] + for i, (outcome, priority) in enumerate([("success", "high"), ("error", "medium"), ("success", "low"), ("dupe", "medium")]): + created = now - dt.timedelta(hours=i * 7) + entry = _entry(created, outcome=outcome, priority=priority) + entry["id"] = f"f{i}" + path = tmp_path / (created.isoformat()[:16].replace(":", "-") + f"_f{i}.json") + path.write_text(json.dumps(entry)) + names.append(path) + await _setup(hass, str(tmp_path)) + + assert (await _daily(hass, {}))["count"] == 4 # fills the memory + assert (await _daily(hass, {"outcome": "SUCCESS"}))["count"] == 2 + assert (await _daily(hass, {"priority": ["medium"]}))["count"] == 2 + assert (await _daily(hass, {"after": (now - dt.timedelta(hours=10)).isoformat()}))["count"] == 2 + + names[0].unlink() # as purge_archive does + after_purge = await _daily(hass, {}) + assert after_purge["count"] == 3 + assert sum(day["priority"].get("high", 0) for day in after_purge["days"]) == 0 + + +def test_daily_record_keeps_what_the_summary_needs(rome: None) -> None: + from custom_components.supernotify.archive import _daily_record + + entry = _entry( + dt.datetime(2026, 10, 4, 9, 15, tzinfo=ROME), + outcome="partial_delivery", + deliveries={"push": {"success": [{}]}, "alexa": {"error": [{}]}, "email": {"skipped": {"x": 1}}, "odd": "?"}, + scenarios={"morning": {}}, + ) + entry["message"] = "x" * 5000 + + record = _daily_record(entry) + + assert "message" not in record + assert summarize_by_day([record]) == summarize_by_day([entry]) + + +async def test_daily_records_outside_home_assistant(tmp_path: pathlib.Path) -> None: + from custom_components.supernotify.archive import ArchiveDirectory + + missing = ArchiveDirectory(str(tmp_path / "never")) + assert await missing.list_daily_records() == [] + + directory = ArchiveDirectory(str(tmp_path)) + await directory.initialize() + now = dt_util.now() + _write(tmp_path, now) + _write(tmp_path, now - dt.timedelta(hours=2)) + + records = await directory.list_daily_records() + + assert len(records) == 2 + assert len(directory.daily_cache) == 2 + assert set(records[0]) == {"created", "outcome", "priority", "deliveries", "enabled_scenarios"}