core: Main loop blocked when parsing very large calendars

The problem

I noticed my android or web clients were getting disconnected regularly

EDIT: the info below is incorrect and unrelated to the freebox integration, i have edited the title accordingly, see https://github.com/home-assistant/core/issues/131743#issuecomment-2568177280 for an updated analysis.

Upon inspection, it seems that when this happens, there is an exception in the HA core logs, related to the freebox integration. I also noticed that the device trackers were not working properly lately (e.g. not detecting my smartphone as home, or the opposite).

For the record, my freebox integration provides 193 entities, including 38 enabled ones.

Why would such an error shut me out of the app: does the websocket timeout because the mainloop is blocked ? Would that mean the all calls are not async / threaded ?

What version of Home Assistant Core has the issue?

core-2024.11.3

What was the last working version of Home Assistant Core?

No response

What type of installation are you running?

Home Assistant OS

Integration causing the issue

freebox

Link to integration documentation on our website

https://www.home-assistant.io/integrations/freebox/

Diagnostics information

No response

Example YAML snippet

No response

Anything in the logs that might be useful for us?

Today, got this one (and got kicked out by the app):



2024-11-27 17:46:17.076 ERROR (MainThread) [homeassistant] Error doing job: Task exception was never retrieved (None)
Traceback (most recent call last):
  File "/usr/local/lib/python3.12/site-packages/aiohttp/client_reqrep.py", line 1059, in start
    message, payload = await protocol.read()  # type: ignore[union-attr]
                       ^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/aiohttp/streams.py", line 644, in read
    await self._waiter
asyncio.exceptions.CancelledError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/freebox/router.py", line 130, in update_all
    await self.update_device_trackers()
  File "/usr/src/homeassistant/homeassistant/components/freebox/router.py", line 142, in update_device_trackers
    self.supports_hosts, fbx_devices = await get_hosts_list_if_supported(
                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/freebox/router.py", line 75, in get_hosts_list_if_supported
    fbx_devices = await fbx_api.lan.get_hosts_list() or []
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/freebox_api/api/lan.py", line 64, in get_hosts_list
    return await self._access.get(f"lan/browser/{interface}")
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/freebox_api/access.py", line 122, in get
    return await self._perform_request(self.session.get, end_url)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/freebox_api/access.py", line 94, in _perform_request
    r = await verb(url, **request_params)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/aiohttp/client.py", line 690, in _request
    await resp.start(conn)
  File "/usr/local/lib/python3.12/site-packages/aiohttp/client_reqrep.py", line 1054, in start
    with self._timer:
  File "/usr/local/lib/python3.12/site-packages/aiohttp/helpers.py", line 749, in __exit__
    raise asyncio.TimeoutError from exc_val
TimeoutError

But i also noticed others:

2024-11-25 20:08:38.062 ERROR (MainThread) [homeassistant.helpers.entity] Update for switch.freebox_wifi fails 
Traceback (most recent call last):
  File "/usr/local/lib/python3.12/site-packages/aiohttp/client.py", line 663, in _request
    conn = await self._connector.connect(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/aiohttp/connector.py", line 538, in connect
    proto = await self._create_connection(req, traces, timeout)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
  File "/usr/local/lib/python3.12/site-packages/aiohttp/connector.py", line 1050, in _create_connection
    _, proto = await self._create_direct_connection(req, traces, timeout)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/aiohttp/connector.py", line 1353, in _create_direct_connection
    transp, proto = await self._wrap_create_connection( 
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
  File "/usr/local/lib/python3.12/site-packages/aiohttp/connector.py", line 1109, in _wrap_create_connection
    sock = await aiohappyeyeballs.start_connection(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/aiohappyeyeballs/impl.py", line 89, in start_connection
    sock, _, _ = await _staggered.staggered_race(
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/aiohappyeyeballs/_staggered.py", line 160, in staggered_race
    done = await _wait_one(
           ^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/aiohappyeyeballs/_staggered.py", line 41, in _wait_one
    return await wait_next
           ^^^^^^^^^^^^^^^
asyncio.exceptions.CancelledError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 944, in async_update_ha_state
    await self.async_device_update()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 1302, in async_device_update
    await self.async_update() 
  File "/usr/src/homeassistant/homeassistant/components/freebox/switch.py", line 75, in async_update
    data = await self._router.wifi.get_global_config()
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/freebox_api/api/wifi.py", line 132, in get_global_config
    return await self._access.get("wifi/config/")
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/freebox_api/access.py", line 122, in get
    return await self._perform_request(self.session.get, end_url)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/freebox_api/access.py", line 94, in _perform_request
    r = await verb(url, **request_params)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/aiohttp/client.py", line 578, in _request
    with timer:
  File "/usr/local/lib/python3.12/site-packages/aiohttp/helpers.py", line 749, in __exit__
    raise asyncio.TimeoutError from exc_val
TimeoutError

And also:

2024-11-25 20:23:56.046 ERROR (MainThread) [homeassistant] Error doing job: Task exception was never retrieved (None)
Traceback (most recent call last):
  File "/usr/local/lib/python3.12/site-packages/aiohttp/client_reqrep.py", line 1059, in start
    message, payload = await protocol.read()  # type: ignore[union-attr]
                       ^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/aiohttp/streams.py", line 644, in read
    await self._waiter
asyncio.exceptions.CancelledError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/freebox/router.py", line 131, in update_all
    await self.update_sensors()
  File "/usr/src/homeassistant/homeassistant/components/freebox/router.py", line 175, in update_sensors
    syst_datas: dict[str, Any] = await self._api.system.get_config()
                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/freebox_api/api/system.py", line 9, in get_config
    return await self._access.get("system/")
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/freebox_api/access.py", line 122, in get
    return await self._perform_request(self.session.get, end_url)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/freebox_api/access.py", line 94, in _perform_request
    r = await verb(url, **request_params)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/aiohttp/client.py", line 690, in _request
    await resp.start(conn)
  File "/usr/local/lib/python3.12/site-packages/aiohttp/client_reqrep.py", line 1054, in start
    with self._timer:
  File "/usr/local/lib/python3.12/site-packages/aiohttp/helpers.py", line 749, in __exit__
    raise asyncio.TimeoutError from exc_val
TimeoutError
2024-11-25 20:


### Additional information

_No response_

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 34 (31 by maintainers)

Most upvoted comments

Also confirmed that with debug logging enabled, then 70% of the performance is due to debug logging, even with these fixes. Enabling debug logging will definitely produce a lot of data and greatly exaggerate things given its making so many log entries for each of those 9k records. (e.g. w/ 3 log entries its like 27k log lines). We can consider reducing the amount of debug logging here, but i think its OK as is.

Appreciate the enthusiasm, though just wanted to clarify there are plenty of options for optimization here, it’s not a mystery, just haven’t explained them here. Since you’re interested, i’ll explain more context.

Firstly on pyparsing performance:

  • It’s not really that strange becausethat is the primary loop evaluating the grammar. It’s a loop through all the expressions so all evaluations should be happening there. It just shows up as a single place in the profiler because it doesn’t have the detail of which expressions are causing the most attribution. That said they have some performance tips and i’ve reviewed/applied them and they did not help. There are discussions in the pyparsing github issue sabout possibly exploring rust in the future that the author was looking into in their spare time. I don’t think we need to report anything.
  • I knew when adopting pyparsing that it was not super fast. This is not surprising at all. The motivation was to ensure we have a correct rfc5545 grammar since my observation was that many projects were using heuristics that resulted in unsupported features or bugs.
  • That said, I may explore rewriting it as hand rolled heuristics, but then using the pyparsing grammar for ensuring everything is working at testing time by running all code through both approaches. This way I can still ensure its correct, but more performant.
  • There may be a way to improve the ical grammar but i haven’t seen it yet. I’m assuming the complicated parts are the groups and parameter extractions and the need to list_all_matches.
  • In the short term, i’m going to break out a special case for the RRULE parser since it only needs a subset of the entire grammar just to parse rrules for gcal. I looked at the dateutil rrule grammar and it isn’t as bare bones as it needs to be to be reusable in this context.

Regarding incremental building:

  • Google calendar sync is incremental. Here are the design details. It syncs deltas from the servers and writes them into local storage
  • Once data is synced, it is written to storage. This step invalidates the in memory calendar
  • Then it re-creates the in memory calendar, re-reading the content. This is the part we’re talking about here. I’ve been looking at what it might take to not do this invalidation – similar to how local calendar works. This is just a change i avoided before to avoid unnecessarily prematurely optimizing things.

Regarding if this is necessary: Appreciate @fthiery your concessions, but we think this is reasonable to optimize. Usually outliers like this are helpful to identify bottlenecks that we can fix to make the system also more performant in the common case. We can make this case work well, and the improvements will benefit everyone. While it could be small on its own, these little things add up across the system.

Appreciate all the work you put into diagnosis here, one of the best but most detailed reports I’ve seen, thank you.