-
Notifications
You must be signed in to change notification settings - Fork 0
Description
Is there an existing issue for this?
- I have searched the existing issues
What happened?
What Happened?
Bug Description
A Time-of-Check to Time-of-Use (TOCTOU) race condition exists in sync-microservice/app/utils/watcher.py. This issue allows multiple background watcher threads to be created simultaneously, resulting in duplicated sync events, corrupted shared state, and potential memory leaks.
Root Cause
The global variables responsible for managing watcher state (watcher_thread, watched_folders, folder_id_map) are modified across asynchronous API requests without proper thread synchronization (i.e., no threading.Lock() protection).
During the startup flow, I/O operations (such as database and filesystem checks) release the Python GIL. If the /start endpoint receives concurrent requests, both requests may pass the watcher_util_is_watcher_running() check before the first request assigns a value to watcher_thread.
As a result, multiple watchfiles processes can be initialized concurrently for the same directories.
Proposed Fix
To ensure thread safety, introduce a global lock:
state_lock = threading.Lock()
Wrap the critical sections inside the following functions:
watcher_util_start_folder_watcher
watcher_util_stop_folder_watcher
watcher_util_restart_folder_watcher
Use a with state_lock: context manager around the code that mutates global watcher state.
Record
- I agree to follow this project's Code of Conduct