Repository navigation
Expand file tree
/
Copy pathSTART_PROCESS_CLEANUP.patch
More file actions
387 lines (375 loc) · 19.8 KB
/
Copy pathSTART_PROCESS_CLEANUP.patch
File metadata and controls
387 lines (375 loc) · 19.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
--- /tmp/start_before_pid_cleanup.py 2026-05-06 23:16:30.065314425 +0000
+++ start.py 2026-05-06 23:18:39.914706237 +0000
@@ -368,6 +368,94 @@
pass
+_START_MANAGED_PID_LOCK = threading.RLock()
+_START_MANAGED_PID_REGISTRY: dict[int, dict[str, object]] = {}
+_START_EXIT_CLEANUP_RUNNING = False
+_START_EXIT_CLEANUP_DONE = False
+
+
+def _start_pid_registry_path() -> Path:
+ try:
+ root = Path(__file__).resolve().parent
+ logs_dir = root / 'logs'
+ logs_dir.mkdir(parents=True, exist_ok=True)
+ return logs_dir / 'start_pids.json'
+ except Exception:
+ return Path(__file__).resolve().parent / 'start_pids.json'
+
+
+def _start_pid_command_text(command: object) -> str:
+ try:
+ if isinstance(command, (list, tuple)):
+ return ' '.join(shlex.quote(str(part)) for part in command)
+ return str(command or '')
+ except Exception:
+ return str(command or '')
+
+
+def _writeStartManagedPidRegistry() -> None:
+ try:
+ path = _start_pid_registry_path()
+ with _START_MANAGED_PID_LOCK:
+ payload = {
+ 'launcher_pid': int(os.getpid()),
+ 'updated_at': datetime.datetime.now().isoformat(timespec='seconds'),
+ 'processes': sorted(_START_MANAGED_PID_REGISTRY.values(), key=lambda row: (str(row.get('role', '')), int(row.get('pid', 0) or 0))),
+ }
+ tmp_path = path.with_suffix(path.suffix + '.tmp')
+ tmp_path.write_text(json.dumps(payload, indent=2, sort_keys=True), encoding='utf-8') # file-wrapper-ok
+ tmp_path.replace(path)
+ except Exception as error:
+ try:
+ RuntimeLog.log(f'[WARN:start-pids] failed to write PID registry: {type(error).__name__}: {error}\n', flush=True, channel='start-pids')
+ except Exception:
+ pass
+
+
+def _recordStartManagedPid(pid: object, *, role: str = 'child', command: object = None, source: str = '', parent_pid: object = None) -> int:
+ try:
+ pid_value = int(pid or 0)
+ except Exception:
+ pid_value = 0
+ if pid_value <= 0:
+ return 0
+ try:
+ parent_value = int(parent_pid or os.getpid() or 0)
+ except Exception:
+ parent_value = int(os.getpid() or 0)
+ with _START_MANAGED_PID_LOCK:
+ existing = dict(_START_MANAGED_PID_REGISTRY.get(pid_value, {}) or {})
+ existing.update({
+ 'pid': pid_value,
+ 'parent_pid': parent_value,
+ 'role': str(role or existing.get('role') or 'child'),
+ 'command': _start_pid_command_text(command if command is not None else existing.get('command', '')),
+ 'source': str(source or existing.get('source') or ''),
+ 'recorded_at': existing.get('recorded_at') or datetime.datetime.now().isoformat(timespec='seconds'),
+ 'updated_at': datetime.datetime.now().isoformat(timespec='seconds'),
+ 'self': bool(pid_value == os.getpid()),
+ })
+ _START_MANAGED_PID_REGISTRY[pid_value] = existing
+ _writeStartManagedPidRegistry()
+ return pid_value
+
+
+def _startManagedPidSnapshot() -> list[dict[str, object]]:
+ with _START_MANAGED_PID_LOCK:
+ return [dict(row) for row in _START_MANAGED_PID_REGISTRY.values()]
+
+
+def _start_cleanup_disabled(argv: list[str] | None = None) -> bool:
+ try:
+ tokens = {str(token or '').strip().lower().lstrip('-/') for token in list(argv if argv is not None else sys.argv[1:])}
+ if tokens.intersection({'no-final-taskkill', 'no-taskkill-final', 'no-process-cleanup', 'keep-children'}):
+ return True
+ raw = str(os.environ.get('TRIO_NO_FINAL_TASKKILL', '') or os.environ.get('FLATLINE_NO_FINAL_TASKKILL', '') or '').strip().lower()
+ return raw in {'1', 'true', 'yes', 'y', 'on'}
+ except Exception:
+ return False
+
+
class File:
"""Early-start small file wrapper used before the full data layer exists.
@@ -571,6 +659,8 @@
installStartConsolePrintMirror()
print(f'[TRACE:start-console-mirror] start.py stdout/stderr/print mirroring to {_start_debug_log_path()}', file=sys.stderr, flush=True)
+_recordStartManagedPid(os.getpid(), role='launcher-parent', command=sys.argv, source='start.py:module')
+
def _early_no_bootstrap_requested(argv: object = None) -> bool:
tokens = _start_cli_token_list(sys.argv[1:] if argv is None else argv)
@@ -892,6 +982,7 @@
recordException('start.py:early-run-command-filebacked-popen-flags', sys.exc_info()[1])
try:
process = subprocess.Popen(command, **popen_kwargs) # lifecycle-bypass-ok # phase-ownership-ok
+ _recordStartManagedPid(getattr(process, 'pid', 0), role='early-filebacked-command', command=command, source='start.py:_early_run_command_filebacked')
deadline = time.monotonic() + timeout_seconds
last_trace = 0.0
while True:
@@ -976,6 +1067,7 @@
process = None
try:
process = subprocess.Popen(command, **popen_kwargs) # lifecycle-bypass-ok # phase-ownership-ok
+ _recordStartManagedPid(getattr(process, 'pid', 0), role='early-command', command=command, source='start.py:_early_run_command')
try:
stdout, stderr = process.communicate(timeout=max(1, int(timeout_seconds or 120)))
return int(process.returncode or 0), str(stdout or ''), str(stderr or '')
@@ -2150,6 +2242,7 @@
before = DEAD_WINDOW_MONITOR.snapshot()
kwargs = flatlineSubprocessKwargs(command, kwargs, policy=_flatlinePolicyFromLegacy(policy, command))
proc = _RAW_SUBPROCESS_POPEN(command, **kwargs)
+ _recordStartManagedPid(getattr(proc, 'pid', 0), role='popen-child', command=command, source=source)
DEAD_WINDOW_MONITOR.checkAfterLaunch(before, launchedPid=int(getattr(proc, 'pid', 0) or 0), command=command, policy=policy, sourceLine=source, delaySeconds=windowDelaySeconds)
return proc
@@ -2782,6 +2875,7 @@
popen_kwargs.setdefault('start_new_session', True)
self.proc = monitoredRawPopen(self.command, sourceLine=self.createdContext, windowPolicy=self.windowPolicy, windowDelaySeconds=self.windowDelaySeconds, **popen_kwargs)
self.pid = int(getattr(self.proc, 'pid', 0) or 0); self.startedAt = time.monotonic(); self.status = 'running'
+ _recordStartManagedPid(self.pid, role='StartProcess', command=self.command, source=self.createdContext)
phase = getattr(self, 'phase', None)
phase_key = str(getattr(self, 'phaseKey', EMPTY_STRING) or getattr(phase, 'key', EMPTY_STRING) or EMPTY_STRING)
print(f'[TRACE:start-process] process.start pid={self.pid} name={self.name} phase={phase_key} command={_launcherCommandText(self.command)}', file=sys.stderr, flush=True)
@@ -2864,6 +2958,8 @@
def __del__(self):
try:
+ if self.isAlive():
+ self.kill(reason='StartProcess.__del__')
RuntimeLog.flush(final=True)
except Exception:
pass
@@ -2901,6 +2997,8 @@
recordException('start.py:bootstrapped-app-attach-pid', sys.exc_info()[1], handled=True)
self.pid = 0
self.command = [str(part) for part in list(command or getattr(process, 'command', []) or [])]
+ if self.pid:
+ _recordStartManagedPid(self.pid, role='bootstrapped-app', command=self.command, source='BootStrappedApp.attach')
self.startedAt = time.time()
self.endedAt = 0.0
return self
@@ -3280,6 +3378,8 @@
print(f'[TRACE:{trace_prefix}] taskkill {line.strip()}', file=sys.stderr, flush=True)
ok = int(getattr(completed, 'returncode', 1) or 0) == 0
print(f'[TRACE:{trace_prefix}] result ok={ok} returncode={getattr(completed, "returncode", None)} pid={pid_value}', file=sys.stderr, flush=True)
+ if not ok:
+ print(f'[WARN:{trace_prefix}] taskkill failed pid={pid_value} returncode={getattr(completed, "returncode", None)} reason={reason}', file=sys.stderr, flush=True)
return ok
try:
if tree:
@@ -3321,6 +3421,106 @@
return False
+
+def _managed_pid_rows_from_controller(controller=None, debugger=None) -> list[dict[str, object]]:
+ rows = list(_startManagedPidSnapshot())
+ seen: set[int] = {int(row.get('pid', 0) or 0) for row in rows if int(row.get('pid', 0) or 0) > 0}
+ def add_pid(pid: object, role: str, command: object = None, source: str = '') -> None:
+ try:
+ pid_value = int(pid or 0)
+ except Exception:
+ pid_value = 0
+ if pid_value <= 0 or pid_value in seen:
+ return
+ seen.add(pid_value)
+ _recordStartManagedPid(pid_value, role=role, command=command, source=source)
+ rows.append({'pid': pid_value, 'role': role, 'command': _start_pid_command_text(command), 'source': source})
+ try:
+ if controller is not None:
+ for pid in list(getattr(controller, 'activeProcesses', {}) or {}).copy():
+ add_pid(pid, 'lifecycle-active-process', source='StartLifecycleController.activeProcesses')
+ for process in list(getattr(controller, 'launcherProcesses', []) or []):
+ add_pid(getattr(process, 'pid', 0), 'lifecycle-launcher-process', getattr(process, 'command', None), 'StartLifecycleController.launcherProcesses')
+ except Exception:
+ recordException('start.py:managed-pid-controller-snapshot', sys.exc_info()[1], handled=True)
+ try:
+ if debugger is not None:
+ child = getattr(debugger, 'child', None)
+ add_pid(getattr(child, 'pid', 0), 'debugger-child', getattr(child, 'command', None), 'Debugger.child')
+ app = getattr(debugger, 'bootStrappedApp', None)
+ add_pid(getattr(app, 'pid', 0), 'bootstrapped-app', getattr(app, 'command', None), 'Debugger.bootStrappedApp')
+ except Exception:
+ recordException('start.py:managed-pid-debugger-snapshot', sys.exc_info()[1], handled=True)
+ return rows
+
+
+def killManagedChildProcesses(*, reason: str = 'final cleanup', controller=None, debugger=None, includeSelf: bool = False, timeout: float = 12.0) -> bool: # noqa: N802
+ """Taskkill every managed child PID we know about, warning loudly on failures."""
+ if _start_cleanup_disabled():
+ print(f'[TRACE:managed-taskkill] disabled reason={reason}', file=sys.stderr, flush=True)
+ return True
+ current_pid = int(os.getpid() or 0)
+ rows = _managed_pid_rows_from_controller(controller=controller, debugger=debugger)
+ # Kill children before helpers, and self only when explicitly requested.
+ ordered: list[int] = []
+ seen: set[int] = set()
+ for row in rows:
+ try:
+ pid_value = int(row.get('pid', 0) or 0)
+ except Exception:
+ pid_value = 0
+ if pid_value <= 0 or pid_value in seen:
+ continue
+ if pid_value == current_pid and not bool(includeSelf):
+ continue
+ seen.add(pid_value)
+ ordered.append(pid_value)
+ ordered = [pid for pid in ordered if pid != current_pid] + ([current_pid] if includeSelf and current_pid in ordered else [])
+ print(f'[TRACE:managed-taskkill] cleanup reason={reason} count={len(ordered)} pids={ordered}', file=sys.stderr, flush=True)
+ ok_all = True
+ for pid_value in ordered:
+ if pid_value == current_pid and not bool(includeSelf):
+ continue
+ if not Tasks.processExists(pid_value) and pid_value != current_pid:
+ print(f'[TRACE:managed-taskkill] pid already gone pid={pid_value}', file=sys.stderr, flush=True)
+ continue
+ ok = Tasks.taskkill(pid_value, tree=True, force=True, reason=reason, timeout=float(timeout or 12.0), trace_prefix='managed-taskkill', allowSelf=bool(pid_value == current_pid and includeSelf))
+ time.sleep(0.10)
+ still_alive = False if pid_value == current_pid and includeSelf else Tasks.processExists(pid_value)
+ if (not ok) or still_alive:
+ ok_all = False
+ print(f'[WARN:managed-taskkill] failed_or_survived pid={pid_value} ok={ok} still_alive={still_alive} reason={reason}', file=sys.stderr, flush=True)
+ _writeStartManagedPidRegistry()
+ try:
+ RuntimeLog.flushAllLogs()
+ except Exception:
+ RuntimeLog.flush(final=True)
+ return bool(ok_all)
+
+
+def _startAtexitProcessCleanup() -> None:
+ global _START_EXIT_CLEANUP_RUNNING, _START_EXIT_CLEANUP_DONE
+ if _START_EXIT_CLEANUP_DONE or _START_EXIT_CLEANUP_RUNNING:
+ return
+ _START_EXIT_CLEANUP_RUNNING = True
+ try:
+ controller = globals().get('LAST_START_CONTROLLER')
+ debugger = getattr(controller, 'debugger', None) if controller is not None else globals().get('LAST_DEBUGGER')
+ killManagedChildProcesses(reason='start.py atexit cleanup', controller=controller, debugger=debugger, includeSelf=False, timeout=10.0)
+ except Exception:
+ recordException('start.py:atexit-process-cleanup', sys.exc_info()[1], handled=True)
+ finally:
+ _START_EXIT_CLEANUP_DONE = True
+ _START_EXIT_CLEANUP_RUNNING = False
+ try:
+ RuntimeLog.flushAllLogs()
+ except Exception:
+ RuntimeLog.flush(final=True)
+
+
+atexit.register(_startAtexitProcessCleanup)
+
+
STALE_CLIENT_PROCESS_MATCHES = (
'start.py', 'trio.py',
)
@@ -29852,6 +30052,7 @@
app = getattr(self, 'bootStrappedApp', None)
if app is not None and app.isRunning():
app.kill(reason='Debugger.shutdownKernel', force=True, tree=True, verify=True)
+ killManagedChildProcesses(reason='Debugger.shutdownKernel', debugger=self, includeSelf=False, timeout=10.0)
except Exception:
recordException('start.py:bootstrapped-app-shutdown-kill', sys.exc_info()[1], handled=True)
self.closeChildStreams()
@@ -29891,13 +30092,18 @@
pid_value = int(getattr(self, 'debuggerPid', 0) or os.getpid())
if os.name == 'nt':
try:
- command = ['taskkill', '/PID', str(pid_value), '/F']
- completed = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) # lifecycle-bypass-ok: final debugger self-kill only
+ command = ['taskkill', '/PID', str(pid_value), '/T', '/F']
+ completed = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True) # lifecycle-bypass-ok: final debugger self-kill only
if verify:
completed.wait(timeout=3)
+ if int(getattr(completed, 'returncode', 1) or 0) != 0:
+ stderr_text = str(getattr(completed, 'stderr', None).read() if getattr(completed, 'stderr', None) is not None else EMPTY_STRING)
+ print(f'[WARN:debugger-kill-self] taskkill failed pid={pid_value} rc={getattr(completed, "returncode", None)} stderr={stderr_text}', file=sys.stderr, flush=True)
+ return False
return True
- except Exception:
+ except Exception as error:
recordException('start.py:debugger-kill-self-taskkill', sys.exc_info()[1], handled=True)
+ print(f'[WARN:debugger-kill-self] taskkill exception pid={pid_value}: {type(error).__name__}: {error}', file=sys.stderr, flush=True)
return False
if verify:
try:
@@ -29913,6 +30119,7 @@
app = getattr(self, 'bootStrappedApp', None)
if app is not None and app.isRunning():
app.kill(reason='Debugger.__del__', force=True, tree=True, verify=True)
+ killManagedChildProcesses(reason='Debugger.__del__', debugger=self, includeSelf=False, timeout=8.0)
try:
clearPycacheDirectories(BASE_DIR, reason='Debugger.__del__')
except Exception:
@@ -31963,22 +32170,35 @@
return True
def finalTeardown(self, *, killDebuggerSelf: bool = False) -> bool:
+ if bool(getattr(self, '_finalTeardownRunning', False)):
+ return True
+ self._finalTeardownRunning = True
debugger = getattr(self, 'debugger', None)
try:
if debugger is not None:
app = getattr(debugger, 'bootStrappedApp', None)
if app is not None and app.isRunning():
app.kill(reason='StartLifecycleController.finalTeardown', force=True, tree=True, verify=True)
+ killManagedChildProcesses(reason='StartLifecycleController.finalTeardown', controller=self, debugger=debugger, includeSelf=False, timeout=12.0)
RuntimeLog.flushAllLogs()
if killDebuggerSelf:
- debugger.killSelf(reason='StartLifecycleController.finalTeardown')
+ debugger.killSelf(reason='StartLifecycleController.finalTeardown', force=True, verify=False)
else:
+ killManagedChildProcesses(reason='StartLifecycleController.finalTeardown(no-debugger)', controller=self, debugger=None, includeSelf=False, timeout=12.0)
RuntimeLog.flushAllLogs()
except Exception:
recordException('start.py:final-teardown', sys.exc_info()[1], handled=True)
RuntimeLog.flush(final=True)
+ finally:
+ self._finalTeardownRunning = False
return True
+ def __del__(self) -> None:
+ try:
+ self.finalTeardown(killDebuggerSelf=False)
+ except Exception:
+ pass
+
def run(self) -> int:
try:
self.runPhaseGroup('startup')
@@ -35883,12 +36103,38 @@
setattr(StartLifecycleController, 'ensureProcessTable', _start_lifecycle_ensureProcessTable_v1022)
return True
+
+def finalSelfTaskkillRequested(argv: list[str] | None = None) -> bool: # noqa: N802
+ """Default to taskkilling the Windows launcher at the last line of normal app runs.
+
+ Report-only and no-bootstrap commands must keep normal exit codes for tests.
+ """
+ if os.name != 'nt':
+ return False
+ tokens = {str(token or '').strip().lower().lstrip('-/') for token in list(argv if argv is not None else sys.argv[1:])}
+ if tokens.intersection({'no-final-taskkill-self', 'no-taskkill-self', 'keep-start-py', 'keep-launcher', 'no-bootstrap', 'version', 'help', 'h', '?' }):
+ return False
+ if _start_cleanup_disabled(list(argv if argv is not None else sys.argv[1:])):
+ return False
+ raw = str(os.environ.get('TRIO_DEBUGGER_KILL_SELF_ON_EXIT', '') or os.environ.get('FLATLINE_KILL_SELF_ON_EXIT', '') or '').strip().lower()
+ if raw in {'0', 'false', 'no', 'n', 'off'}:
+ return False
+ if raw in {'1', 'true', 'yes', 'y', 'on'}:
+ return True
+ # Normal Windows GUI/debugger runs are the ones that leave orphaned python.exe
+ # processes and locked files. Keep this off for workers and report-only CLIs.
+ worker_names = {'font-worker', 'dependency-worker', 'model-catalog-worker', 'startup-tools-worker', 'chat-test-worker', 'shell-rpc-worker'}
+ report_names = {'health', 'rough', 'ruff', 'claude-detectors', 'detectors-one-by-one', 'certify', 'detector-selftest', 'font-metadata', 'extract-glyph'}
+ if tokens.intersection(worker_names | report_names):
+ return False
+ return True
+
if __name__ == '__main__':
_exit_code = int(main())
try:
_controller = globals().get('LAST_START_CONTROLLER')
if _controller is not None and hasattr(_controller, 'finalTeardown'):
- _kill_self = str(os.environ.get('TRIO_DEBUGGER_KILL_SELF_ON_EXIT', EMPTY_STRING) or EMPTY_STRING).strip().lower() in {'1', 'true', 'yes', 'on'}
+ _kill_self = finalSelfTaskkillRequested(sys.argv[1:])
_controller.finalTeardown(killDebuggerSelf=bool(_kill_self))
else:
RuntimeLog.flushAllLogs()