bep40 commited on
Commit
4fca660
·
verified ·
1 Parent(s): 777ad4e

Upload patch_fix_session_hang.py

Browse files
Files changed (1) hide show
  1. patch_fix_session_hang.py +396 -0
patch_fix_session_hang.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Definitive fix for "treo session" (hung/stuck session) while executing a task.
2
+
3
+ Root causes (all verified against current upstream smolagents/ml-intern:
4
+ agent_loop.py, local_tools.py, session_manager.py, session.py):
5
+
6
+ 1. BLOCKING SUBPROCESS (#1 mid-task freeze).
7
+ agent/tools/local_tools.py `_bash_handler` runs `subprocess.run(...)`
8
+ synchronously inside an async handler. Because the whole backend is a
9
+ single asyncio event loop, ANY bash command (pip install, a training run,
10
+ a long shell pipeline) freezes the ENTIRE loop: every session's agent loop,
11
+ the SSE fan-out, the reaper, and the cancellation path all stop being
12
+ scheduled. The frontend sees keepalives but zero events, so it shows
13
+ "Processing…" for hours. MAX_TIMEOUT=36000 (10 h) makes it worse.
14
+ Fix: run bash via asyncio.create_subprocess_shell so it never blocks the
15
+ loop, cap MAX_TIMEOUT to a sane 1800 s, and kill the process group on
16
+ either cancel (Stop) or timeout so no orphan keeps running.
17
+
18
+ 2. NO TURN-LEVEL WATCHDOG.
19
+ backend/session_manager.py `_run_session` awaits `process_submission`
20
+ directly with no timeout. Combined with bep40's patch_lossless_context
21
+ setting max_iterations=-1 (unlimited), a turn can run forever (doom loop,
22
+ unkillable tool, connection hang). When a turn hangs, is_processing stays
23
+ True and the idle reaper REFUSES to reap it -> permanent zombie.
24
+ Fix: wrap process_submission in asyncio.wait with a turn timeout (1 h). On
25
+ timeout, cancel the turn, send `interrupted` + `turn_complete` terminal SSE
26
+ events (so the frontend un-freezes), clear the cancel flag so the session
27
+ stays usable, and let it continue on the next message.
28
+
29
+ Design notes / safety:
30
+ - Does NOT change max_iterations semantics. It only adds a hard safety net.
31
+ - Does NOT change the user's task, model, dataset, or training approach.
32
+ - Idempotent: every mutation is guarded by a marker check.
33
+ - Runs in the Python build stage AFTER `uv sync` (needs agent/backend present),
34
+ NEXT TO the other backend patches (patch_lossless_context etc.).
35
+ """
36
+
37
+ import ast
38
+ import os
39
+
40
+ LOCAL_TOOLS = "/app/agent/tools/local_tools.py"
41
+ SESSION_MANAGER = "/app/backend/session_manager.py"
42
+
43
+ M1 = "ML_INTERN_TURN_WATCHDOG"
44
+ M2 = "ML_INTERN_TO_THREAD_BASH"
45
+ M3 = "_cancelled_ok_helper"
46
+
47
+ errors = []
48
+
49
+ NEW_BASH_HANDLER = '''async def _bash_handler(
50
+ args: dict[str, Any], session: Any = None, **_kw
51
+ ) -> tuple[str, bool]:
52
+ """Run a shell command WITHOUT blocking the event loop. # ML_INTERN_TO_THREAD_BASH
53
+ Uses asyncio subprocess + a single wait guard so a long/hung command never
54
+ freezes the whole backend (every session's loop + SSE). On cancel (Stop) or
55
+ timeout the process group is killed so nothing keeps running silently.
56
+ """
57
+ command = args.get("command", "")
58
+ if not command:
59
+ return "No command provided.", False
60
+ command = wrap_shell_command_with_hub_artifact_bootstrap(command, session)
61
+ work_dir = args.get("work_dir", ".")
62
+ timeout = min(args.get("timeout") or DEFAULT_TIMEOUT, MAX_TIMEOUT)
63
+
64
+ cancelled = asyncio.Event()
65
+ if session is not None:
66
+ inner = getattr(session, "_cancelled", None)
67
+ if inner is not None and hasattr(inner, "add_done_callback"):
68
+ inner.add_done_callback(lambda _e, ev=cancelled: ev.set())
69
+
70
+ async def _run() -> tuple[str, bool]:
71
+ # create_subprocess with start_new_session so we can kill the whole
72
+ # process group on cancel/timeout.
73
+ try:
74
+ proc = await asyncio.create_subprocess_shell(
75
+ command,
76
+ cwd=work_dir or ".",
77
+ stdout=asyncio.subprocess.PIPE,
78
+ stderr=asyncio.subprocess.PIPE,
79
+ start_new_session=True,
80
+ )
81
+ except Exception as e:
82
+ return f"bash error (spawn): {e}", False
83
+
84
+ cancel_task = asyncio.ensure_future(cancelled.wait())
85
+
86
+ def _kill_group() -> None:
87
+ try:
88
+ os.killpg(os.getpgid(proc.pid), 9)
89
+ except Exception:
90
+ try:
91
+ proc.kill()
92
+ except Exception:
93
+ pass
94
+
95
+ # communicate() both waits for the process and reads its output, so we
96
+ # use it as the single "process finished" future.
97
+ comm_task = asyncio.ensure_future(proc.communicate())
98
+
99
+ # One single guard: wait for process completion OR cancellation, with the
100
+ # hard per-call deadline applied directly here. asyncio.wait with a
101
+ # timeout returns (done, pending) and does NOT raise on timeout.
102
+ done, pending = await asyncio.wait(
103
+ [comm_task, cancel_task],
104
+ timeout=timeout,
105
+ return_when=asyncio.FIRST_COMPLETED,
106
+ )
107
+ for t in pending:
108
+ t.cancel()
109
+
110
+ if comm_task not in done:
111
+ # Either cancelled, or genuinely timed out -> kill + report.
112
+ comm_task.cancel()
113
+ _kill_group()
114
+ reason = (
115
+ "cancelled"
116
+ if cancel_task in done
117
+ else f"timed out after {timeout}s"
118
+ )
119
+ return (
120
+ f"Command {reason} and was killed.\\n\\n"
121
+ "For long-running commands, run in the background:\\n"
122
+ " nohup <command> > /tmp/output.log 2>&1 & echo $!\\n"
123
+ "Then poll:\\n"
124
+ " kill -0 <PID> 2>/dev/null && echo 'running' || echo 'done'\\n"
125
+ " tail -n 50 /tmp/output.log"
126
+ ), False
127
+
128
+ # Process finished naturally -> read results from the comhpleted future.
129
+ cancel_task.cancel()
130
+ try:
131
+ stdout, stderr = comm_task.result()
132
+ except Exception:
133
+ stdout, stderr = b"", b""
134
+ raw = stdout.decode("utf-8", errors="replace") + stderr.decode(
135
+ "utf-8", errors="replace"
136
+ )
137
+ output = _strip_ansi(raw)
138
+ output = _truncate_output(output)
139
+ if not output.strip():
140
+ output = "(no output)"
141
+ return output, proc.returncode == 0 if proc.returncode is not None else False
142
+
143
+ try:
144
+ return await _run()
145
+ except (asyncio.TimeoutError, asyncio.CancelledError):
146
+ return "Command was cancelled/interrupted.", False
147
+ except Exception as e:
148
+ return f"bash error: {e}", False
149
+ '''
150
+
151
+ OLD_BASH_HANDLER = '''async def _bash_handler(
152
+ args: dict[str, Any], session: Any = None, **_kw
153
+ ) -> tuple[str, bool]:
154
+ command = args.get("command", "")
155
+ if not command:
156
+ return "No command provided.", False
157
+ command = wrap_shell_command_with_hub_artifact_bootstrap(command, session)
158
+ work_dir = args.get("work_dir", ".")
159
+ timeout = min(args.get("timeout") or DEFAULT_TIMEOUT, MAX_TIMEOUT)
160
+ try:
161
+ result = subprocess.run(
162
+ command,
163
+ shell=True,
164
+ capture_output=True,
165
+ text=True,
166
+ cwd=work_dir,
167
+ timeout=timeout,
168
+ )
169
+ output = _strip_ansi(result.stdout + result.stderr)
170
+ output = _truncate_output(output)
171
+ if not output.strip():
172
+ output = "(no output)"
173
+ return output, result.returncode == 0
174
+ except subprocess.TimeoutExpired:
175
+ return (
176
+ f"Command timed out after {timeout}s and was killed.\\n\\n"
177
+ f"For long-running commands, run in the background and poll:\\n"
178
+ f" nohup <command> > /tmp/output.log 2>&1 & echo $!\\n"
179
+ f"Then check status with:\\n"
180
+ f" kill -0 <PID> 2>/dev/null && echo 'running' || echo 'done'\\n"
181
+ f" tail -n 50 /tmp/output.log"
182
+ ), False
183
+ except Exception as e:
184
+ return f"bash error: {e}", False
185
+ '''
186
+
187
+
188
+ # =========================================================================
189
+ # PART 1: local_tools.py -> non-blocking, cancellation-aware bash
190
+ # =========================================================================
191
+ if os.path.exists(LOCAL_TOOLS):
192
+ with open(LOCAL_TOOLS) as f:
193
+ c = f.read()
194
+
195
+ if M2 in c:
196
+ print("OK: local_tools.py already patched (idempotent)")
197
+ else:
198
+ if "import asyncio" not in c:
199
+ c = c.replace(
200
+ "import subprocess\n",
201
+ "import asyncio\nimport subprocess\n",
202
+ 1,
203
+ )
204
+ c = c.replace(
205
+ "MAX_TIMEOUT = 36000 # 10 hours — needed for long training runs (e.g. PostTrainBench)",
206
+ "MAX_TIMEOUT = 1800 # 30 min hard cap; long jobs must run in background (ML Intern)",
207
+ )
208
+
209
+ if OLD_BASH_HANDLER in c:
210
+ c = c.replace(OLD_BASH_HANDLER, NEW_BASH_HANDLER, 1)
211
+ print("OK: _bash_handler replaced with non-blocking cancellable version")
212
+ else:
213
+ start = c.find("async def _bash_handler(")
214
+ end = c.find("async def _read_handler(", start)
215
+ if start >= 0 and end > start:
216
+ c = c[:start] + NEW_BASH_HANDLER + "\n\n" + c[end:]
217
+ print("OK: _bash_handler replaced via region fallback")
218
+ else:
219
+ print("FAIL: could not locate _bash_handler in local_tools.py")
220
+ errors.append("local_tools _bash_handler")
221
+
222
+ with open(LOCAL_TOOLS, "w") as f:
223
+ f.write(c)
224
+ try:
225
+ ast.parse(c)
226
+ print("OK: local_tools.py syntax OK")
227
+ except SyntaxError as e:
228
+ print(f"FAIL: local_tools.py syntax: {e}")
229
+ errors.append("local_tools syntax")
230
+
231
+
232
+ # =========================================================================
233
+ # PART 2: session_manager.py -> turn-level watchdog
234
+ # =========================================================================
235
+ if os.path.exists(SESSION_MANAGER):
236
+ with open(SESSION_MANAGER) as f:
237
+ c = f.read()
238
+
239
+ if M1 in c:
240
+ print("OK: session_manager.py already patched (idempotent)")
241
+ else:
242
+ # 2a. Add turn-timeout constant before DEFAULT_CONFIG_PATH.
243
+ anchor = "DEFAULT_CONFIG_PATH = str(PROJECT_ROOT"
244
+ const_block = (
245
+ "# ML_INTERN_TURN_WATCHDOG\n"
246
+ "TURN_TIMEOUT_S = 3600 # hard per-turn safety net (1 h).\n"
247
+ " # A single turn (LLM + tools) must never run forever.\n\n"
248
+ )
249
+ if anchor in c and "TURN_TIMEOUT_S" not in c:
250
+ c = c.replace(anchor, const_block + anchor, 1)
251
+ print("OK: added TURN_TIMEOUT_S constant")
252
+ else:
253
+ print("FAIL: could not find DEFAULT_CONFIG_PATH anchor in session_manager.py")
254
+ errors.append("session_manager constant")
255
+
256
+ old_block = ''' agent_session.is_processing = True
257
+ self._touch(agent_session)
258
+ try:
259
+ should_continue = await process_submission(
260
+ session, submission
261
+ )
262
+ finally:
263
+ agent_session.is_processing = False
264
+ # Stamp on turn finish too: a turn that ran longer
265
+ # than the idle window would otherwise be reaped the
266
+ # instant it completes.
267
+ self._touch(agent_session)
268
+ if session.config.save_sessions:
269
+ await self.refresh_session_usage_metrics(agent_session)
270
+ await self.persist_session_snapshot(agent_session)'''
271
+
272
+ new_block = ''' agent_session.is_processing = True
273
+ self._touch(agent_session)
274
+ try:
275
+ # ML_INTERN_TURN_WATCHDOG — hard per-turn deadline so
276
+ # a hung turn can never leave the session stuck.
277
+ turn_task = asyncio.create_task(
278
+ process_submission(session, submission)
279
+ )
280
+ done, _pending = await asyncio.wait(
281
+ {turn_task}, timeout=TURN_TIMEOUT_S
282
+ )
283
+ if not done:
284
+ # Watchdog fired: force-cancel the stuck turn.
285
+ turn_task.cancel()
286
+ try:
287
+ await turn_task
288
+ except asyncio.CancelledError:
289
+ pass
290
+ # Clear the cancel flag so the session stays
291
+ # usable for the NEXT turn (not a permanent
292
+ # zombie). Only when a resettable Event exists.
293
+ if _cancelled_ok(session):
294
+ session._cancelled.clear()
295
+ # Terminal SSE events -> frontend un-freezes.
296
+ await session.send_event(
297
+ Event(
298
+ event_type="interrupted",
299
+ data={
300
+ "error": (
301
+ "Single turn exceeded the "
302
+ f"{TURN_TIMEOUT_S}s safety limit "
303
+ "and was stopped."
304
+ )
305
+ },
306
+ )
307
+ )
308
+ await session.send_event(
309
+ Event(
310
+ event_type="turn_complete",
311
+ data={
312
+ "message": (
313
+ "Turn was auto-stopped after "
314
+ f"{TURN_TIMEOUT_S}s. The task may "
315
+ "need smaller steps or background "
316
+ "work."
317
+ ),
318
+ "auto_stopped": True,
319
+ },
320
+ )
321
+ )
322
+ should_continue = True
323
+ else:
324
+ should_continue = turn_task.result()
325
+ finally:
326
+ agent_session.is_processing = False
327
+ # Stamp on turn finish too: a turn that ran longer
328
+ # than the idle window would otherwise be reaped the
329
+ # instant it completes.
330
+ self._touch(agent_session)
331
+ if session.config.save_sessions:
332
+ await self.refresh_session_usage_metrics(agent_session)
333
+ await self.persist_session_snapshot(agent_session)'''
334
+
335
+ if old_block in c:
336
+ c = c.replace(old_block, new_block, 1)
337
+ print("OK: wrapped process_submission in turn watchdog")
338
+ else:
339
+ print("FAIL: could not find process_submission block in session_manager.py")
340
+ idx = c.find("should_continue = await process_submission")
341
+ if idx >= 0:
342
+ print("DEBUG context:")
343
+ print(c[idx - 400 : idx + 200])
344
+ errors.append("session_manager watchdog")
345
+
346
+ with open(SESSION_MANAGER, "w") as f:
347
+ f.write(c)
348
+ try:
349
+ ast.parse(c)
350
+ print("OK: session_manager.py syntax OK")
351
+ except SyntaxError as e:
352
+ print(f"FAIL: session_manager.py syntax: {e}")
353
+ errors.append("session_manager syntax")
354
+
355
+
356
+ # =========================================================================
357
+ # PART 3: helper for the watchdog (clear resettable cancel flag)
358
+ # =========================================================================
359
+ def ensure_helper() -> None:
360
+ if not os.path.exists(SESSION_MANAGER):
361
+ return
362
+ with open(SESSION_MANAGER) as f:
363
+ c = f.read()
364
+ if M3 in c:
365
+ print("OK: _cancelled_ok helper already present")
366
+ return
367
+ anchor = "\n\nlogger = logging.getLogger(__name__)\n"
368
+ helper = (
369
+ "\n\ndef _cancelled_ok(session) -> bool: # _cancelled_ok_helper\n"
370
+ " # ML_INTERN_TURN_WATCHDOG helper — True if session has a resettable\n"
371
+ " # _cancelled asyncio.Event (used to clear stop-state after an\n"
372
+ " # auto-stopped turn so the session stays usable).\n"
373
+ " e = getattr(session, \"_cancelled\", None)\n"
374
+ " return e is not None and hasattr(e, \"clear\")\n\n"
375
+ )
376
+ if anchor in c and "_cancelled_ok(session)" in c:
377
+ c = c.replace(anchor, helper + anchor, 1)
378
+ with open(SESSION_MANAGER, "w") as f:
379
+ f.write(c)
380
+ try:
381
+ ast.parse(c)
382
+ print("OK: added _cancelled_ok helper; session_manager.py syntax OK")
383
+ except SyntaxError as e:
384
+ print(f"FAIL: session_manager.py syntax after helper: {e}")
385
+ errors.append("helper syntax")
386
+ else:
387
+ print("FAIL: could not place _cancelled_ok helper")
388
+ errors.append("helper placement")
389
+
390
+
391
+ ensure_helper()
392
+
393
+ if errors:
394
+ print(f"PATCH FAILED: {errors}")
395
+ raise SystemExit(1)
396
+ print("DONE: session-hang fix applied (non-blocking bash + turn watchdog)")