fix: take the signal-time autosave on the game goroutine (closes #24)

The SIGHUP/SIGTERM handler gob-encoded the live game tree from the signal
goroutine while the game goroutine was mid-turn mutating it, and AutoSave
removed the save file before encoding — so the failure mode was not a
stale save but a deleted one followed by a possibly torn replacement,
with a window in which the player had neither. The suite has run under
-race since 2026-08-09 and was green because nothing had ever driven the
turn loop concurrently with a signal: evidence of untested, not of safe.

The handler no longer writes anything. AutoSaveOnSignal posts a request,
wakes the input read, and waits up to signalSaveTimeout for the game
goroutine to take it; the encode runs on the goroutine that owns the
state, at the three points where that goroutine can sit: between turns
(command), on waking from a blocked readchar, and while parked in the `!`
shell escape (runShellEscape, which now runs the shell on a helper
goroutine so a hangup during it still rescues the game).

Blocked on input is the case that matters — a dropped connection lands
while the player is thinking, so a flag checked only between turns would
never be looked at. Terminal.ReadChar therefore returns (byte, bool),
with ok false meaning "woken by Interrupt, no key", and term.Tcell posts
a tcell.EventInterrupt onto tcell's own event queue to unpark PollEvent.
readchar services the request and reads again, so no caller sees it.

Running the shell on a helper goroutine would also have moved
term.Tcell.ShellEscape's panic on a failed Screen.Resume onto it, and a
panic at the top of any goroutine terminates the process without running
the deferred calls of the others — including cmd/rogue/main.go's
`defer t.Fini()`. The tty would have been left raw on precisely the path
where the terminal is already broken, which is issue #12's failure on a
path this change created. runShellEscape therefore recovers the helper's
panic and re-raises it on the game goroutine, whose stack has the restore
in it, so "every path restores the terminal via Terminal.Fini before
exiting" stays true.

saveFile writes a temporary file in the save's own directory, fsyncs it
and renames it over the target instead of truncating in place, so a save
that fails — or never happens because the deadline ran out — leaves the
player's previous save whole.

What the handoff guarantees is stated exactly rather than flatteringly:
the encode runs on the state-owning goroutine, so the snapshot is
internally consistent and restorable, but it is not necessarily taken
between commands. readchar is reached from mid-command prompts (--More--,
askOverwrite, getStr, the direction and pack prompts) and the command has
already mutated state by then, so a save taken there freezes that command
half applied and restoring loses the rest of it.

The SIGINT/SIGQUIT no-save decision and the single-signal-read ordering
guarantee are untouched. pendingSaver reads the game out from under its
mutex rather than delegating with it held, because the delegated call now
blocks until the save is taken.
This commit is contained in:
clawbot
2026-08-09 06:47:40 +00:00
committed by sneak
parent e1bf46b241
commit 0dc4c70f18
13 changed files with 1113 additions and 98 deletions

View File

@@ -6,6 +6,8 @@ import (
"errors"
"fmt"
"os"
"path/filepath"
"time"
)
// save.c + state.c — game persistence. The hand-written, XOR-encrypted C
@@ -643,38 +645,176 @@ func (g *RogueGame) askOverwrite() saveAnswer {
}
}
// saveFile writes the saved game (save.c save_file). A failed write means
// a corrupt save, so the file is removed before reporting the error.
// saveFile writes the saved game (save.c save_file).
//
// The snapshot goes to a temporary file in the target's own directory and
// is renamed over the target, so there is no instant at which the player
// has no save file: until the rename the old file is whole, and after it
// the new one is. C wrote straight over the target, and this port did the
// same with a remove in front of it (AutoSave), so a write that failed —
// or a signal-time save cut short by the process dying — could leave the
// player with neither the old save nor a usable new one (issue #24).
//
// The temporary file is fsynced before the rename so its contents reach
// the disk ahead of the directory entry that will point at it. The
// directory itself is not fsynced: that would only matter for a machine
// that loses power in the same instant, and the old save survives that
// case anyway. A process killed mid-encode leaves its temporary file
// behind, which is litter next to a destroyed save file, and the dot
// prefix keeps it out of the way.
func (g *RogueGame) saveFile(path string) error {
f, err := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o400) //nolint:gosec,lll // G304: user-chosen save path
f, err := os.CreateTemp(filepath.Dir(path), ".rogue-save-*")
if err != nil {
return err
}
encErr := gob.NewEncoder(f).Encode(g.snapshot())
closeErr := f.Close()
tmp := f.Name()
if encErr != nil || closeErr != nil {
_ = os.Remove(path) // don't leave a corrupt save behind
writeErr := encodeSnapshot(f, g.snapshot())
if writeErr != nil {
_ = os.Remove(tmp) // never leave a half-written file behind
if encErr != nil {
return encErr
}
return closeErr
return writeErr
}
return os.Chmod(path, 0o400)
renErr := os.Rename(tmp, path)
if renErr != nil {
_ = os.Remove(tmp)
return renErr
}
return nil
}
// AutoSave silently saves to the current file name; used on SIGHUP/SIGTERM
// (save.c auto_save). Best effort by design: it runs on the way out of a
// dying process.
func (g *RogueGame) AutoSave() {
if g.FileName != "" {
_ = os.Remove(g.FileName)
_ = g.saveFile(g.FileName)
// encodeSnapshot encodes the snapshot into an open temporary file and
// closes it, leaving it read-only as the C game's saves were (save.c
// save_file). It never removes the file: its caller owns the cleanup, so
// that one place decides what happens to a failed write.
func encodeSnapshot(f *os.File, st *SaveState) error {
encErr := gob.NewEncoder(f).Encode(st)
if encErr == nil {
encErr = f.Sync()
}
if encErr == nil {
encErr = f.Chmod(0o400)
}
closeErr := f.Close()
if encErr != nil {
return encErr
}
return closeErr
}
// autoSaveRequest is one signal-triggered autosave in flight: the signal
// goroutine posts it and waits, the game goroutine performs the save and
// closes done. ok is written before done is closed and read only after,
// so the close is the happens-before edge that publishes it.
type autoSaveRequest struct {
done chan struct{}
ok bool
}
// AutoSaveOnSignal asks the game goroutine to autosave and waits up to
// timeout for it to finish, reporting whether the save actually ran
// (save.c auto_save, the SIGHUP/SIGTERM handler). It is the only entry
// point the signal goroutine may use, and it deliberately touches no game
// state: the gob encoder used to walk the live game tree from the signal
// goroutine while the game goroutine was mid-turn mutating it (issue
// #24).
//
// Blocked on input is the case that matters, since a dropped connection
// is the whole reason the handler exists: the request is posted first and
// the input read is then interrupted, so a game goroutine parked in
// ReadChar wakes, saves in readchar, and reads again. A game goroutine
// that is running turns instead picks the request up between turns, in
// command; one parked in the `!` shell escape picks it up in
// runShellEscape.
//
// The wait is bounded because the signal goroutine's job is to get the
// process out. If the game goroutine is somewhere with no service point
// at all, the deadline expires, this reports false, and the caller
// restores the terminal and exits — leaving the player's previous save
// file exactly as it was, which is the point of the rename in saveFile.
func (g *RogueGame) AutoSaveOnSignal(timeout time.Duration) bool {
req := &autoSaveRequest{done: make(chan struct{})}
select {
case g.sigSave <- req:
default:
// A request is already queued and unserviced, or there is no
// game loop to service one; either way this one would not be
// answered either.
return false
}
g.scr.Interrupt()
timer := time.NewTimer(timeout)
defer timer.Stop()
select {
case <-req.done:
return req.ok
case <-timer.C:
return false
}
}
// serviceAutoSaveRequest performs a pending signal-triggered autosave, if
// one is waiting, and otherwise returns at once. It runs on the game
// goroutine — that is the whole design — so it must only be called where
// that goroutine is not itself inside the encode: between turns, or while
// parked waiting for input or for the shell escape.
//
// What is guaranteed, exactly: the encode runs on the one goroutine that
// owns the state, so the snapshot is internally consistent and always
// restorable. It is *not* guaranteed to be a between-commands snapshot.
// Two of the three service points are, but readchar is reached from
// prompts raised part-way through a command — --More-- on the second
// message of a turn, askOverwrite, getStr, the direction and pack prompts
// — and by then the command has already mutated state: fight sets
// g.Count and g.Quiet and runs runTo before any message, revealXeroc
// writes tp.Disguise before emitting one. A save serviced at such a
// prompt therefore freezes that command half applied; restoring re-enters
// playit at the top of command, so the rest of that command never runs
// and the player loses its remaining effects. That is a coherent game
// state, one turn's worth of effects short — strictly better than the
// torn encode this replaced, and the cost of being able to save a player
// whose line dropped mid-prompt at all.
func (g *RogueGame) serviceAutoSaveRequest() {
select {
case req := <-g.sigSave:
g.runAutoSaveRequest(req)
default:
}
}
// runAutoSaveRequest answers one request: save, then release the waiter.
func (g *RogueGame) runAutoSaveRequest(req *autoSaveRequest) {
req.ok = g.autoSave()
close(req.done)
}
// autoSave silently saves to the current file name (save.c auto_save),
// reporting whether it wrote a save. Game-goroutine only — reach it
// through AutoSaveOnSignal from anywhere else.
//
// The error is not surfaced: there is no player to tell, since the
// terminal is on its way out, and nothing sensible to do about it. It is
// reported to the waiting signal goroutine as a failed save rather than
// discarded outright, which is what the old `_ =` here used to do.
func (g *RogueGame) autoSave() bool {
if g.FileName == "" {
return false
}
return g.saveFile(g.FileName) == nil
}
// ErrSaveOutOfDate reports a save file from an incompatible version.
@@ -746,6 +886,7 @@ func Restore(path string, params Params) (*RogueGame, error) {
FileName: path,
rogueOpts: params.RogueOpts,
restored: true,
sigSave: make(chan *autoSaveRequest, 1),
}
g.scr = NewScreen(params.Term)
g.Msgs.attach(g.scr, g.look, g.readchar)