Skip to content

fix(funasr): fix race condition in suppress_stdout causing startup crash#53

Open
wei-yao wants to merge 1 commit intoyan5xu:mainfrom
wei-yao:fix/suppress-stdout-race-condition
Open

fix(funasr): fix race condition in suppress_stdout causing startup crash#53
wei-yao wants to merge 1 commit intoyan5xu:mainfrom
wei-yao:fix/suppress-stdout-race-condition

Conversation

@wei-yao
Copy link
Copy Markdown

@wei-yao wei-yao commented Mar 3, 2026

Problem

On startup, FunASR models finish loading but the server immediately crashes with:

ValueError: I/O operation on closed file
  File "funasr_server.py", line 471, in run
    print(json.dumps(init_result, ensure_ascii=False))

The app gets stuck showing "模型加载中" indefinitely.

Root Cause

suppress_stdout() saves and restores the global sys.stdout to suppress noise from FunASR/modelscope during model initialization. Since three models (ASR, VAD, punc) load in parallel threads, each thread calls suppress_stdout() concurrently — causing a race condition:

Step Thread A (ASR) Thread B (VAD) sys.stdout
1 old_A = sys.stdout (real pipe) real pipe
2 sys.stdout = devnull_A devnull_A
3 old_B = sys.stdoutcaptures devnull_A devnull_A
4 sys.stdout = devnull_B devnull_B
5 (done) sys.stdout = old_A, devnull_A.close() real pipe
6 (done) sys.stdout = old_Bclosed devnull_A closed file

After all threads complete, sys.stdout points to a closed file, so any subsequent print() raises ValueError.

Fix

Restore to sys.__stdout__ (Python's original stdout) instead of the locally saved reference. This is always stable regardless of thread interleaving.

# before
finally:
    sys.stdout = old_stdout
    devnull.close()

# after
finally:
    sys.stdout = sys.__stdout__
    devnull.close()

When three model-loading threads run in parallel, each calls suppress_stdout()
which saves and restores sys.stdout. Due to interleaving, one thread could
capture another thread's devnull as its old_stdout, and later restore to a
closed file — causing `ValueError: I/O operation on closed file` when the
server tried to print the init result.

Fix by restoring to sys.__stdout__ (Python's original stdout) instead of the
locally saved reference, which is always stable regardless of thread order.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant