Skip to content

fix(code_run): 固定 sleep(1) 轮询导致每次工具调用白等最多 1 秒 #875

Open

Description

@leonsong09

现象

code_run 每次调用都要多等最多 1 秒才能拿到结果,即使子进程 50ms 就跑完了。

根因

ga.py 的 code_run() 用固定间隔轮询看进程是否结束:

while t.is_alive():
    ...
    time.sleep(1)      # ← 只看一眼就睡满 1 秒

子进程在第 0.05s 结束,线程也立刻退出了,但主线程还在 sleep(1) 里,必须睡完才回到 is_alive() 发现线程没了。这段等待完全是空转,不产生任何工作。

实测数据

产物侧写,非估算:

  1. 响应间隔直方图:temp/model_responses/*.txt 里 5,187 个 Response → 下一条 Prompt 间隔,p50 恰好 = 1.000s;其中 2,012 次精确等于 1.000s,按 tool_use_id 归因,code_run 占 1,912 次(95%)。

  2. 对照实验(纯内存,同一份 code_run 源码跑 old/new 两版):

场景 旧 sleep(1) 新 t.join(0.05)
短脚本 print('hi') 1.010s 0.245s
3000 行输出 1.010s 0.400s
sys.exit(7) 1.011s / exit=7 0.240s / exit=7
超时用例(script sleep 10s, timeout=2) 2.01s 2.03s

即短工具调用固定损失约 0.77s,长输出约 0.61s,超时与退出码语义不变。

期望

子进程一退出就返回,不再固定睡满 1 秒。

补充说明(我第一版补丁踩到的坑,供评审参考)

只把 time.sleep(1) 换成 t.join(0.05) 会引入新 bug:reader 线程可能先于进程回收退出,此时 process.poll() 仍返回 None,结果 exit_code 变成 None(状态被判成 ⏳ 而非 error/success)。所以必须补 process.wait() 兜底——这正是我最初单行改动在自测里挂掉的原因。

Activity

  1. leonsong09 commented on Nov 14, 2026

    @leonsong09
    Author

    Folded into #880 (commit 5 of 6, ga.py +4/-1). The measurement and the process.wait() fallback rationale are preserved verbatim in that PR's description.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions