subprocess: Popen.wait(timeout) raises TimeoutExpired early when the kqueue/pidfd fast path falls back to polling

Ouverte Adaptée aux débutants
#162,438 0 commentaires 0 réactions 0 personnes assignées Voir sur GitHub

Les mainteneurs répondent en général sous 1 jour

Personne n'a encore pris cette issue.

Évaluation

Difficulté
2/5
Temps estimé
1-3 heures
Accessibilité débutants
72/100
Type d'issue
Bug
Clarté
Clairement spécifiée
Activité
Active
Stack technique
macos, python

Piste de recherche

Commence dans Lib/subprocess.py à Popen._wait, où endtime est calculé à partir de started et où l'ajustement endtime -= elapsed s'exécute après le repli sur l'interrogation via _wait_kqueue()/_wait_pidfd(). Exécute le reproducteur de l'issue, qui force les deux premiers appels à _try_wait à renvoyer (0, 0), et vérifie qu'il lève TimeoutExpired vers 2 s. C'est terminé lorsque rc 7 s'affiche après environ 2 s et qu'un test de non-régression est ajouté dans Lib/test/test_subprocess.py.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Description

stdlib topic-subprocess type-bug
Bug description:

On macOS/BSD, Popen.wait(timeout=T) can raise TimeoutExpired well before T has elapsed. The child has in fact already exited, and its exit status is lost to the caller.

In Popen._wait (Lib/subprocess.py), endtime is an absolute deadline:

started = _time()
endtime = started + timeout

If _wait_kqueue() (or _wait_pidfd()) reports the exit but the first waitpid(WNOHANG) still returns 0, the code falls back to busy polling and does:

elapsed = _time() - started
endtime -= elapsed

Since endtime is already absolute, this moves the deadline earlier by the time already spent. The busy loop then raises TimeoutExpired as soon as now > started + T - elapsed. That is immediately whenever more than half of the timeout had elapsed when the child exited, provided the process is still not reapable on the loop's first poll. The endtime -= elapsed line looks like a leftover from a relative-timeout version of this code, and can simply be removed.

Reproducer. It forces the rare race the fallback exists for by making the first two WNOHANG reaps return (0, 0):

import subprocess, sys, time

p = subprocess.Popen([sys.executable, "-c", "import time, sys; time.sleep(2); sys.exit(7)"])
real, calls = p._try_wait, [0]

def racy(flags):
    if calls[0] < 2:
        calls[0] += 1
        return (0, 0)  # NOTE_EXIT seen, but the child is not reapable yet
    return real(flags)

p._try_wait = racy
t0 = time.monotonic()
try:
    print("rc", p.wait(timeout=3))
except subprocess.TimeoutExpired:
    print(f"TimeoutExpired after {time.monotonic() - t0:.2f}s of a 3 s timeout; child rc {p.wait()}")

Output on 3.15.2:

TimeoutExpired after 2.02s of a 3 s timeout; child rc 7

The expected output is rc 7, after about 2 s.

Without the patch, we hit this in practice on a heavily loaded machine (5-minute load average of about 60 on 16 cores). Long-running child processes with timeouts of about 1,500-1,560 s exited normally at 804-879 s, past half their timeout but well before it, and wait() raised TimeoutExpired at that moment instead of returning their status.

CPython versions tested on:

3.15

Operating systems tested on:

macOS

Langage dominant
Python
Étoiles
78.4k
Forks
36.6k
Merge moyen
23 h 34 min
PR mergées (30 j)
610

Préparer son environnement

Ouvrir dans Codespaces

Lance le conteneur de développement du projet dans votre navigateur, avec votre propre compte GitHub.

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Autres issues de python/cpython

Toutes les issues de python/cpython

Issues similaires

Plus d'issues Python

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.