Skip to content

A stop signal goes through the event loop: never lost, every save made, a second one changes nothing (#78) - #80

Merged
Dyotson merged 22 commits into
mainfrom
fix/stop-through-the-loop
Nov 23, 2026
Merged

Dyotson merged 22 commits into
mainfrom
fix/stop-through-the-loop

Conversation

@Dyotson

@Dyotson Dyotson commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Closes #78

What was wrong

docker stop (SIGTERM) and Ctrl+C ended the server through signal.default_int_handler: a KeyboardInterrupt raised in the main thread at whatever bytecode it was on. Two ways that went wrong, both reproduced on main with Python 3.12 (the image's version), stopping a busy server over and over (tools/stop_loop.py, below):

  • The stop was lost. When the signal landed inside a __del__ or a weakref callback (here StreamWriter.__del__ and _SelectorTransport.__del__ of the HTTP connections), Python only printed Exception 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.
  • The stop saved, then never ended. When the exception came up through asyncio's own code, the loop could no longer finish shutting down after the saves. The process was killed at 20 s too.

main, busy (HTTP connections opened and dropped as fast as one thread can, junk datagrams):

batch stops lost of them without the saves
Python 3.12.15, one SIGTERM (three batches) 1,300 22 15
Python 3.14.7, one SIGTERM 200 11 7

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()), plus forza_live_server.py.

  • A signal only notes itself. SIGTERM and SIGINT have a signal.signal handler (StopRequest.schedule) on every system, which hands the note to the loop with call_soon_threadsafe and raises nothing. loop.add_signal_handler is 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 of asyncio.sleep(1), and the stop runs from main()'s own code.

  • The stop, in order (the_stop in main(), run once by StopRequest.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 no remove_reader, on Windows; on 3.13+ Server.close() during an accept printed Exception 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 from live_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_IGN until 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()), then SIG_IGN with 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.py notes a signal before it imports the server and run(came) replays it.

  • --relay-only: the relay is cancelled at the await it 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's KeyboardInterrupt broke in and saved. A thread (StopRequest.watch, started by install()) now waits from the first signal for the stop to begin. If it has not begun --stop-limit seconds later (counted from the end of the start for a signal during the start), it logs stop: 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 it and sends the signal again to the main thread (pthread_kill; _thread.interrupt_main on Windows). The handler then raises BreakIn (a KeyboardInterrupt, 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 in main()'s or run()'s own frames (a raise there, before the stop began, would skip it), nor once stop_once() has begun, which is its first statement; the saves' own handler takes a late try as nothing. When the BreakIn ended the loop's run outside main() (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

before after
SIGTERM / Ctrl+C 0 (-2 with several signals) 0, whatever comes after
a loop held by Python code past the stop's time broken into, saves made, 0 broken into after --stop-limit, saves made, 0
a loop held inside a C call past the stop's time killed, no save (137) the same: nothing can save there; two lines say what the stop waits for
a start refused (a file it cannot read) 1, its own line last the same
--relay-only 0, no line 0, stop: SIGTERM: the server stops last
the last lines of a stop the notifications' line, then the boards' (busy: often tracebacks, Exception 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)
a second signal during the notifications' write ended that write (a warning), boards still written logged and ignored, both written
a third signal during the boards' write cut it short logged and ignored

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 100 runs the server with gc.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 only notifications.journal has, so every stop that saves writes notifications.json whole (its line) and live_state.json. A stop is lost when the process still runs after 20 s (the compose file's stop_grace_period). Each run also checks: one notifications line, then one boards line, nothing after them but an "again" line; no traceback, Exception ignored or Task was destroyed; a held run broken into exactly when its hold went past the limit.

This branch at 0d4d39f:

Python stops signals gc held (under / past the limit) lost without the saves exit status not 0 traceback / "Exception ignored" / "Task was destroyed" lines out of order broken into the wrong way
3.12.15 300 SIGTERM 100 36 (20 / 16) 0 0 0 0 / 0 / 0 0 0
3.12.15 300 SIGTERM, SIGTERM, SIGINT, 10 ms apart default 29 (17 / 12) 0 0 0 0 / 0 / 0 0 0
3.14.7 150 SIGTERM 100 11 (5 / 6) 0 0 0 0 / 0 / 0 0 0
3.14.7 150 SIGTERM, SIGTERM, SIGINT, 10 ms apart default 17 (7 / 10) 0 0 0 0 / 0 / 0 0 0

main in the same harness (no held loops): 3.12.15, 100 stops: 2 lost, both without the saves, 49 with a traceback, 23 Exception ignored, 50 Task was destroyed. 3.14.7, 50 stops: 1 lost (saved, then never ended), 20 tracebacks.

Large stores and a flood of signals (scoreboards.json 27 MB plus 500 rows only in its journal, notifications.json 11 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):

Python stops signals per stop (median) lost exit status not 0 a file not what the server held not written whole traceback / "Exception ignored" / "race condition" stop time median / max
3.12.15 70 3,129 0 0 0 0 0 / 0 / 0 0.79 / 1.00 s
3.14.7 30 4,094 0 0 0 0 0 / 0 / 0 1.18 / 2.04 s

On main the 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)

stops median 99th percentile max
main, 3.12, one SIGTERM 98 0.040 s 0.218 s 0.218 s
this branch, 3.12, one SIGTERM 264 0.029 s 0.075 s 0.100 s
this branch, 3.12, three signals 271 0.043 s 0.210 s 0.623 s
main, 3.14, one SIGTERM 49 0.052 s 0.876 s 0.876 s
this branch, 3.14, one SIGTERM 139 0.046 s 0.709 s 0.789 s
this branch, 3.14, three signals 133 0.045 s 0.187 s 0.190 s
this branch, a loop held 2-4 s (both Pythons) 49 2.3 s 3.7 s (once the loop is free)
this branch, a loop held 8-40 s (both Pythons) 44 5.05 s 5.18 s (broken into at 5 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)

the loop held by, SIGTERM 1 s in this branch main
Python code, 3 s stops when the loop is free, every save, 0 at once, every save, 0
Python code, 30 s broken into 5 s after the signal, every save, 0 at once, every save, 0
time.sleep(30) the same, 5 s at once, every save, 0
a C call that ends at 12 s (a pthread mutex held by another thread) its two lines at 5 s and 10 s, broken into as the call returns, every save, 0 the same moment, every save, 0
a C call past the 20 s its two lines, then the kill: no save (-9) the kill: no save

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):

  • StopRequest with signals raised in this process: why the old way lost one (KeyboardInterrupt dropped 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, then SIG_IGN; never SIG_DFL or default_int_handler.
  • The break-in, in-process through 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 in main()'s own frame or once the stop has begun.
  • stop_accepting; the held signals' log lines, two signals in one round, a flood.
  • Real servers (POSIX; skipped on Windows, where a stop is TerminateProcess or 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-limit by 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.md has 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: one docker 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.md lists --stop-limit.

Notes

  • Not covered: the few tens of milliseconds between the process starting and the first line of 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.
  • On Windows the wakeup fd is the Proactor loop's own (Ctrl+C needs it), so a loop held inside a C call is not seen there until the call returns. The launcher stops a Windows server with TerminateProcess, unchanged.
  • A break-in cuts what held the loop short where it was, as every stop did before this change.

…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.
…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'.
… 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.
@Dyotson Dyotson self-assigned this Nov 15, 2026
…, 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.
…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).
… 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.
… 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
Dyotson marked this pull request as ready for review November 23, 2026 19:02
@Dyotson
Dyotson merged commit ac046a7 into main Nov 23, 2026
15 of 16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[WIP] A stop signal can be lost: SIGTERM raises KeyboardInterrupt wherever the code is, and Python ignores it inside a weakref callback

1 participant