diff --git a/.github/scripts/dashboard_entity_allowlist.txt b/.github/scripts/dashboard_entity_allowlist.txt index f5306873..a483a4a2 100644 --- a/.github/scripts/dashboard_entity_allowlist.txt +++ b/.github/scripts/dashboard_entity_allowlist.txt @@ -176,6 +176,7 @@ sensor.mariadb_log_file_size sensor.mariadb_max_connections sensor.mariadb_performance sensor.mariadb_questions +sensor.mariadb_recorder_workload sensor.mariadb_status sensor.mariadb_table_cache sensor.mariadb_tmp_table_size diff --git a/config/dashboards/README.md b/config/dashboards/README.md index 7631fb55..96bdf0fb 100644 --- a/config/dashboards/README.md +++ b/config/dashboards/README.md @@ -22,6 +22,12 @@ This folder holds YAML-managed Home Assistant Lovelace dashboards, UI resources, and themes. +### Recorder database history + +The [Systems database view](infrastructure/partials/mariadb_sections.yaml) shows 90 days of database size and daily state writes, a seven-day moving average, and the ten busiest entities over 30 completed local days. Expand an entity to see its ID, its share of all state rows, and the number of days it appeared in the daily top ten. The native Storage report shows the space used by retained data. Compare both before changing what you record. + +The [MariaDB package](../packages/mariadb.yaml) calls the [snapshot runner](../shell_scripts/mariadb_snapshot.py) and [workload collector](../shell_scripts/recorder_workload.py). The collector needs MariaDB, the existing Recorder database URL, and a writable local cache. Backfill can count only retained rows. The oldest partially retained day and the current day are omitted. [Screenshots and worked example](https://github.com/CCOSTAN/Home-AssistantConfig/issues/2081). + The Home and Systems status grids fit their columns to the available card area, including when the sidebar is open. Long names and readings wrap at their usual text size. Systems > HVAC includes a read-only downstairs cooling plan below equipment maintenance. diff --git a/config/dashboards/infrastructure/partials/mariadb_sections.yaml b/config/dashboards/infrastructure/partials/mariadb_sections.yaml index b116901a..68f224f2 100644 --- a/config/dashboards/infrastructure/partials/mariadb_sections.yaml +++ b/config/dashboards/infrastructure/partials/mariadb_sections.yaml @@ -4,9 +4,10 @@ # Original Repo : https://github.com/CCOSTAN/Home-AssistantConfig # ------------------------------------------------------------------- # Infrastructure Partial - MariaDB -# Humanized KPIs, seven-day capacity trends, recorder health, and tuning. +# Related Issue: 2081 +# Database growth, daily ingest, ranked writers, server health, and tuning. # ------------------------------------------------------------------- -# Notes: Database growth, ingest rate, and connections use consistent 168-hour graphs. +# Notes: Writer shares count Recorder state rows over completed local days. ###################################################################### # ------------------------------------------------------------------- @@ -73,65 +74,142 @@ # ------------------------------------------------------------------- - type: grid column_span: 4 - columns: 3 + columns: 2 square: false cards: - - type: custom:mini-graph-card - name: Database Growth - icon: mdi:database-arrow-up - hours_to_show: 2160 - points_per_hour: 0.0416667 - line_width: 2 - smoothing: true - show: - legend: false - labels: false - name: true - icon: true - state: true - entities: - - entity: sensor.database_size - name: Database Size - card_mod: - style: !include /config/dashboards/infrastructure/card_mod/infra_card.yaml + - type: custom:layout-card + grid_options: + columns: full + layout_type: custom:grid-layout + layout: + grid-template-columns: repeat(2, minmax(0, 1fr)) + grid-gap: 12px + margin: 0 + mediaquery: + "(max-width: 700px)": + grid-template-columns: minmax(0, 1fr) + cards: + - type: custom:mini-graph-card + name: Database Growth (90 Days) + icon: mdi:database-arrow-up + hours_to_show: 2160 + points_per_hour: 0.0416667 + line_width: 2 + smoothing: true + show: + legend: false + labels: false + name: true + icon: true + state: true + entities: + - entity: sensor.database_size + name: Database Size + card_mod: + style: !include /config/dashboards/infrastructure/card_mod/infra_card.yaml - - type: custom:mini-graph-card - name: Recorder Ingest Rate - icon: mdi:chart-line - hours_to_show: 2160 - points_per_hour: 0.0416667 - line_width: 2 - smoothing: true - show: - legend: false - labels: false - name: true - icon: true - state: true - entities: - - entity: sensor.database_records_per_day - name: Records per Day + - type: custom:mini-graph-card + name: Active Connections + icon: mdi:lan-connect + hours_to_show: 168 + points_per_hour: 0.25 + line_width: 2 + smoothing: true + show: + legend: false + labels: false + name: true + icon: true + state: true + entities: + - entity: sensor.mariadb_connections + name: Connections + card_mod: + style: !include /config/dashboards/infrastructure/card_mod/infra_card.yaml + +# ApexCharts renders backfilled daily counts immediately from the snapshot. +- type: grid + column_span: 4 + cards: + - type: custom:apexcharts-card + grid_options: + columns: full + header: + show: true + title: Recorder Ingest (90 Days) + graph_span: 90d + span: + end: day + offset: "-1d" + apex_config: + chart: + height: 260 + legend: + show: true + tooltip: + x: + format: 'MMM d, yyyy' + yaxis: + labels: + formatter: "EVAL:function(n) { return Math.round(n / 1000) + 'k'; }" + plotOptions: + bar: + columnWidth: '80%' + series: + - entity: sensor.mariadb_recorder_workload + name: Daily state rows + type: column + unit: rows + color: '#5b96c3' + float_precision: 0 + data_generator: | + return (entity.attributes.daily || []).map(([date, count]) => + [new Date(date + 'T12:00:00').getTime(), count]); + - entity: sensor.mariadb_recorder_workload + name: 7-day average + type: line + unit: rows + color: '#cb7529' + stroke_width: 3 + float_precision: 0 + data_generator: | + return (entity.attributes.daily || []).map(([date, , mean]) => + [new Date(date + 'T12:00:00').getTime(), mean]); card_mod: style: !include /config/dashboards/infrastructure/card_mod/infra_card.yaml - - type: custom:mini-graph-card - name: Active Connections - icon: mdi:lan-connect - hours_to_show: 168 - points_per_hour: 0.25 - line_width: 2 - smoothing: true - show: - legend: false - labels: false - name: true - icon: true - state: true - entities: - - entity: sensor.mariadb_connections - name: Connections +# Native Markdown supports the variable-length ranking and expandable entity IDs. +- type: grid + column_span: 4 + cards: + - type: markdown + grid_options: + columns: full + title: Top Recorder Writers (30 Days) + content: |- + {% set source = 'sensor.mariadb_recorder_workload' %} + {% set days = state_attr(source, 'writer_days') %} + {% set writers = state_attr(source, 'leaders') %} + {% if days and writers %} + **{{ "{:,}".format(state_attr(source, 'writer_rows')) }} state rows** over {{ days }} completed days through {{ states(source) }}. + + + + + {% for w in writers -%} + + {% endfor -%} +
EntityState rowsShareDays in top 10
{{ (state_attr(w.entity_id, 'friendly_name') or w.entity_id.replace('_', ' ')) | e }}{{ w.entity_id | e }}
{{ "{:,}".format(w.rows) }}{{ "%.2f"|format(w.share) }}%{{ w.top_days }} / {{ days }}
+ {% else %} + Waiting for completed Recorder days. + {% endif %} + + [Open the native Storage report](/config/storage) card_mod: - style: !include /config/dashboards/infrastructure/card_mod/infra_card.yaml + style: + .: !include /config/dashboards/infrastructure/card_mod/infra_panel.yaml + ha-markdown$: | + code { overflow-wrap: anywhere; } # ------------------------------------------------------------------- # Recorder and server health @@ -172,7 +250,7 @@ - type: custom:button-card template: bearstone_infra_list_row entity: sensor.database_records_per_day - name: Records per Day + name: Retention Average per Day icon: mdi:chart-line - type: custom:button-card diff --git a/config/dashboards/infrastructure/views/05_mariadb.yaml b/config/dashboards/infrastructure/views/05_mariadb.yaml index cab4e931..f6a0992f 100644 --- a/config/dashboards/infrastructure/views/05_mariadb.yaml +++ b/config/dashboards/infrastructure/views/05_mariadb.yaml @@ -4,9 +4,10 @@ # Original Repo : https://github.com/CCOSTAN/Home-AssistantConfig # ------------------------------------------------------------------- # Infrastructure View - MariaDB +# Related Issue: 2081 # Humanized KPIs, recorder health, capacity trends, and tuning details. # ------------------------------------------------------------------- -# Notes: Trend cards use a consistent seven-day window. +# Notes: Growth and daily ingest span 90 days; top writers span 30 completed days. ###################################################################### title: MariaDB diff --git a/config/packages/README.md b/config/packages/README.md index a29572ca..272cc8d0 100755 --- a/config/packages/README.md +++ b/config/packages/README.md @@ -72,7 +72,7 @@ The kiosk package also exposes `sensor.kiosk_recent_phone_notifications`: a rest | [`speedtest.yaml`](speedtest.yaml) | Logs corroborated WAN outages, sustained latency/loss degradation, slow Ookla capacity advisories, and recovery without letting one throughput snapshot declare the WAN down. [YouTube](https://youtu.be/F-PpsKkzcrM) [Blog post](https://www.vcloudinfo.com/2026/08/home-assistant-internet-speed-monitoring-ookla.html) | `binary_sensor.infra_wan_quality_degraded`, `binary_sensor.infra_wan_outage`, `binary_sensor.infra_wan_capacity_degraded`, `sensor.ookla_speedtest_download`, `sensor.ookla_speedtest_upload`, `script.send_to_logbook` | | [`onenote_indexer.yaml`](onenote_indexer.yaml) | Dedicated-appliance OneNote indexer health/status monitoring for Joanna, explicit index-health confirmation, and failure-repair automation. Native indexer reconciliation remains the maintenance owner. | `sensor.onenote_indexer_last_job_status`, `binary_sensor.onenote_indexer_last_job_successful`, `binary_sensor.onenote_indexer_index_healthy` | | [`mqtt_status.yaml`](mqtt_status.yaml) | Command-line MQTT broker reachability probe with Spook Repairs escalation and Joanna troubleshooting dispatch on outage. | `binary_sensor.mqtt_status_raw`, `binary_sensor.mqtt_broker_problem`, `repairs.create`, `rest_command.bearclaw_command` | -| [`mariadb.yaml`](mariadb.yaml) | MariaDB recorder health and capacity snapshots with hourly live metrics, weekly admin/recorder polling, and stats-ready numeric sensors. | `sensor.mariadb_status`, `sensor.database_size` | +| [`mariadb.yaml`](mariadb.yaml) | Recorder health, 90 days of daily state counts and a seven-day average, plus the top writers over 30 completed days. [Collector](../shell_scripts/recorder_workload.py) ยท [Dashboard and screenshots](https://github.com/CCOSTAN/Home-AssistantConfig/issues/2081) | `sensor.mariadb_recorder_workload`, `sensor.database_size` | | [`processmonitor.yaml`](processmonitor.yaml) | Root filesystem disk-pressure monitoring with immediate digest/logbook notes at 80%, Joanna review after 10 minutes above 80%, and delayed phone alerts only if the issue stays unresolved after dispatch. | `sensor.disk_use_percent`, `repairs.create`, `script.joanna_dispatch`, `tts.clear_cache` | | [`tugtainer_updates.yaml`](tugtainer_updates.yaml) | Tugtainer container update reports via webhook, with Available-only reports processed without persistent alerts, visible `### Updated:` / `### Failed:` / `### Rolled-back:` outcomes, immediate Joanna recovery dispatch for failures, and Joanna review dispatch for every `### Available:` report. The notification template must include still-pending `available(notified)` items so unresolved updates remain visible. At 07:30 the existing post-rollout check requests a fresh private Security & Updates scan and verifies the completed rollout, application health, and protected updater components independently of report contents. Home Assistant core participates in the 07:00 automatic rollout after a mandatory Tugtainer pre-update config check, with HTTP health and image rollback safeguards. Protected Tugtainer control-plane containers are updated one host at a time through their owning Compose stacks; duplicate Portainer image-update entities are auto-disabled because Tugtainer and Compose own rollout decisions. [YouTube](https://youtu.be/4NNOkXzUyYw) [Blog post](https://www.vcloudinfo.com/2026/07/home-assistant-tugtainer-docker-updates.html) | `automation.tugtainer_disable_duplicate_portainer_image_updates`, `persistent_notification.create`, `event: tugtainer_available_detected`, `script.joanna_dispatch`, `input_datetime.tugtainer_last_update` | | [`printer.yaml`](printer.yaml) | Epson ink watchdog with one-day and one-week mobile snooze actions for low-ink reminders. | `input_datetime.printer_ink_snooze_until`, `sensor.epson_*`, mobile app action events | diff --git a/config/packages/mariadb.yaml b/config/packages/mariadb.yaml index 9ea650e2..14fd58ad 100644 --- a/config/packages/mariadb.yaml +++ b/config/packages/mariadb.yaml @@ -4,14 +4,29 @@ # Original Repo : https://github.com/CCOSTAN/Home-AssistantConfig # ------------------------------------------------------------------- # MariaDB Monitoring - Snapshot-driven DB health sensors +# Related Issue: 2081 # Recorder-backed metrics for MariaDB health, capacity, and tuning. # ------------------------------------------------------------------- # Notes: Uses command_line snapshot helpers so expensive MariaDB queries are not forced to run every 30 seconds by the SQL integration. # Notes: Live metrics poll hourly; recorder/admin snapshots poll weekly. +# Notes: Workload uses completed local days and reuses cached daily counts on each poll. # Notes: Numeric template sensors expose state_class where useful so HA can keep long-term statistics efficiently. ###################################################################### command_line: + - sensor: + name: MariaDB Recorder Workload + unique_id: mariadb_recorder_workload + command: "python3 /config/shell_scripts/mariadb_snapshot.py workload" + scan_interval: 3600 + command_timeout: 900 + value_template: "{{ value_json.through }}" + json_attributes: + - daily + - leaders + - writer_days + - writer_rows + - sensor: name: MariaDB Live Snapshot unique_id: mariadb_live_snapshot diff --git a/config/shell_scripts/README.md b/config/shell_scripts/README.md index e9ed1667..4b2504ff 100755 --- a/config/shell_scripts/README.md +++ b/config/shell_scripts/README.md @@ -26,6 +26,7 @@ Longer-running shell helpers referenced by automations, packages, or cron. Anyth ### Featured files to browse | File | Why it matters | | --- | --- | +| [Recorder workload](recorder_workload.py) and [snapshot runner](mariadb_snapshot.py) | Cache completed daily state counts and rank monthly writers for the [Systems database charts](../dashboards/README.md#recorder-database-history). | | [HAUpdate.sh](HAUpdate.sh) | One-command Home Assistant update helper. | | [`holiday_countdowns.py`](holiday_countdowns.py) | Local countdowns and perpetual holiday/flag calendars using weekday rules, python-dateutil for Gregorian Easter, and hdate for 25 Kislev. Reads public events from `www/json_data` and optional private recurring dates from `secrets/household_holidays.json`. Uses the container's local timezone and installed libraries; no API key or network call. Actual dates are used, rather than substitute workdays. Preview with `python3 holiday_countdowns.py chanukkah --date 2026-10-15`. [Watch local holiday countdowns](https://youtu.be/QzrfDFA7htc) [Local holiday countdowns blog](https://www.vcloudinfo.com/2026/10/home-assistant-local-holiday-countdowns-python-codex.html) | | [apt_pending_check.sh](apt_pending_check.sh) | On-demand, read-only APT pending-count reporter for the Docker host maintenance dashboard. | diff --git a/config/shell_scripts/mariadb_snapshot.py b/config/shell_scripts/mariadb_snapshot.py index 05685dca..55553656 100644 --- a/config/shell_scripts/mariadb_snapshot.py +++ b/config/shell_scripts/mariadb_snapshot.py @@ -119,12 +119,12 @@ def main() -> int: """Run the requested query mode and emit a compact JSON payload.""" mode = sys.argv[1].strip().lower() if len(sys.argv) > 1 else "" - if len(sys.argv) != 2 or mode not in QUERIES: + if len(sys.argv) != 2 or (mode not in QUERIES and mode != "workload"): print( json.dumps( { "error": "usage", - "message": "expected one mode: admin, live, recorder", + "message": "expected one mode: admin, live, recorder, workload", }, separators=(",", ":"), ), @@ -135,8 +135,14 @@ def main() -> int: engine = create_engine(_load_db_url(), pool_pre_ping=True) try: - with engine.connect() as connection: - row = connection.execute(text(QUERIES[mode])).mappings().one() + if mode == "workload": + from recorder_workload import collect_workload + + payload = collect_workload(engine) + else: + with engine.connect() as connection: + row = connection.execute(text(QUERIES[mode])).mappings().one() + payload = {key: _json_safe(value) for key, value in row.items()} except Exception as err: # pragma: no cover - runtime safety path print( json.dumps( @@ -147,7 +153,6 @@ def main() -> int: ) return 1 - payload = {key: _json_safe(value) for key, value in row.items()} print(json.dumps(payload, separators=(",", ":"))) return 0 diff --git a/config/shell_scripts/recorder_workload.py b/config/shell_scripts/recorder_workload.py new file mode 100644 index 00000000..c095e45f --- /dev/null +++ b/config/shell_scripts/recorder_workload.py @@ -0,0 +1,102 @@ +"""Summarize completed local days for the Systems Recorder charts (issue #2081).""" + +import json +import sqlite3 +from collections import Counter +from datetime import date, datetime, time, timedelta +from pathlib import Path + +from sqlalchemy import bindparam, text + +CACHE = Path("/config/.cache/mariadb/workload.sqlite") +DAY = timedelta(days=1) +TREND_DAYS = 90 +WRITER_DAYS = 30 +MEAN_DAYS = 7 +TOP = 10 +WINDOW = "FROM states WHERE last_updated_ts >= :start AND last_updated_ts < :end" + + +def collect_workload(engine, cache_path=CACHE): + # The container's TZ is the HA local timezone. Allow the final Recorder + # commit to settle before sealing yesterday, including on DST transitions. + end = (datetime.now() - timedelta(minutes=5)).date() + writer_start = end - WRITER_DAYS * DAY + trend_start = end - TREND_DAYS * DAY + first = trend_start - (MEAN_DAYS - 1) * DAY + cache_path.parent.mkdir(parents=True, exist_ok=True) + cache = sqlite3.connect(cache_path, timeout=30) + try: + cache.execute( + "CREATE TABLE IF NOT EXISTS days " + "(day TEXT PRIMARY KEY, total INTEGER NOT NULL, counts TEXT)" + ) + with engine.connect() as db: + db.exec_driver_sql("SET SESSION TRANSACTION READ ONLY") + db.exec_driver_sql("SET SESSION max_statement_time = 30") + oldest = db.scalar(text("SELECT MIN(last_updated_ts) FROM states")) + db.rollback() + if oldest is None: + raise ValueError("Recorder contains no state rows") + # A backfill cannot establish a full count for the first retained day. + earliest_full = datetime.fromtimestamp(oldest).date() + DAY + saved = {d for d, in cache.execute("SELECT day FROM days")} + day = max(first, earliest_full) + while day < end: + key = day.isoformat() + if key not in saved: + bounds = { + "start": datetime.combine(day, time.min).timestamp(), + "end": datetime.combine(day + DAY, time.min).timestamp(), + } + counts = None + if day >= writer_start: + rows = db.execute(text("SELECT metadata_id, COUNT(*) " + WINDOW + + " GROUP BY metadata_id"), bounds) + counts = {int(mid or 0): n for mid, n in rows} + total = sum(counts.values()) + else: + total = db.scalar(text("SELECT COUNT(*) " + WINDOW), bounds) + db.rollback() # Release the MariaDB read view between days. + with cache: + cache.execute("INSERT OR IGNORE INTO days VALUES (?, ?, ?)", + (key, total, json.dumps(counts) if counts is not None else None)) + day += DAY + with cache: + cache.execute("DELETE FROM days WHERE day < ?", (first.isoformat(),)) + cache.execute("UPDATE days SET counts = NULL WHERE day < ? AND counts IS NOT NULL", + (writer_start.isoformat(),)) + + daily = {} + writers = Counter() + top_days = Counter() + periods = 0 + for key, total, counts in cache.execute("SELECT day, total, counts FROM days WHERE day < ? ORDER BY day", (end.isoformat(),)): + daily[date.fromisoformat(key)] = total + if counts is not None and key >= writer_start.isoformat(): + volumes = {int(mid): n for mid, n in json.loads(counts).items()} + writers.update(volumes) + top_days.update(sorted(volumes, key=lambda mid: (-volumes[mid], mid))[:TOP]) + periods += 1 + + ranked = sorted((mid for mid in writers if mid), key=lambda mid: (-writers[mid], mid))[:TOP] + names = dict(db.execute(text("SELECT metadata_id, entity_id FROM states_meta WHERE metadata_id IN :ids") + .bindparams(bindparam("ids", expanding=True)), {"ids": ranked}).all()) + volume = sum(writers.values()) + leaders = [{ + "entity_id": names.get(mid, f"Removed entity ({mid})"), + "rows": writers[mid], + "share": round(writers[mid] * 100 / volume, 2), + "top_days": top_days[mid], + } for mid in ranked] + trend = [] + for day, total in daily.items(): + if day < trend_start: + continue + week = [daily.get(day - offset * DAY) for offset in range(MEAN_DAYS)] + mean = round(sum(week) / MEAN_DAYS) if None not in week else None + trend.append([day.isoformat(), total, mean]) + return {"through": (end - DAY).isoformat(), "daily": trend, "leaders": leaders, + "writer_days": periods, "writer_rows": volume} + finally: + cache.close()