Access token expires mid-batch despite refresh logic

Running a batch job to update contact attributes via /api/v2/contacts. The script handles the initial token fetch fine. It starts processing and then fails halfway through with a 401 Unauthorized. The refresh token logic is supposed to kick in when status is 401. It’s not triggering. Here is the loop structure:

while contacts:
 try:
 resp = session.post(url, json=batch)
 except requests.exceptions.HTTPError as e:
 if e.response.status_code == 401:
 refresh_token()
 continue

The 401 happens on the request before the check. The token is already dead when the call goes out.