The last_login query is too long, at 300 days. It only needs to be longer than the maximum login session duration.
The way the groups query is constructed means that every user gets returned, regardless of the last_login date. This results in 40k users getting found, far more than necessary.