[client] get_devices_ts_time_ago: document or serialize the concurrent re-auth race (shared session) #182

Closed
opened 2026-10-27 11:31:55 +00:00 by mat · 0 comments
Owner

get_devices_ts_time_ago (_batch.py) fans out get_device_ts_time_ago over a ThreadPoolExecutor, sharing the single requests.Session across worker threads. The docstring already notes that requests gives "no official guarantee" for thread-safety, but a sharper unstated risk exists:

With auto_reauth enabled, a 401 mid-flight makes every worker hit _request's re-auth branch (_core.py:98-104) and call _reauthenticate() concurrently — a cookie-jar race with N duplicate logins and partially-overwritten session state, right when the session just expired and every request is failing.

Options (pick one):

  • Serialize re-auth: guard _reauthenticate() with a threading.Lock so one thread re-authenticates while the others wait, then retry — small change, no API impact; or
  • Pre-authenticate before fan-out: call _reauthenticate_if_expired() once before spawning workers, and document the residual race; or
  • Document only: state the limitation in the docstring.

Done when: chosen option implemented; a test simulates a 401 on the first worker and asserts a single re-auth call; docstring updated accordingly.

`get_devices_ts_time_ago` (`_batch.py`) fans out `get_device_ts_time_ago` over a `ThreadPoolExecutor`, sharing the single `requests.Session` across worker threads. The docstring already notes that `requests` gives "no official guarantee" for thread-safety, but a sharper unstated risk exists: With `auto_reauth` enabled, a 401 mid-flight makes every worker hit `_request`'s re-auth branch (`_core.py:98-104`) and call `_reauthenticate()` concurrently — a cookie-jar race with N duplicate logins and partially-overwritten session state, right when the session just expired and every request is failing. **Options (pick one):** - **Serialize re-auth:** guard `_reauthenticate()` with a `threading.Lock` so one thread re-authenticates while the others wait, then retry — small change, no API impact; or - **Pre-authenticate before fan-out:** call `_reauthenticate_if_expired()` once before spawning workers, and document the residual race; or - **Document only:** state the limitation in the docstring. **Done when:** chosen option implemented; a test simulates a 401 on the first worker and asserts a single re-auth call; docstring updated accordingly.
mat closed this issue 2026-10-27 14:37:13 +00:00
Sign in to join this conversation.
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
mat/python-comwatt-client#182
No description provided.