Repository navigation
Fix daemon start on modern FastAPI and stale PID files on Windows - #15
Open
ericwang915 wants to merge 3 commits into
Open
ericwang915 wants to merge 3 commits into
ericwang915 wants to merge 3 commits into
Conversation
…an (#13) Starlette 1.0 removed the add_websocket_route/on_event shortcuts from the application class. FastAPI >= 0.133 no longer pins Starlette < 1.0, so a fresh install (e.g. FastAPI 0.165.0) crashes in create_app with AttributeError: 'FastAPI' object has no attribute 'add_websocket_route'. Use FastAPI's own add_api_websocket_route (available across the declared fastapi>=0.100 range) and move the channel startup hook from the deprecated @app.on_event('startup') to a lifespan passed into create_app. Co-authored-by: Eric Wang <wangchen2007915@gmail.com>
… Windows (#14) _is_alive only caught ProcessLookupError/PermissionError, but on Windows os.kill(pid, 0) on a stale PID raises a plain OSError (WinError 11), so 'pythonclaw start' died with a traceback. Catch the whole OSError family. On Windows os.kill() is not a probe at all: any signal other than CTRL_C/CTRL_BREAK is forwarded to TerminateProcess, so 'status' or a second 'start' would kill a live daemon. Probe with OpenProcess + GetExitCodeProcess there instead; POSIX keeps using os.kill(pid, 0). Also print a clear message when a stale PID file is cleaned up on start, and make stop_daemon tolerate OSError / missing SIGKILL on Windows. Co-authored-by: Eric Wang <wangchen2007915@gmail.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #13
Fixes #14
Both reports come from the same repro on Windows 11 / Python 3.14.7 / PythonClaw 0.7.2 / FastAPI 0.165.0:
pythonclaw start, then open http://localhost:7788/.Root cause: #13 (
daemon.logtraceback,'FastAPI' object has no attribute 'add_websocket_route')create_app()registered the chat WebSocket withapp.add_websocket_route(...). That method was never FastAPI's; it was a shortcut inherited fromstarlette.applications.Starlette, and Starlette 1.0 removed it (together withon_event,add_event_handler, ...). FastAPI dropped itsstarlette<1.0pin in 0.133 and requiresstarlette>=1.6from 0.164, so any fresh install today (the reporter's 0.165.0 resolves Starlette 1.10) hits theAttributeErrorin the background daemon. The daemon died within its first second, which is why the parentstartcould never serve the dashboard.Fix: use FastAPI's own
add_api_websocket_route, which exists across the project's declared range (fastapi>=0.100). The channel startup hook inmain.pyused the sibling@app.on_event("startup")shortcut on the same path; FastAPI still ships its own copy of that with aDeprecationWarning, so it had not broken yet, but it is the same removal class, socreate_app()now accepts anon_startupcoroutine and wires it through the lifespan API (available since FastAPI 0.93) instead.Root cause: #14 (terminal traceback,
OSError: [WinError 11]from_is_alive)daemon._is_alive()probed the PID frompythonclaw.pidwithos.kill(pid, 0)and only caughtProcessLookupError/PermissionError. On Windows a stale/foreign PID surfaces as a plainOSErrorcarrying aWinErrorcode, so the exception escapedstart_daemon()andpythonclaw startcrashed with a traceback (the stale PID file was left behind by the #13 crash).Fix:
_is_alive()now catches the wholeOSErrorfamily and never raises; POSIX keeps usingos.kill(pid, 0)with the samePermissionError -> Falsesemantics as before.os.kill(pid, 0)is also the wrong tool: per theos.killdocs, any signal other thanCTRL_C_EVENT/CTRL_BREAK_EVENTis forwarded toTerminateProcess, sopythonclaw statusor a secondpythonclaw startwould have killed a live daemon had the PID been valid. Windows now probes withOpenProcess(PROCESS_QUERY_LIMITED_INFORMATION)+GetExitCodeProcess == STILL_ACTIVEviactypes, which is read-only.start_daemon()printsStale PID file (process N not running). Cleaning up.instead of silently proceeding.stop_daemon()tolerates the sameOSErrorfamily around its signal sends and usesgetattr(signal, "SIGKILL", signal.SIGTERM)sinceSIGKILLdoes not exist on Windows (previously anAttributeErroron that branch).No version bump, no CHANGELOG entry (prior bugfix PR #12 followed the same convention; CHANGELOG is updated at release time).
Tests
New
tests/test_daemon_and_web.py(19 tests):create_app()builds withDeprecationWarningescalated to an error and registers/and/ws/chat.TestClient:GET /returns 200 HTML,/api/statusresponds,/ws/chataccepts a connection and replies; theon_startuphook runs exactly once via lifespan._is_alive: live PID, non-positive PID,ProcessLookupError,PermissionError, and a genericOSErrorwithwinerror=11all return a bool without raising; thewin32branch never callsos.kill._is_alive_windows: running / exited /OpenProcessfailure /GetExitCodeProcessfailure / DLL load failure, with a fakekernel32injected throughctypes.WinDLL.start_daemon,daemon_status,print_status,stop_daemonwith a stale PID file whose probe raises the Windows-styleOSError: no crash, clear message, PID/meta cleaned up, new daemon spawned once.Verification done here:
AttributeErrorfromcreate_app) before the fix.ruff check pythonclaw/clean.PYTHONCLAW_HOME: seeded a stale PID file, ranpythonclaw start(stale file cleaned, daemon spawned),curl http://127.0.0.1:<port>/returned200 text/html, thenstatus, a secondstart("Already running"),stop, andstatusagain all behaved.Not reproducible without Windows
[WinError 11]and theTerminateProcessside effect ofos.kill(pid, 0)cannot be triggered on Linux; the POSIX tests simulate the former by monkeypatchingos.killto raiseOSError(winerror=11), and the Windows probe is exercised only against a fakekernel32(CI has no Windows runner). Thectypescall shapes follow the documented Win32 signatures; a quickpythonclaw start/status/start/stopcycle on a Windows box would be a welcome confirmation.