subprocess: Popen.wait(timeout) raises TimeoutExpired early when the kqueue/pidfd fast path falls back to polling
Mantenedores costumam responder em até 1 dia
Ninguém assumiu esta issue ainda.
Avaliação
- Dificuldade
- 2/5
- Tempo estimado
- 1-3 horas
- Facilidade para iniciantes
- 72/100
- Tipo de issue
- Bug
- Clareza
- Claramente especificada
- Status de atividade
- Ativa
- Stack de tecnologia
- macos, python
- Domínio
- operating-systems
Direção de pesquisa
Comece em Lib/subprocess.py, em Popen._wait, onde endtime é calculado a partir de started e o ajuste endtime -= elapsed é executado após o fallback para polling com _wait_kqueue()/_wait_pidfd(). Execute o reprodutor da issue, que força as duas primeiras chamadas de _try_wait a retornar (0, 0), e confirme que ele lança TimeoutExpired por volta de 2 s. Está concluído quando rc 7 é impresso após cerca de 2 s e um teste de regressão é adicionado em Lib/test/test_subprocess.py.
Escrita pelo modelo de indexação a partir do texto da issue.
Descrição
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
- Linguagem predominante
- Python
- Estrelas
- 78.4k
- Forks
- 36.6k
- Merge médio
- 23h 34min
- PRs com merge (30d)
- 610
Preparar o ambiente
Inicia o contêiner de desenvolvimento do projeto no navegador, com a sua própria conta do GitHub.
- Sem Dockerfile nem arquivo Docker Compose
- Tem um modelo de pull request
- Ler o guia de contribuição
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Mais de python/cpython
-
interpreter-core type-bug
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 62/100
Mantenedores costumam responder em até 1 dia
-
corner case: base64.b32decode ignorechars=b'=' miscounts paddingTalvez já em andamento @ElDShell assumiu hoje. Aberta3.15 easy type-bug
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 62/100
python/cpython#162353 · 1 comentário ·
Mantenedores costumam responder em até 1 dia
-
TracebackException.lineno changes from str to int after format() when a keyword typo suggestion is foundTalvez já em andamento @Sudhakar7J assumiu há 2 dias. Abertastdlib type-bug
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 67/100
python/cpython#162296 · 1 comentário ·
Mantenedores costumam responder em até 1 dia
-
[HACL] The `HACL_CAN_COMPILE_VEC128` macro is not defined when building Python with `-Wundef`Talvez já em andamento @tamaki0575-cloud assumiu há 1 dia. Abertabuild extension-modules topic-C-API type-bug
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 64/100
python/cpython#162219 · 2 comentários ·
Mantenedores costumam responder em até 1 dia
-
zipfile: ZipInfo.comment exceeding 65535 bytes causes struct.error in ZipFile.close() without proper validationTalvez já em andamento @1cbyc assumiu há 5 dias. Abertastdlib type-bug
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 75/100
Mantenedores costumam responder em até 1 dia
Todas as issues de python/cpython
Issues semelhantes
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 68/100
vllm-project/vllm#69304 · 1 comentário ·
Mantenedores costumam responder em até 1 dia
-
pydanty:is-working
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 68/100
pydantic/pydantic-ai#14187 ·
Mantenedores costumam responder em até 1 dia
-
bug
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 62/100
Mantenedores costumam responder em até 1 dia
-
test
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 62/100
prebid/salesagent#2676 ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 1/5 1-3 horas Facilidade para iniciantes 62/100
sunososobro-hub/cloudball#339 ·
Mantenedores costumam responder em até 1 dia