Repository navigation
A stop signal goes through the event loop: never lost, every save made, a second one changes nothing (#78) - #80
Merged
Merged
Conversation
…cond one changes nothing (#78) SIGTERM and Ctrl+C used to end the server through a KeyboardInterrupt raised wherever the main thread was. Inside a __del__ or a weakref callback Python only prints it ("Exception ignored in ..."): the stop was lost, and the server ran on until the container runtime killed it, without the stop's saves. Raised inside asyncio's own code, it could also leave the loop unable to end after the saves. Now loop.add_signal_handler (on Windows, a signal.signal handler that only schedules onto the loop) notes the signal and wakes main(), whose tick loop waits on the request. main() then stops from its own code: the log line, the HTTP port closed, the watchdog off, the saves in the same order with the same lines, exit status 0. The stop signals are held for the whole of the saves, so a second or third one is logged and ignored and no write is cut short. A signal during the start (even while the code is imported) stops the server once its files are read whole; the --relay-only relay is cancelled at its await. tools/stop_loop.py stops a busy server thousands of times and counts the stops lost or unsaved.
…and its parts from the log (#78)
…o longer changes the exit status (#78) Python puts the default action back for its own handlers as the interpreter ends: a third signal 20 ms into a stop ended the process with status -2 (179 of 700 busy stops with three signals), after every save. SIG_IGN is left as it is. The stop's log, when signals came during the journaled writes: their line follows the boards'.
…one as ignored (#78)
… of closing the server (#78) On Python 3.13 and later, Server.close() while a connection is being accepted fails in that accept (an assertion, silent) and again as the process ends: "Exception ignored ... _SelectorTransport.__del__", the closed server woken a second time. About one busy stop in 20 on 3.14 logged it; none in 150 now. Windows' loops have no remove_reader: Server.close() there.
…, and a flood of signals costs them nothing (#78) A stop that came while the tick waited for the Discord status update waited for it before any save: on a bad network that can run past the 20 s a container runtime gives the stop. The update is now raced against the stop; after the saves the stop gives it up to 5 s, then the offline status is the last edit. During the saves, after the first held signal the signals are SIG_IGN until the log has told of it: a flood is no longer a handler's call and a wakeup byte each. The steps before the saves are guarded: one that fails is logged and the saves are made. After the saves the signals are taken off the loop while it is open and set to SIG_IGN, so the loop's close no longer puts the default action back for a thread that is still running.
…, and what ends a stop that does not end (#78)
…e same round of handlers is still noted (#78) Two signals that wait together (SIGINT and SIGTERM 10 ms apart, while the saves were in a system call) have their handlers run in one round; the first one set SIG_IGN for both, and the second then printed "Signal 15 ignored due to race condition" with a traceback (5 of 79 busy three-signal stops).
…pdate stuck past the stop's time (#78)
…paragraph of its own (#78)
… back no longer raises out of the stop (#78) remove_signal_handler puts default_int_handler back for SIGINT before end() sets SIG_IGN; a SIGINT just then (a flood of them) raised KeyboardInterrupt out of end(), and the rest of main()'s stop after the saves was skipped.
…er the loop's: Python's default action is never put back (#78) loop.add_signal_handler's loop gives SIGTERM SIG_DFL (and SIGINT default_int_handler) as it lets go of them, before SIG_IGN can be set. A SIGTERM in that moment, taken by a thread still running, ended the process with -15 after the saves (a flood of 1,000 signals: 1 stop in 50), and a signal met by SIG_IGN in Python's handler table printed "Signal 2 ignored due to race condition" (3 in 50). The handler that only hands the note to the loop (call_soon_threadsafe), so far Windows' only, is now the one everywhere: it never raises, and the loop never owns the signals. After the saves it does nothing; quiet(), once the loop is closed and its threads joined, sets SIG_IGN with the signals blocked in the main thread.
… holds it, and the stop makes every save before the kill (#78) Since the signal only notes itself on the loop, a loop held by Python code past the container runtime's 20 s was killed without a save, where the old KeyboardInterrupt broke in and saved. A thread now waits for the stop to begin from the first signal: --stop-limit seconds later (default 5; the saves take well under a second) it sends the signal again to the main thread, and the handler raises BreakIn (a KeyboardInterrupt) where the loop is held, every 0.1 s until the stop runs, since one raised where Python only prints it is lost. Never inside the stop's own code: main() and run() frames, and once stop_once() has begun. run() runs the stop itself when the BreakIn ended the loop outside main(). The signals' wakeup fd is the thread's pipe (POSIX), so it knows of a signal even while the main thread is in a C call that does not let the handler run; the log then says the stop waits for that call.
…the open HTTP connections end where they are (#78) During the wait for a Discord status update after the saves, the loop still answered datagrams and the connections opened before the stop: a player could join then and be missing from live_state.json. Before the saves the UDP transport is closed and every other task but the Discord update is cancelled (the open HTTP connections at their await, unanswered), as the loop's close cancelled them before.
…stop's last one (#78)
… past the stop's limit; the saves' lines' order and "Task was destroyed" checked (#78)
…after it (#78) When the break-in ended the loop's run outside main() and run() made the stop, main()'s wait could time out meanwhile and run one more tick after the saves (the events' flush on a closed database, a line after the boards'). The open tasks' cancellation before the saves already kept it from happening; now stop_once() also sets the request, and the wait says so after its time too.
… status 1: the stop does not cancel its own task (#78) When the held loop ended just before the break-in, the signal's note ran and main()'s wakeup was queued; the break-in then landed in the next callback, and run() queued its own task for the stop behind main()'s wakeup. main() began the stop first, and its cancellation of every other task cancelled run()'s too: a CancelledError out of run() after every save, a traceback and exit status 1 (a few in a hundred stops freed near the limit, every time when a callback held the loop again). That task only waits for the stop to end and writes nothing: end_the_others now keeps the tasks StopRequest.finish makes. Catching CancelledError in finish would also have taken a real cancellation for "try again".
…00 s (#78) --stop-limit inf crashed the stop's watching thread with an OverflowError in its wait once a signal came (the stop then ran without the break-in). The value is checked as the command line is read, with a message, and the thread waits in steps of at most 1 s.
…r after the saves (#78) When the stop broke into the loop while an HTTP connection's task ran, asyncio's streams logged "Unhandled exception in client_connected_cb" with the BreakIn's traceback, after every save (exit status 0, files whole). StopRequest.install now gives the loop an exception handler that drops a BreakIn (finish() sees those) and leaves everything else to asyncio's default. A loop that already has a handler keeps it. test_stop: a "task" hold, where the break-in lands in a stream server's connection task.
Dyotson
marked this pull request as ready for review
November 23, 2026 19:02
This was referenced Nov 23, 2026
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.
Closes #78
What was wrong
docker stop(SIGTERM) and Ctrl+C ended the server throughsignal.default_int_handler: aKeyboardInterruptraised in the main thread at whatever bytecode it was on. Two ways that went wrong, both reproduced onmainwith Python 3.12 (the image's version), stopping a busy server over and over (tools/stop_loop.py, below):__del__or a weakref callback (hereStreamWriter.__del__and_SelectorTransport.__del__of the HTTP connections), Python only printedException ignored in .... The server ran on until the 20 s ran out and it was killed, and none of the stop's saves were made.main, busy (HTTP connections opened and dropped as fast as one thread can, junk datagrams):With three signals 10 ms apart (SIGTERM, SIGTERM, SIGINT), main lost none, because the second signal raised again, but it cut the notifications' write short in 180 of 200 (its warning; the journal had every change), and 59 ended with exit status -2. With large stores and a flood of signals, 10 of 10 main stops ended with -2 and 9 of them wrote nothing at all.
What changed
All in
forza_live/server.py(StopRequest,main(),run()), plusforza_live_server.py.A signal only notes itself. SIGTERM and SIGINT have a
signal.signalhandler (StopRequest.schedule) on every system, which hands the note to the loop withcall_soon_threadsafeand raises nothing.loop.add_signal_handleris not used: the loop puts Python's default handlers back as it lets go of them, and a SIGTERM in that moment ended a stop with -15 after its saves (a flood of signals: 1 stop in 50).main()'s tick loop waits on the request (while not await stop.wait(1)) instead ofasyncio.sleep(1), and the stop runs frommain()'s own code.The stop, in order (
the_stopinmain(), run once byStopRequest.stop_once):stop: SIGTERM: the server stops(new line); nothing new from there (below); the watchdog off; the saves in the same order with the same lines; the Discord status; the exit, status 0.Nothing new is taken before the saves. The HTTP port's listening sockets are taken off the loop (
stop_accepting:loop.remove_reader;Server.close()only where there is noremove_reader, on Windows; on 3.13+Server.close()during an accept printedException ignored ... _SelectorTransport.__del__in 1 busy stop in 20), the UDP transport is closed (no datagram, no player joins), and every other task but a Discord update under way is cancelled (end_the_others): the open HTTP connections end at the await they are at, unanswered, as the loop's close cancelled them all before. Without that, a player could join during the wait for the Discord update after the saves and be missing fromlive_state.json.The signals are held for the whole of the saves, not only the first three stores. A second or third SIGTERM/SIGINT is noted and ignored, and the log says so once for each part of the stop:
stop: SIGTERM again while the registrations, co-op ledger and friends were written: ignored until they were(as before)stop: SIGTERM again while notifications.json and scoreboards.json were written: ignored until they were(new: a signal used to cut those two writes short)After a held signal is noted it turns only itself to
SIG_IGNuntil its line is logged, so a flood of signals costs the saves one handler call per part (a flood of thousands a second used to starve the boards' write).The Discord status update is not waited for before the saves. It is shielded and raced against the stop; after the saves it gets up to 5 s more (
DISCORD_WAIT), then the offline status.After the stop every signal is nothing: the handler stays ours while the loop closes (
end()), thenSIG_IGNwith the signals blocked in the main thread for that moment (quiet()). The default action is never put back, not even for a moment: a third signal as the interpreter ended gave exit status -2 in 179 of 700 three-signal stops before that part.A signal during the start stops the server once the start is done: every file is read whole, then the normal stop runs with all its saves (
stop: SIGTERM during the start: the server stops now that it is done). That holds even while Python is still loading the code:forza_live_server.pynotes a signal before it imports the server andrun(came)replays it.--relay-only: the relay is cancelled at theawaitit is at (it has nothing to save). It logs the stop line and exits with 0.The last resort for a held event loop (new,
--stop-limit S, default 5). A note on the loop is taken only once the loop is free, so a loop held by Python code past the container runtime's 20 s would have been killed without a save, where main'sKeyboardInterruptbroke in and saved. A thread (StopRequest.watch, started byinstall()) now waits from the first signal for the stop to begin. If it has not begun--stop-limitseconds later (counted from the end of the start for a signal during the start), it logsstop: SIGTERM came 5 s ago and the event loop has not taken it: something holds the loop (the watchdog's lines say what); the stop breaks into itand sends the signal again to the main thread (pthread_kill;_thread.interrupt_mainon Windows). The handler then raisesBreakIn(aKeyboardInterrupt, so asyncio lets it through) where the loop is held, as main's handler did. It tries again every 0.1 s until the stop has begun, since one raised where Python only prints it is lost. It never raises inside the stop: not inmain()'s orrun()'s own frames (a raise there, before the stop began, would skip it), nor oncestop_once()has begun, which is its first statement; the saves' own handler takes a late try as nothing. When theBreakInended the loop's run outsidemain()(main()still at its wait),run()runs the stop itself (StopRequest.finish). The signals' wakeup fd is the thread's pipe (POSIX), so the thread knows of a signal even while the main thread is in a C call that does not let Python's handler run. Then the stop waits for that call, and the log says so 5 s later (stop: the event loop is still held 5 s later: inside a call that cannot be broken into; the stop waits for it). 5 s leaves the saves (well under 1 s on the public data, at most 3 s seen on a stalling disk) far inside the 20 s, and a loop free sooner takes the signal itself.Nothing else changes: no store's format, no route, standard library only.
Exit status and the last log lines
--stop-limit, saves made, 0--relay-onlystop: SIGTERM: the server stopslastException ignored,Task was destroyed but it is pending!)stop: SIGTERM: the server stops… the notifications' line, then the boards', and nothing after them (with a second signal during those two writes, its "again" line)Proof
tools/stop_loop.py RUNS [--python EXE] [--gc-threshold N] [--signals ...] [--gap S] [--held SHARE]: each run starts the server on 127.0.0.1 with free ports and a temporary data folder, waits for/status, and puts it under load. The load is HTTP connections opened and closed as fast as one thread can (a third answered, a third dropped after half a request, a third at once) and junk datagrams, so tasks die and their weak references are cleaned up all the time.--gc-threshold 100runs the server withgc.set_threshold(100), so the garbage collector runs far more often.--held 0.1: in a tenth of the runs a task holds the loop with a pure-Python loop, 2-4 s (under the 5 s limit) or 8-40 s (past it), and the signal comes 0.2-1 s into the hold. Each data folder starts with a notification that onlynotifications.journalhas, so every stop that saves writesnotifications.jsonwhole (its line) andlive_state.json. A stop is lost when the process still runs after 20 s (the compose file'sstop_grace_period). Each run also checks: one notifications line, then one boards line, nothing after them but an "again" line; no traceback,Exception ignoredorTask was destroyed; a held run broken into exactly when its hold went past the limit.This branch at 0d4d39f:
mainin the same harness (no held loops): 3.12.15, 100 stops: 2 lost, both without the saves, 49 with a traceback, 23Exception ignored, 50Task was destroyed. 3.14.7, 50 stops: 1 lost (saved, then never ended), 20 tracebacks.Large stores and a flood of signals (
scoreboards.json27 MB plus 500 rows only in its journal,notifications.json11 MB plus 300 only in its journal, so both are written whole at every stop; SIGTERM, then SIGTERM and SIGINT alternating every 0.2 ms until the process ends). After each stop each file is read alone, as a previous version reads it, and compared with what the stores' own load of the template's file and journal gives (what the server held):On
mainthe same check found every one of 10 such stops ended with -2 and 9 of them wrote nothing at all.Stop time (first signal to the process's end; the public server is given 20 s)
The medians are the same as main's. The tails are the stop's own file writes, flushed to disk, on this machine with other work running and the server at
nice 15. Signal to the stop's first line: 0 ms median (the held runs: 5.005 s, the break-in). The boards' line to the process's end: 13-14 ms median, 18 ms max.Held loops, one at a time (
tests/server/test_stop.py, and by hand on 3.12 and 3.14)time.sleep(30)Tests (in CI)
tests/server/test_stop.py, 33 tests (20 runs in a row on 3.12.15 and 20 on 3.14.7: all OK, 34-41 s each):StopRequestwith signals raised in this process: why the old way lost one (KeyboardInterruptdropped in a weakref callback); a signal in a weakref callback noted and waking the wait; the handler only schedules the note; more signals change nothing; a signal during the start; the relay cancelled at its await; after the stop nothing, thenSIG_IGN; neverSIG_DFLordefault_int_handler.run(): a loop free before the limit takes the signal itself; a loop held past it is broken into and the stop runs; a try that lands in a weakref callback is printed and the next one stops it; never inside the stop; never raised inmain()'s own frame or once the stop has begun.stop_accepting; the held signals' log lines, two signals in one round, a flood.TerminateProcessor Ctrl+C in the server's own console): SIGTERM while busy, Ctrl+C, three signals, a signal while the boards are read and while Python imports the server, a slow Discord update, a step before the saves that fails, the relay, a refused start; a loop held 3 s, held past--stop-limitby Python code and by a sleep, held in a C call that returns before the kill and one that does not; and nothing taken after the saves (a HELLO during the Discord wait gets no WELCOME, a request on a connection opened before the stop gets no answer).Mutations caught: no UDP close and no cancellation (a WELCOME, then a
200 OK), no retry of the break-in, the stop's own frames not excluded. Whole suite: 1257 tests, OK on Python 3.12.15 and 3.14.7; CI green on all 8 jobs.Docs
docs/operating.mdhas a new "Stopping the server" section: what a stop does in order, what the log shows, the start and relay cases, a flood of signals, a Discord update stuck past the stop's time, a held event loop and the break-in, and what a kill costs. The rule "Stopping: onedocker compose stop, and let it end" is rewritten, now that repeated signals are harmless (logged and ignored): a second stop changes nothing, and only a kill ends a stop early. "Scores on disk" no longer says that a signal ends the notifications' write.docs/configuration.mdlists--stop-limit.Notes
forza_live_server.py, where Python has no handler yet. As a container's first process, a SIGTERM then is dropped by the kernel, as before.TerminateProcess, unchanged.