Add recorder database usage report (#190600)

Test failure unrelated.
This commit is contained in:
Erwin Douna
2026-11-16 20:06:07 +01:00
committed by GitHub
parent 5eb4fac646
commit 9c4e47ec5e
4 changed files with 1526 additions and 0 deletions
@@ -27,6 +27,7 @@ from homeassistant.util.event_type import EventType
# startup
from . import (
backup, # noqa: F401
database_usage,
entity_options,
entity_registry,
websocket_api,
@@ -187,6 +188,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
)
get_instance.cache_clear()
entity_registry.async_setup(hass)
database_usage.async_setup(hass)
entity_options.async_setup(hass)
instance.async_initialize()
instance.async_register()
@@ -0,0 +1,493 @@
"""Report which entities and statistics use space in the recorder database."""
import asyncio
from collections import defaultdict
from collections.abc import Callable, Mapping
from contextlib import suppress
from datetime import datetime, timedelta
import os
from typing import TYPE_CHECKING, Any, Final, TypedDict
import probatio
from sqlalchemy import LargeBinary, cast, exists, func, literal_column, select, text
from sqlalchemy.exc import OperationalError
from sqlalchemy.orm.session import Session
from homeassistant.components import websocket_api
from homeassistant.core import HassJob, HomeAssistant, callback
from homeassistant.helpers.event import async_call_later
from homeassistant.helpers.recorder import get_instance, session_scope
from homeassistant.util import dt as dt_util
from homeassistant.util.hass_dict import HassKey
from .const import DOMAIN, SupportedDialect
from .db_schema import (
TABLE_STATE_ATTRIBUTES,
TABLE_STATES,
TABLE_STATISTICS,
TABLE_STATISTICS_SHORT_TERM,
StateAttributes,
States,
StatesMeta,
Statistics,
StatisticsMeta,
StatisticsShortTerm,
)
if TYPE_CHECKING:
from sqlalchemy.dialects.mysql.base import MySQLDialect
from .core import Recorder
CACHE_TIME: Final = timedelta(hours=1)
REFRESH_INTERVAL: Final = timedelta(minutes=1)
DATA_DATABASE_USAGE: HassKey[DatabaseUsageCache] = HassKey(f"{DOMAIN}_database_usage")
SQLITE_DBSTAT_QUERY: Final = (
"SELECT m.tbl_name, SUM(d.pgsize) FROM dbstat AS d "
"JOIN sqlite_master AS m ON m.name = d.name "
"WHERE d.aggregate = TRUE GROUP BY m.tbl_name"
)
class TableUsage(TypedDict):
"""Space used by one table, including its indexes."""
table: str
bytes: int
class EntityUsage(TypedDict):
"""Estimated space the states of one entity use.
An entity_id of None collects rows without a known entity.
"""
entity_id: str | None
states: int
states_bytes: int | None
attributes_bytes: int | None
class StatisticUsage(TypedDict):
"""Estimated space one statistic uses.
A statistic_id of None collects rows without a known statistic.
"""
statistic_id: str | None
source: str | None
statistics: int
statistics_short_term: int
statistics_bytes: int | None
statistics_short_term_bytes: int | None
class DatabaseUsage(TypedDict):
"""Space used in the recorder database.
total_bytes is the size of the database, free_bytes included, without the
SQLite write-ahead log, whose files wal_bytes holds. On MySQL and MariaDB
the byte figures are approximate, as they come from InnoDB statistics.
Byte figures per table and row are None when the engine cannot report
table sizes.
"""
generated_at: datetime
duration: float
total_bytes: int
free_bytes: int | None
wal_bytes: int | None
tables: list[TableUsage] | None
entities: list[EntityUsage]
statistics: list[StatisticUsage]
def _sqlite_table_bytes(session: Session) -> tuple[dict[str, int] | None, int, int]:
"""Return bytes per table, the database size and its free space."""
page_count = session.execute(text("PRAGMA page_count")).scalar_one()
page_size = session.execute(text("PRAGMA page_size")).scalar_one()
free_pages = session.execute(text("PRAGMA freelist_count")).scalar_one()
try:
rows = session.execute(text(SQLITE_DBSTAT_QUERY)).all()
except OperationalError as err:
# Only dbstat can be missing, when built without SQLITE_ENABLE_DBSTAT_VTAB
if "no such table" not in str(err.orig):
raise
table_bytes = None
else:
table_bytes = {table: int(size) for table, size in rows}
return table_bytes, page_count * page_size, free_pages * page_size
def _sqlite_wal_bytes(session: Session) -> int | None:
"""Return the size of the write-ahead log and its index, None in memory."""
database = next(
file
for _, name, file in session.execute(text("PRAGMA database_list")).all()
if name == "main"
)
if not database:
return None
size = 0
for postfix in ("-wal", "-shm"):
with suppress(FileNotFoundError):
size += os.path.getsize(f"{database}{postfix}")
return size
def _mysql_table_bytes(session: Session) -> tuple[dict[str, int], int, int]:
"""Return bytes per table, the database size and its free space."""
dialect = session.get_bind().dialect
if TYPE_CHECKING:
assert isinstance(dialect, MySQLDialect)
stats_expiry = None
if not dialect.is_mariadb:
# MySQL caches these sizes for a day by default, MariaDB does not
stats_expiry = session.execute(
text("SELECT @@SESSION.information_schema_stats_expiry")
).scalar_one()
session.execute(text("SET SESSION information_schema_stats_expiry = 0"))
try:
rows = session.execute(
text(
"SELECT table_name, data_length + index_length, data_free "
"FROM information_schema.tables WHERE table_schema = DATABASE() "
"AND table_type = 'BASE TABLE'"
)
).all()
finally:
# The session setting would otherwise stay on the pooled connection
if stats_expiry is not None:
session.execute(
text("SET SESSION information_schema_stats_expiry = :expiry"),
{"expiry": stats_expiry},
)
table_bytes = {table: int(size or 0) for table, size, _ in rows}
table_free = [int(free or 0) for _, _, free in rows]
# Free space is computed as for InnoDB, the only engine the recorder creates
# tables with. Tables in the shared tablespace each report its free space.
# This assumes all tables were created under the current innodb_file_per_table:
# it overcounts tables left in ibdata1 when on, and undercounts when off
if session.execute(text("SELECT @@innodb_file_per_table")).scalar_one():
free_bytes = sum(table_free)
else:
free_bytes = max(table_free, default=0)
return table_bytes, sum(table_bytes.values()) + free_bytes, free_bytes
def _postgresql_table_bytes(session: Session) -> tuple[dict[str, int], int, None]:
"""Return bytes per table and the database size, catalogs included.
Tables are those unqualified names resolve to through the search_path.
"""
table_bytes = {
table: int(size)
for table, size in session.execute(
text(
"SELECT c.relname, pg_total_relation_size(c.oid) FROM pg_class AS c "
"JOIN pg_namespace AS n ON n.oid = c.relnamespace "
"WHERE c.relkind = 'r' AND pg_table_is_visible(c.oid) "
"AND n.nspname NOT IN ('pg_catalog', 'information_schema')"
)
).all()
}
total = session.execute(
text("SELECT pg_database_size(current_database())")
).scalar_one()
return table_bytes, int(total), None
def _counts(session: Session, column: Any) -> dict[int | None, int]:
"""Return the row count per value of an indexed column."""
return dict(session.execute(select(column, func.count()).group_by(column)).all())
def _byte_length(dialect: SupportedDialect | None, column: Any) -> Any:
"""Return the length of a text column in bytes, not characters."""
match dialect:
case SupportedDialect.MYSQL:
return func.length(column)
case SupportedDialect.POSTGRESQL:
return func.octet_length(column)
case _:
return func.length(cast(column, LargeBinary))
def _attribute_lengths(
session: Session, dialect: SupportedDialect | None
) -> dict[int | None, float]:
"""Return the attributes length in bytes per metadata_id.
An attributes row shared by several entities is split over them by how
many of their states use it. Rows without a state go to None.
"""
# + 0 makes SQLite scan the table instead of reading it through an index
owner = States.metadata_id + literal_column("0")
refs = (
select(
owner.label("metadata_id"),
States.attributes_id,
func.count().label("rows"),
)
.group_by(owner, States.attributes_id)
.subquery()
)
weighted = select(
refs.c.metadata_id,
refs.c.attributes_id,
refs.c.rows,
func.sum(refs.c.rows).over(partition_by=refs.c.attributes_id).label("total"),
).subquery()
length = _byte_length(dialect, StateAttributes.shared_attrs)
sub = (
select(
weighted.c.metadata_id.label("owner"),
func.coalesce(length * weighted.c.rows / weighted.c.total, length).label(
"length"
),
)
.select_from(StateAttributes)
.outerjoin(weighted, weighted.c.attributes_id == StateAttributes.attributes_id)
.subquery()
)
return {
metadata_id: float(length or 0)
for metadata_id, length in session.execute(
select(sub.c.owner, func.sum(sub.c.length)).group_by(sub.c.owner)
).all()
}
def _has_orphan_attributes(session: Session) -> bool:
"""Return if an attributes row has no state."""
return (
session.execute(
select(StateAttributes.attributes_id)
.where(
~exists().where(States.attributes_id == StateAttributes.attributes_id)
)
.limit(1)
).first()
is not None
)
def _group[KeyT, ValueT: (int, float)](
values: dict[int | None, ValueT], keys: Mapping[int | None, KeyT]
) -> dict[KeyT | None, ValueT]:
"""Return the values per key, with unknown ids under None."""
grouped: dict[KeyT | None, ValueT] = defaultdict(int)
for id_, value in values.items():
grouped[keys.get(id_)] += value
return grouped
def _begin_snapshot(session: Session, dialect: SupportedDialect | None) -> None:
"""Begin a transaction that reads one snapshot of the database."""
match dialect:
case SupportedDialect.MYSQL:
session.connection(execution_options={"isolation_level": "REPEATABLE READ"})
case SupportedDialect.POSTGRESQL:
session.connection(
execution_options={
"isolation_level": "REPEATABLE READ",
"postgresql_readonly": True,
}
)
case _:
# pysqlite only begins a transaction for writes; in WAL mode the read
# transaction does not block the recorder, but holds back checkpoints
# until the report is done
session.execute(text("BEGIN"))
def get_database_usage(instance: Recorder) -> DatabaseUsage:
"""Return the space entities and statistics use in the database.
Table sizes come from the database engine; a table's bytes are spread over
its rows evenly, except for attributes, which are spread by the length of
the JSON each entity owns. Row counts read one snapshot of the database.
"""
started = dt_util.utcnow()
dialect = instance.dialect_name
wal_bytes: int | None = None
with session_scope(session=instance.get_session(), read_only=True) as session:
_begin_snapshot(session, dialect)
states = _counts(session, States.metadata_id)
statistics = _counts(session, Statistics.metadata_id)
short_term = _counts(session, StatisticsShortTerm.metadata_id)
table_bytes: dict[str, int] | None
free_bytes: int | None
match dialect:
case SupportedDialect.MYSQL:
table_bytes, total_bytes, free_bytes = _mysql_table_bytes(session)
case SupportedDialect.POSTGRESQL:
table_bytes, total_bytes, free_bytes = _postgresql_table_bytes(session)
case _:
table_bytes, total_bytes, free_bytes = _sqlite_table_bytes(session)
wal_bytes = _sqlite_wal_bytes(session)
attributes: dict[int | None, float]
if table_bytes is not None:
attributes = _attribute_lengths(session, dialect)
elif _has_orphan_attributes(session):
attributes = {None: 0}
else:
attributes = {}
entity_ids: dict[int | None, str | None] = dict(
session.execute(select(StatesMeta.metadata_id, StatesMeta.entity_id)).all()
)
statistic_ids: dict[int | None, tuple[str | None, str | None]] = {
id_: (statistic_id, source)
for id_, statistic_id, source in session.execute(
select(
StatisticsMeta.id,
StatisticsMeta.statistic_id,
StatisticsMeta.source,
)
).all()
}
totals = {
TABLE_STATES: sum(states.values()),
TABLE_STATE_ATTRIBUTES: sum(attributes.values()),
TABLE_STATISTICS: sum(statistics.values()),
TABLE_STATISTICS_SHORT_TERM: sum(short_term.values()),
}
def share(table: str, part: float) -> int | None:
"""Return the bytes of a table that part of its rows or JSON takes."""
if table_bytes is None:
return None
if not part:
return 0
return round(table_bytes.get(table, 0) * part / totals[table])
entity_states = _group(states, entity_ids)
entity_attributes = _group(attributes, entity_ids)
statistic_rows = _group(statistics, statistic_ids)
statistic_short_term = _group(short_term, statistic_ids)
generated_at = dt_util.utcnow()
return {
"generated_at": generated_at,
"duration": (generated_at - started).total_seconds(),
"total_bytes": total_bytes,
"free_bytes": free_bytes,
"wal_bytes": wal_bytes,
"tables": None
if table_bytes is None
else [{"table": table, "bytes": size} for table, size in table_bytes.items()],
"entities": [
{
"entity_id": entity_id,
"states": entity_states.get(entity_id, 0),
"states_bytes": share(TABLE_STATES, entity_states.get(entity_id, 0)),
"attributes_bytes": share(
TABLE_STATE_ATTRIBUTES, entity_attributes.get(entity_id, 0)
),
}
for entity_id in entity_states | entity_attributes
],
"statistics": [
{
"statistic_id": key[0] if key else None,
"source": key[1] if key else None,
"statistics": statistic_rows.get(key, 0),
"statistics_short_term": statistic_short_term.get(key, 0),
"statistics_bytes": share(TABLE_STATISTICS, statistic_rows.get(key, 0)),
"statistics_short_term_bytes": share(
TABLE_STATISTICS_SHORT_TERM, statistic_short_term.get(key, 0)
),
}
for key in statistic_rows | statistic_short_term
],
}
class DatabaseUsageCache:
"""Run one database usage report at a time and keep the last result."""
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize the cache."""
self._hass = hass
self.usage: DatabaseUsage | None = None
self._pending: asyncio.Future[DatabaseUsage] | None = None
self._expire_job = HassJob(self._async_expire, cancel_on_shutdown=True)
self._cancel_expire: Callable[[], None] | None = None
async def async_refresh(self, instance: Recorder) -> DatabaseUsage:
"""Return a new report, or the last one if it is still recent."""
if self._pending is None:
if (
self.usage is not None
and dt_util.utcnow() - self.usage["generated_at"] < REFRESH_INTERVAL
):
return self.usage
self._pending = instance.async_add_executor_job(
get_database_usage, instance
)
self._pending.add_done_callback(self._async_finished)
# A cancelled request must not cancel the run other requests wait for
return await asyncio.shield(self._pending)
@callback
def _async_finished(self, future: asyncio.Future[DatabaseUsage]) -> None:
"""Store the result of a finished run."""
self._pending = None
if future.cancelled() or future.exception() is not None:
return
if self._cancel_expire is not None:
self._cancel_expire()
self.usage = future.result()
self._cancel_expire = async_call_later(self._hass, CACHE_TIME, self._expire_job)
@callback
def _async_expire(self, _now: datetime) -> None:
"""Release the cached report."""
self._cancel_expire = None
self.usage = None
@callback
def async_setup(hass: HomeAssistant) -> None:
"""Set up the database usage websocket API."""
hass.data[DATA_DATABASE_USAGE] = DatabaseUsageCache(hass)
websocket_api.async_register_command(hass, ws_database_usage)
@websocket_api.require_admin
@websocket_api.websocket_command(
{
probatio.Required("type"): "recorder/database_usage",
probatio.Optional("refresh", default=False): bool,
}
)
@websocket_api.async_response
async def ws_database_usage(
hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any]
) -> None:
"""Return the last report, or analyze the database when refresh is set."""
cache = hass.data[DATA_DATABASE_USAGE]
if not msg["refresh"]:
connection.send_result(msg["id"], cache.usage)
return
instance = get_instance(hass)
# Shielded, as cancelling these shared futures would break recorder startup
if (
await asyncio.shield(instance.async_db_connected)
and instance.migration_in_progress
):
connection.send_error(
msg["id"],
"migration_in_progress",
"The recorder database is being migrated",
)
return
# The recorder executor starts once the database is ready
if not await asyncio.shield(instance.async_db_ready):
connection.send_error(
msg["id"], "recorder_not_ready", "The recorder database is not available"
)
return
connection.send_result(msg["id"], await cache.async_refresh(instance))
@@ -0,0 +1,39 @@
# serializer version: 1
# name: test_database_usage
dict({
'duration': float,
'entities': list([
dict({
'attributes_bytes': int,
'entity_id': 'sensor.busy',
'states': 10,
'states_bytes': int,
}),
dict({
'attributes_bytes': int,
'entity_id': 'sensor.quiet',
'states': 1,
'states_bytes': int,
}),
]),
'generated_at': '2026-01-01T12:00:00+00:00',
'statistics': list([
dict({
'source': 'recorder',
'statistic_id': 'sensor.busy',
'statistics': 3,
'statistics_bytes': int,
'statistics_short_term': 1,
'statistics_short_term_bytes': int,
}),
dict({
'source': 'test',
'statistic_id': 'test:external',
'statistics': 1,
'statistics_bytes': int,
'statistics_short_term': 0,
'statistics_short_term_bytes': int,
}),
]),
})
# ---
@@ -0,0 +1,992 @@
"""Test the recorder database usage report."""
import asyncio
from contextlib import closing
from datetime import UTC, datetime, timedelta
from pathlib import Path
import sqlite3
import threading
from typing import Any
from unittest.mock import MagicMock, Mock, patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from pytest_homeassistant.common import async_fire_time_changed
from pytest_homeassistant.components.recorder.common import (
async_recorder_block_till_done,
async_wait_purge_done,
async_wait_recording_done,
do_adhoc_statistics,
)
from pytest_homeassistant.typing import (
MockHAClientWebSocket,
RecorderInstanceContextManager,
WebSocketGenerator,
)
from sqlalchemy import create_engine, delete, select, text, update
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from syrupy.assertion import SnapshotAssertion
from syrupy.matchers import path_type
from homeassistant.components import recorder
from homeassistant.components.recorder import Recorder
from homeassistant.components.recorder.const import SupportedDialect
from homeassistant.components.recorder.database_usage import (
CACHE_TIME,
REFRESH_INTERVAL,
DatabaseUsage,
_begin_snapshot,
_mysql_table_bytes,
_sqlite_wal_bytes,
get_database_usage,
)
from homeassistant.components.recorder.db_schema import (
ALL_TABLES,
StateAttributes,
States,
StatesMeta,
Statistics,
)
from homeassistant.components.recorder.statistics import (
async_add_external_statistics,
async_import_statistics,
)
from homeassistant.components.recorder.util import get_engine_db_url, session_scope
from homeassistant.core import HomeAssistant
from homeassistant.helpers import recorder as recorder_helper
from homeassistant.setup import async_setup_component
START = datetime(2026, 1, 1, 12, 0, tzinfo=UTC)
POWER_ATTRIBUTES = {
"device_class": "power",
"state_class": "measurement",
"unit_of_measurement": "W",
}
BYTES_MATCHER = path_type({r".*bytes": (int,), "duration": (float,)}, regex=True)
def _sqlite_has_dbstat() -> bool:
"""Return if SQLite is built with the dbstat table."""
with closing(sqlite3.connect(":memory:")) as connection:
return ("ENABLE_DBSTAT_VTAB",) in connection.execute(
"PRAGMA compile_options"
).fetchall()
@pytest.fixture
def skip_without_table_sizes(recorder_db_url: str) -> None:
"""Skip tests of byte figures on SQLite built without dbstat."""
if recorder_db_url.startswith("sqlite") and not _sqlite_has_dbstat():
pytest.skip("SQLite is built without dbstat")
async def _record_data(hass: HomeAssistant) -> None:
"""Record states and statistics."""
await async_setup_component(hass, "sensor", {})
await async_recorder_block_till_done(hass)
for value in range(10):
hass.states.async_set("sensor.busy", str(value), POWER_ATTRIBUTES)
hass.states.async_set("sensor.quiet", "1", {"unit_of_measurement": "W"})
await async_wait_recording_done(hass)
do_adhoc_statistics(hass, start=START)
hourly = [
{"start": START + timedelta(hours=hour), "mean": 1.0} for hour in range(3)
]
async_import_statistics(
hass,
{
"has_sum": False,
"mean_type": 1,
"name": None,
"source": "recorder",
"statistic_id": "sensor.busy",
"unit_class": "power",
"unit_of_measurement": "W",
},
hourly,
)
async_add_external_statistics(
hass,
{
"has_sum": False,
"mean_type": 1,
"name": "External",
"source": "test",
"statistic_id": "test:external",
"unit_class": "power",
"unit_of_measurement": "W",
},
hourly[:1],
)
await async_wait_recording_done(hass)
async def _async_usage(client: MockHAClientWebSocket, **kwargs: Any) -> Any:
"""Return the database usage report from the websocket API."""
await client.send_json_auto_id({"type": "recorder/database_usage", **kwargs})
response = await client.receive_json()
assert response["success"]
return response["result"]
SPREAD = {
"states": ("entities", "states_bytes"),
"state_attributes": ("entities", "attributes_bytes"),
"statistics": ("statistics", "statistics_bytes"),
"statistics_short_term": ("statistics", "statistics_short_term_bytes"),
}
def _assert_spread(usage: DatabaseUsage, *tables: str) -> None:
"""Assert the bytes of tables with rows are spread over them, rounded per row."""
assert usage["tables"] is not None
table_bytes = {table["table"]: table["bytes"] for table in usage["tables"]}
for table in tables:
rows, key = SPREAD[table]
assert sum(row[key] for row in usage[rows]) == pytest.approx(
table_bytes[table], abs=len(usage[rows])
)
def _by_id(rows: list[dict[str, Any]], key: str) -> dict[str | None, dict[str, Any]]:
"""Return report rows by id."""
return {row[key]: row for row in rows}
@pytest.mark.usefixtures("skip_without_table_sizes")
async def test_database_usage(
recorder_mock: Recorder,
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
freezer: FrozenDateTimeFactory,
snapshot: SnapshotAssertion,
) -> None:
"""Test the report lists the space entities and statistics use."""
client = await hass_ws_client()
freezer.move_to(START)
await _record_data(hass)
result = await _async_usage(client, refresh=True)
assert {table["table"] for table in result["tables"]} >= set(ALL_TABLES)
_assert_spread(result, *SPREAD)
assert {
"duration": result["duration"],
"entities": sorted(result["entities"], key=lambda row: row["entity_id"]),
"generated_at": result["generated_at"],
"statistics": sorted(result["statistics"], key=lambda row: row["statistic_id"]),
} == snapshot(matcher=BYTES_MATCHER)
@pytest.mark.skip_on_db_engine(["mysql", "postgresql"])
@pytest.mark.usefixtures("skip_by_db_engine", "skip_without_table_sizes")
@pytest.mark.parametrize("persistent_database", [True])
async def test_database_usage_sqlite_size(
recorder_mock: Recorder, hass: HomeAssistant
) -> None:
"""Test SQLite reports every table, the file size, free pages and the WAL."""
await _record_data(hass)
for value in range(10):
hass.states.async_set(f"sensor.big_{value}", "1", {"text": "a" * 15000})
await async_wait_recording_done(hass)
await recorder_mock.async_add_executor_job(_delete_states, recorder_mock)
usage = await recorder_mock.async_add_executor_job(
get_database_usage, recorder_mock
)
(
page_size,
page_count,
free_pages,
tables,
) = await recorder_mock.async_add_executor_job(_sqlite_pages, recorder_mock)
assert usage["tables"] is not None
assert {table["table"] for table in usage["tables"]} == tables
assert usage["total_bytes"] == page_count * page_size
assert usage["free_bytes"] == free_pages * page_size > 0
assert usage["wal_bytes"] > 0
# Only the pages of the schema table itself are left out
assert (
sum(table["bytes"] for table in usage["tables"]) + usage["free_bytes"]
< usage["total_bytes"]
)
def _sqlite_pages(instance: Recorder) -> tuple[int, int, int, set[str]]:
"""Return the page size, page count, free pages and tables of SQLite."""
with session_scope(session=instance.get_session(), read_only=True) as session:
return (
session.execute(text("PRAGMA page_size")).scalar_one(),
session.execute(text("PRAGMA page_count")).scalar_one(),
session.execute(text("PRAGMA freelist_count")).scalar_one(),
{
name
for (name,) in session.execute(
text("SELECT DISTINCT tbl_name FROM sqlite_master")
)
},
)
def _delete_states(instance: Recorder) -> None:
"""Delete all states and attributes so their pages become free."""
with session_scope(session=instance.get_session()) as session:
session.query(States).delete()
session.query(StateAttributes).delete()
def _add_view(instance: Recorder) -> None:
"""Add a view to the recorder database."""
with session_scope(session=instance.get_session()) as session:
session.execute(text("CREATE VIEW usage_view AS SELECT * FROM states"))
@pytest.mark.skip_on_db_engine(["sqlite", "postgresql"])
@pytest.mark.usefixtures("skip_by_db_engine")
async def test_database_usage_mysql_size(
recorder_mock: Recorder, hass: HomeAssistant
) -> None:
"""Test MySQL reports the tables and their free space as the size on disk."""
await _record_data(hass)
await recorder_mock.async_add_executor_job(_add_view, recorder_mock)
usage = await recorder_mock.async_add_executor_job(
get_database_usage, recorder_mock
)
assert usage["tables"] is not None
assert "states" in {table["table"] for table in usage["tables"]}
assert "usage_view" not in {table["table"] for table in usage["tables"]}
assert usage["free_bytes"] is not None
assert usage["wal_bytes"] is None
assert usage["total_bytes"] == (
sum(table["bytes"] for table in usage["tables"]) + usage["free_bytes"]
)
@pytest.mark.skip_on_db_engine(["sqlite", "mysql"])
@pytest.mark.usefixtures("skip_by_db_engine")
async def test_database_usage_postgresql_size(
recorder_mock: Recorder, hass: HomeAssistant
) -> None:
"""Test PostgreSQL reports the database size and no free space."""
await _record_data(hass)
usage = await recorder_mock.async_add_executor_job(
get_database_usage, recorder_mock
)
assert usage["tables"] is not None
assert usage["free_bytes"] is None
assert usage["wal_bytes"] is None
assert usage["total_bytes"] >= sum(table["bytes"] for table in usage["tables"])
@pytest.mark.usefixtures("recorder_mock")
async def test_database_usage_empty(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test the report of a database without states or statistics."""
client = await hass_ws_client()
freezer.move_to(START)
result = await _async_usage(client, refresh=True)
assert result["total_bytes"] > 0
assert result["wal_bytes"] is None
assert result["entities"] == []
assert result["statistics"] == []
assert result["generated_at"] == START.isoformat()
def _add_unattributed_rows(instance: Recorder) -> None:
"""Add rows without a known owner, and attributes shared by two entities."""
with session_scope(session=instance.get_session()) as session:
shared_id = session.query(States.attributes_id).limit(1).scalar()
metadata_ids = [
metadata_id
for (metadata_id,) in session.query(States.metadata_id).distinct()
]
session.add_all(
[
StateAttributes(shared_attrs='{"orphan":true}', hash=1),
States(state="no metadata", metadata_id=None),
Statistics(metadata_id=None, start_ts=0.0, created_ts=0.0),
*(
States(
state="shared",
metadata_id=metadata_id,
attributes_id=shared_id,
)
for metadata_id in metadata_ids
),
]
)
async def _async_unattributed_usage(
instance: Recorder, hass: HomeAssistant
) -> DatabaseUsage:
"""Return the report of a database with rows without a known owner."""
hass.states.async_set("sensor.first", "1", {"shared": True})
hass.states.async_set("sensor.second", "1", {"other": True})
await async_wait_recording_done(hass)
await instance.async_add_executor_job(_add_unattributed_rows, instance)
return await instance.async_add_executor_job(get_database_usage, instance)
async def test_database_usage_attribution(
recorder_mock: Recorder, hass: HomeAssistant
) -> None:
"""Test rows without a known owner are counted under None."""
usage = await _async_unattributed_usage(recorder_mock, hass)
assert {(row["entity_id"], row["states"]) for row in usage["entities"]} == {
("sensor.first", 2),
("sensor.second", 2),
(None, 1),
}
assert [
(
row["statistic_id"],
row["source"],
row["statistics"],
row["statistics_short_term"],
)
for row in usage["statistics"]
] == [(None, None, 1, 0)]
@pytest.mark.usefixtures("skip_without_table_sizes")
async def test_database_usage_attribution_bytes(
recorder_mock: Recorder, hass: HomeAssistant
) -> None:
"""Test shared, orphaned and ownerless rows are each counted once."""
usage = await _async_unattributed_usage(recorder_mock, hass)
# Shared attributes are counted once, so the spread adds up
_assert_spread(usage, "states", "state_attributes", "statistics")
assert {
row["entity_id"]: row["attributes_bytes"] > 0 for row in usage["entities"]
} == {"sensor.first": True, "sensor.second": True, None: True}
assert [
(row["statistics_bytes"] > 0, row["statistics_short_term_bytes"])
for row in usage["statistics"]
] == [(True, 0)]
@pytest.mark.parametrize("repack", [False, True])
async def test_database_usage_after_purge(
recorder_mock: Recorder,
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
freezer: FrozenDateTimeFactory,
repack: bool,
) -> None:
"""Test the report only counts the rows a purge keeps."""
client = await hass_ws_client()
freezer.move_to(START)
await _record_data(hass)
freezer.move_to(START + timedelta(days=2))
hass.states.async_set("sensor.busy", "new", {"after": "purge"})
await async_wait_recording_done(hass)
await hass.services.async_call(
recorder.DOMAIN, "purge", {"keep_days": 1, "repack": repack}, blocking=True
)
await async_wait_purge_done(hass)
result = await _async_usage(client, refresh=True)
assert [(row["entity_id"], row["states"]) for row in result["entities"]] == [
("sensor.busy", 1)
]
assert {
(row["statistic_id"], row["statistics"], row["statistics_short_term"])
for row in result["statistics"]
} == {("sensor.busy", 3, 0), ("test:external", 1, 0)}
@pytest.mark.usefixtures("skip_without_table_sizes")
async def test_database_usage_weighting(
recorder_mock: Recorder, hass: HomeAssistant
) -> None:
"""Test states are spread per row and attributes by their size in bytes."""
hass.states.async_set("sensor.large", "1", {"text": "é" * 2000})
for value in range(9):
hass.states.async_set("sensor.noisy", str(value), {"text": "a" * 500})
await async_wait_recording_done(hass)
usage = await recorder_mock.async_add_executor_job(
get_database_usage, recorder_mock
)
_assert_spread(usage, "states", "state_attributes")
entities = _by_id(usage["entities"], "entity_id")
large, noisy = entities["sensor.large"], entities["sensor.noisy"]
assert noisy["states_bytes"] == pytest.approx(9 * large["states_bytes"], abs=9)
# JSON lengths in bytes; the noisy states share one attributes row
assert large["attributes_bytes"] / noisy["attributes_bytes"] == pytest.approx(
4011 / 511, rel=0.01
)
@pytest.mark.usefixtures("skip_without_table_sizes")
async def test_database_usage_shared_attributes(
recorder_mock: Recorder, hass: HomeAssistant
) -> None:
"""Test an attributes row shared by entities is split by their states."""
for value in range(3):
hass.states.async_set("sensor.busy", str(value), POWER_ATTRIBUTES)
hass.states.async_set("sensor.quiet", "1", POWER_ATTRIBUTES)
await async_wait_recording_done(hass)
usage = await recorder_mock.async_add_executor_job(
get_database_usage, recorder_mock
)
_assert_spread(usage, "state_attributes")
entities = _by_id(usage["entities"], "entity_id")
assert entities["sensor.busy"]["attributes_bytes"] == pytest.approx(
3 * entities["sensor.quiet"]["attributes_bytes"], abs=4
)
def _purge_entity(instance: Recorder, entity_id: str) -> None:
"""Delete the states and metadata of an entity on another connection."""
engine = create_engine(get_engine_db_url(instance.db_url))
try:
with engine.begin() as connection:
metadata_id = connection.execute(
select(StatesMeta.metadata_id).where(StatesMeta.entity_id == entity_id)
).scalar_one()
connection.execute(
update(States)
.where(States.metadata_id == metadata_id)
.values(old_state_id=None)
)
connection.execute(delete(States).where(States.metadata_id == metadata_id))
connection.execute(
delete(StatesMeta).where(StatesMeta.metadata_id == metadata_id)
)
finally:
engine.dispose()
@pytest.mark.parametrize("persistent_database", [True])
async def test_database_usage_snapshot(
recorder_mock: Recorder, hass: HomeAssistant
) -> None:
"""Test a purge during the report does not change what it reads."""
await _record_data(hass)
def purge_during_report(session: Session, dialect: SupportedDialect) -> None:
_begin_snapshot(session, dialect)
# Anchor the snapshot before the purge; pysqlite defers BEGIN to the
# first read
session.execute(select(States.state_id).limit(1))
_purge_entity(recorder_mock, "sensor.busy")
with patch(
"homeassistant.components.recorder.database_usage._begin_snapshot",
side_effect=purge_during_report,
):
usage = await recorder_mock.async_add_executor_job(
get_database_usage, recorder_mock
)
assert {(row["entity_id"], row["states"]) for row in usage["entities"]} == {
("sensor.busy", 10),
("sensor.quiet", 1),
}
report = await recorder_mock.async_add_executor_job(
get_database_usage, recorder_mock
)
# The attributes of the purged entity are left without a state
assert {(row["entity_id"], row["states"]) for row in report["entities"]} == {
("sensor.quiet", 1),
(None, 0),
}
def _mysql_session(
is_mariadb: bool, file_per_table: int
) -> tuple[MagicMock, list[tuple[Any, ...]]]:
"""Return a session that answers the MySQL size queries, and its statements."""
tables = [
("states", 1000, 100),
("events", 500, 100),
("statistics", 200, 30),
]
results = {
"@@SESSION.information_schema_stats_expiry": Mock(
scalar_one=Mock(return_value=86400)
),
"information_schema_stats_expiry = 0": Mock(),
"information_schema_stats_expiry = :expiry": Mock(),
"information_schema.tables": Mock(all=Mock(return_value=tables)),
"@@innodb_file_per_table": Mock(scalar_one=Mock(return_value=file_per_table)),
}
executed: list[tuple[Any, ...]] = []
def execute(statement: Any, *args: Any) -> Mock:
key = next(key for key in results if key in str(statement))
executed.append((key, *args))
return results[key]
session = MagicMock()
session.get_bind.return_value.dialect.is_mariadb = is_mariadb
session.execute.side_effect = execute
return session, executed
@pytest.mark.parametrize(
("file_per_table", "free_bytes"),
[
pytest.param(1, 230, id="file_per_table"),
pytest.param(0, 100, id="shared_tablespace"),
],
)
@pytest.mark.parametrize(
("is_mariadb", "statements"),
[
pytest.param(
False,
[
("@@SESSION.information_schema_stats_expiry",),
("information_schema_stats_expiry = 0",),
("information_schema.tables",),
("information_schema_stats_expiry = :expiry", {"expiry": 86400}),
("@@innodb_file_per_table",),
],
id="mysql",
),
pytest.param(
True,
[("information_schema.tables",), ("@@innodb_file_per_table",)],
id="mariadb",
),
],
)
def test_mysql_free_bytes(
is_mariadb: bool,
statements: list[tuple[Any, ...]],
file_per_table: int,
free_bytes: int,
) -> None:
"""Test MySQL counts a shared InnoDB tablespace once and reads fresh sizes."""
session, executed = _mysql_session(is_mariadb, file_per_table)
assert _mysql_table_bytes(session) == (
{"states": 1000, "events": 500, "statistics": 200},
1700 + free_bytes,
free_bytes,
)
assert executed == statements
@pytest.mark.parametrize(
"url",
[
pytest.param("sqlite:///{}", id="path"),
pytest.param("sqlite:///file:{}?uri=true", id="uri"),
],
)
def test_sqlite_wal_bytes(tmp_path: Path, url: str) -> None:
"""Test the WAL is measured next to the file SQLite opened."""
engine = create_engine(url.format(tmp_path / "test.db"))
with Session(engine) as session:
session.execute(text("PRAGMA journal_mode=WAL"))
session.execute(text("CREATE TABLE test (value TEXT)"))
session.commit()
wal_bytes = _sqlite_wal_bytes(session)
# Closing the last connection checkpoints and removes the WAL files
files_bytes = sum(
path.stat().st_size
for path in (tmp_path / "test.db-wal", tmp_path / "test.db-shm")
)
engine.dispose()
assert wal_bytes == files_bytes > 0
def test_sqlite_wal_bytes_in_memory() -> None:
"""Test an in-memory database has no WAL to measure."""
engine = create_engine("sqlite://")
with Session(engine) as session:
assert _sqlite_wal_bytes(session) is None
engine.dispose()
def _add_orphan_attributes(instance: Recorder) -> None:
"""Add an attributes row without a state."""
with session_scope(session=instance.get_session()) as session:
session.add(StateAttributes(shared_attrs='{"orphan":true}', hash=1))
@pytest.mark.parametrize(
("orphan", "unattributed"),
[
pytest.param(False, set(), id="no_orphan"),
pytest.param(True, {(None, 0, None, None)}, id="orphan"),
],
)
@pytest.mark.skip_on_db_engine(["mysql", "postgresql"])
@pytest.mark.usefixtures("skip_by_db_engine")
async def test_database_usage_without_dbstat(
recorder_mock: Recorder,
hass: HomeAssistant,
orphan: bool,
unattributed: set[tuple[None, int, None, None]],
) -> None:
"""Test SQLite without dbstat reports row counts without table sizes."""
await _record_data(hass)
if orphan:
await recorder_mock.async_add_executor_job(
_add_orphan_attributes, recorder_mock
)
with (
patch(
"homeassistant.components.recorder.database_usage.SQLITE_DBSTAT_QUERY",
"SELECT * FROM no_such_table",
),
patch(
"homeassistant.components.recorder.database_usage._attribute_lengths"
) as mock_attribute_lengths,
):
usage = await recorder_mock.async_add_executor_job(
get_database_usage, recorder_mock
)
# Attribute sizes are only spread over table bytes
mock_attribute_lengths.assert_not_called()
assert usage["tables"] is None
assert usage["total_bytes"] > 0
assert usage["free_bytes"] is not None
assert {
(row["entity_id"], row["states"], row["states_bytes"], row["attributes_bytes"])
for row in usage["entities"]
} == {
("sensor.busy", 10, None, None),
("sensor.quiet", 1, None, None),
} | unattributed
assert {
(row["statistic_id"], row["statistics_bytes"]) for row in usage["statistics"]
} == {("sensor.busy", None), ("test:external", None)}
@pytest.mark.skip_on_db_engine(["mysql", "postgresql"])
@pytest.mark.usefixtures("skip_by_db_engine")
async def test_database_usage_dbstat_error(
recorder_mock: Recorder, hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test other SQLite errors are not mistaken for a missing dbstat."""
client = await hass_ws_client()
with patch(
"homeassistant.components.recorder.database_usage.SQLITE_DBSTAT_QUERY",
"SELECT * FROM",
):
await client.send_json_auto_id(
{"type": "recorder/database_usage", "refresh": True}
)
response = await client.receive_json()
assert not response["success"]
@pytest.mark.parametrize(
("elapsed", "runs"),
[
pytest.param(REFRESH_INTERVAL - timedelta(seconds=1), 1, id="too_soon"),
pytest.param(REFRESH_INTERVAL, 2, id="refresh"),
],
)
@pytest.mark.usefixtures("recorder_mock")
async def test_database_usage_refresh_interval(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
freezer: FrozenDateTimeFactory,
elapsed: timedelta,
runs: int,
) -> None:
"""Test a refresh shortly after the last one returns that report."""
client = await hass_ws_client()
freezer.move_to(START)
with patch(
"homeassistant.components.recorder.database_usage.get_database_usage",
wraps=get_database_usage,
) as mock_usage:
await _async_usage(client, refresh=True)
freezer.tick(elapsed)
result = await _async_usage(client, refresh=True)
assert mock_usage.call_count == runs
assert result["generated_at"] == (START + elapsed * (runs - 1)).isoformat()
@pytest.mark.usefixtures("recorder_mock")
async def test_database_usage_cached(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test a report is kept for an hour and never started without refresh."""
client = await hass_ws_client()
freezer.move_to(START)
with patch(
"homeassistant.components.recorder.database_usage.get_database_usage",
wraps=get_database_usage,
) as mock_usage:
assert await _async_usage(client) is None
report = await _async_usage(client, refresh=True)
freezer.tick(CACHE_TIME - timedelta(seconds=1))
async_fire_time_changed(hass)
assert await _async_usage(client) == report
freezer.tick(timedelta(seconds=1))
async_fire_time_changed(hass)
assert await _async_usage(client) is None
assert mock_usage.call_count == 1
@pytest.mark.usefixtures("recorder_mock")
async def test_database_usage_slow_run(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test a run is dated and kept from when it finished."""
client = await hass_ws_client()
freezer.move_to(START)
slow = timedelta(minutes=10)
def slow_begin_snapshot(session: Session, dialect: SupportedDialect) -> None:
_begin_snapshot(session, dialect)
freezer.tick(slow)
with patch(
"homeassistant.components.recorder.database_usage._begin_snapshot",
side_effect=slow_begin_snapshot,
):
report = await _async_usage(client, refresh=True)
assert report["generated_at"] == (START + slow).isoformat()
assert report["duration"] == slow.total_seconds()
freezer.tick(CACHE_TIME - timedelta(seconds=1))
async_fire_time_changed(hass)
assert await _async_usage(client) == report
@pytest.mark.usefixtures("recorder_mock")
async def test_database_usage_single_flight(hass_ws_client: WebSocketGenerator) -> None:
"""Test concurrent refresh requests share one run."""
client = await hass_ws_client()
release = threading.Event()
def blocked_usage(instance: Recorder) -> DatabaseUsage:
release.wait()
return get_database_usage(instance)
with patch(
"homeassistant.components.recorder.database_usage.get_database_usage",
side_effect=blocked_usage,
) as mock_usage:
for _ in range(2):
await client.send_json_auto_id(
{"type": "recorder/database_usage", "refresh": True}
)
try:
# Messages are handled in order, so both requests wait once the pong is back
await client.send_json_auto_id({"type": "ping"})
assert (await client.receive_json())["type"] == "pong"
finally:
release.set()
responses = [await client.receive_json() for _ in range(2)]
assert mock_usage.call_count == 1
assert all(response["success"] for response in responses)
assert responses[0]["result"] == responses[1]["result"]
@pytest.mark.usefixtures("recorder_mock")
async def test_database_usage_cancelled_request(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test a cancelled request does not cancel the run another request waits for."""
client = await hass_ws_client()
release = threading.Event()
def blocked_usage(instance: Recorder) -> DatabaseUsage:
release.wait()
return get_database_usage(instance)
with patch(
"homeassistant.components.recorder.database_usage.get_database_usage",
side_effect=blocked_usage,
) as mock_usage:
for _ in range(2):
await client.send_json_auto_id(
{"type": "recorder/database_usage", "refresh": True}
)
try:
# Messages are handled in order, so both requests wait once the pong is back
await client.send_json_auto_id({"type": "ping"})
assert (await client.receive_json())["type"] == "pong"
cancelled, waiting = (
task
for task in asyncio.all_tasks()
if task.get_name() == "websocket_api.async:ws_database_usage"
)
cancelled.cancel()
finally:
release.set()
await hass.async_block_till_done(wait_background_tasks=True)
assert cancelled.cancelled()
assert not waiting.cancelled()
# The ping is answered after the result of the request still waiting
await client.send_json_auto_id({"type": "ping"})
response = await client.receive_json()
assert response["type"] == "result"
assert response["success"]
assert (await client.receive_json())["type"] == "pong"
assert mock_usage.call_count == 1
assert await _async_usage(client) == response["result"]
@pytest.mark.usefixtures("recorder_mock")
async def test_database_usage_error_not_cached(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test a failed run is not cached and the next request runs again."""
client = await hass_ws_client()
with patch(
"homeassistant.components.recorder.database_usage.get_database_usage",
side_effect=SQLAlchemyError,
):
await client.send_json_auto_id(
{"type": "recorder/database_usage", "refresh": True}
)
response = await client.receive_json()
assert not response["success"]
assert await _async_usage(client) is None
assert (await _async_usage(client, refresh=True))["total_bytes"] > 0
async def test_database_usage_during_migration(
recorder_mock: Recorder, hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test a refresh is refused without waiting for an offline migration."""
client = await hass_ws_client()
with (
patch.object(recorder_mock, "migration_in_progress", True),
patch.object(recorder_mock, "async_db_ready", hass.loop.create_future()),
):
await client.send_json_auto_id(
{"type": "recorder/database_usage", "refresh": True}
)
response = await client.receive_json()
assert not response["success"]
assert response["error"]["code"] == "migration_in_progress"
@pytest.mark.parametrize("future", ["async_db_connected", "async_db_ready"])
async def test_database_usage_cancelled_during_startup(
recorder_mock: Recorder,
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
future: str,
) -> None:
"""Test a request cancelled during startup does not cancel recorder setup."""
client = await hass_ws_client()
pending: asyncio.Future[bool] = hass.loop.create_future()
with patch.object(recorder_mock, future, pending):
await client.send_json_auto_id(
{"type": "recorder/database_usage", "refresh": True}
)
await client.send_json_auto_id({"type": "ping"})
assert (await client.receive_json())["type"] == "pong"
(task,) = (
task
for task in asyncio.all_tasks()
if task.get_name() == "websocket_api.async:ws_database_usage"
)
task.cancel()
await hass.async_block_till_done(wait_background_tasks=True)
assert task.cancelled()
assert not pending.done()
@pytest.mark.usefixtures("recorder_mock")
async def test_database_usage_requires_admin(
hass_ws_client: WebSocketGenerator, hass_read_only_access_token: str
) -> None:
"""Test a non-admin user cannot read the report."""
client = await hass_ws_client(access_token=hass_read_only_access_token)
await client.send_json_auto_id({"type": "recorder/database_usage"})
response = await client.receive_json()
assert not response["success"]
assert response["error"]["code"] == "unauthorized"
async def test_database_usage_waits_for_database_ready(
async_test_recorder: RecorderInstanceContextManager,
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test a refresh during startup waits until the database is ready."""
client = await hass_ws_client()
recorder_helper.async_initialize_recorder(hass)
async with async_test_recorder(
hass, wait_recorder=False, wait_recorder_setup=False
):
await client.send_json_auto_id(
{"type": "recorder/database_usage", "refresh": True}
)
response = await client.receive_json()
# A stop queued before the recorder runs its event loop is lost
await async_wait_recording_done(hass)
assert response["success"]
assert response["result"]["total_bytes"] > 0
async def test_database_usage_recorder_failed(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test an error is returned when the recorder failed to start."""
client = await hass_ws_client()
with patch("homeassistant.components.recorder.migration._migrate_schema"):
recorder_helper.async_initialize_recorder(hass)
assert not await async_setup_component(
hass,
recorder.DOMAIN,
{
recorder.DOMAIN: {
recorder.CONF_DB_URL: "sqlite:////no_dir/no_file.db",
recorder.CONF_DB_RETRY_WAIT: 0,
}
},
)
await hass.async_add_executor_job(recorder.get_instance(hass).join)
await client.send_json_auto_id({"type": "recorder/database_usage", "refresh": True})
response = await client.receive_json()
assert not response["success"]
assert response["error"]["code"] == "recorder_not_ready"