diff --git a/.github/scripts/test-windows.ps1 b/.github/scripts/test-windows.ps1 index b75da40..74a51e0 100644 --- a/.github/scripts/test-windows.ps1 +++ b/.github/scripts/test-windows.ps1 @@ -73,7 +73,8 @@ $required = @( 'TestAnalyzeInputsDescribeTheSameRecordEntry', 'TestAnalyzeTerminalAndUnsearchedResultsAreExplicit', 'TestAnalyzeRefusalsDoNotWriteState', - 'TestAnalyzeDoesNotRedirectAnUnreadableExactGame' + 'TestAnalyzeDoesNotRedirectAnUnreadableExactGame', + 'TestPlayNowCutsAMaxSearchShort' ) $missing = @($required | Where-Object { -not $passes.ContainsKey($_) }) $missingStorage = @() diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c229ae9..180d2bc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -196,9 +196,12 @@ jobs: # search enough to change what they measure: on a 24x24 board at the # measurement budgets the depths reached fall from beginner 1, intermediate 3, # pro 4 to 1, 2 and 2, so the tiers stop being distinguishable and a strength - # number produced under the detector is not the engine's. The Unix terminal - # harness delegates its PTY to tmux; the concurrent ConPTY implementation is - # covered separately by the native Windows amd64 race job below. + # number produced under the detector is not the engine's. The progress tests + # are the exception and run under it by name: they measure no strength, and + # their subject is a snapshot read from another goroutine while a search + # publishes it. The Unix terminal harness delegates its PTY to tmux; the + # concurrent ConPTY implementation is covered separately by the native + # Windows amd64 race job below. race: runs-on: ubuntu-latest steps: @@ -219,6 +222,7 @@ jobs: run: | go test -race -count=1 ./internal/netplay/ ./internal/app/ ./internal/cli/ \ ./internal/leaderboard/ ./internal/profile/ + go test -race -count=1 -run '^TestProgress' ./internal/bot/ # Native Windows executes the same product scenarios through ConPTY. The # script fails if any terminal test skips or if its positive controls did diff --git a/CHANGELOG.md b/CHANGELOG.md index b1c1069..bd6c6fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,28 @@ project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Added + +- A live line while the bot thinks: time since its search began, then the + deepest completed iteration and its node count. Only completed work of the + search behind the coming move is shown, and it is read without waiting for + the search. In a terminal too small for the panel, the status line leads + with `esc play now` and the time and completed depth. +- `esc` while the bot is searching plays now, exactly once: the bot makes its + tier's ordinary choice from the work it has finished — the ranking of its + last completed iteration, or its move ordering before one — and the + announcement names the completed depth. The beginner tier still picks among + its near-best candidates. Leaving still discards the search. +- `i` in a bot game shows the figures of the search behind the bot's last + move: completed depth, nodes and time in all, and stop reason. A status line + too narrow for all of them gives up whole items, the stop reason before the + time and the nodes, and always keeps the move and its completed depth. + +### Fixed + +- A search left running by a finished bot game can no longer have its move + played in the rematch. + ## [0.7.0] - 2026-09-12 ### Added diff --git a/docs/MANUAL.md b/docs/MANUAL.md index b48c0aa..df2c2de 100644 --- a/docs/MANUAL.md +++ b/docs/MANUAL.md @@ -323,9 +323,10 @@ none of those. | `enter` | Places the peg when none is staged yet, and commits the turn once one is. | | `x` | Enter or leave link mode. | | `1`-`8` | Only in link mode: toggle the link in that direction. | -| `esc` | Leave link mode. | +| `esc` | Leave link mode. Otherwise, while a bot is searching for its move: play now, with the search it has finished. | | `a` | Abort the turn: the board goes back to how it stood when your turn began. | | `?` | In a bot game: the move the bot would play, and why. | +| `i` | In a bot game: the figures of the search behind the bot's last move. Offered once the bot has moved, and not while it is searching. | | `s` | Take the swap option, while it is on offer. | | `d` | Offer a draw, or accept the one on offer. | | `r` | Resign. | @@ -530,6 +531,37 @@ recursive nodes, all position analyses including tactical probes, completed depth, elapsed search time and the actual stop reason. Nodes and analyses are different quantities; neither is an MCTS simulation count. +While the bot searches, the panel's thinking line shows how long it has been at +it and, once its first iteration has finished, the deepest iteration it has +completed and the nodes that work took. Those two figures are completed work +only: they hold still while an iteration is in progress, and before the first +one finishes the line shows the time alone. In a terminal too small for the +panel, the status line leads with `esc play now` and a short form of the same +line — the time and the completed depth, as in `2.4s d4`, or the depth alone +when the two do not fit — ahead of whose turn it is. Press `esc` to have the +bot play now. The search stops and the bot makes its tier's ordinary choice +from the work it has finished: from the moves as its last completed iteration +scored them or, if none had finished, as its ordering heuristic ranks them. The +beginner tier still picks among its near-best candidates, as it does on every +move; the other tiers play the move that ranking puts first. The line +announcing the move says it was played early and at what completed depth. The +move is played once, like any other. Leaving the game still discards a search +in progress, and a rematch never plays a move from, or shows the progress of, +a search the previous game left running. Once the bot has moved, `i` shows +that search's figures as `bot.StatsOf` reports them: the depth it completed, +its nodes and time in all, and why it stopped — out of time, stopped by play +now, and so on. +The nodes in all include work on an iteration the search did not finish, so +they can be more than the thinking line last showed beside the same depth. A +search that stopped because it found a winning line has found one among the +moves it searched, which is not a proof. A full principal variation is not +shown. Where the status line is too narrow for the whole sentence, it gives up +whole items rather than cutting one: the opening words first, then why the +search stopped, then the long wording of the depth, which becomes `d4`, then +the time and the nodes. The move and its completed depth always show, at the +least as `E3: d4`, and nodes or time, wherever they show, are still given as in +all. + Asking for a hint runs the same search with the highest-effort settings the package has, whichever tier you are playing, and gives you the move it would play, a line on why, and the holes that reason is about, marked on the board. It keeps a two-second diff --git a/internal/app/gamescreen.go b/internal/app/gamescreen.go index 2c9d822..6c2aa31 100644 --- a/internal/app/gamescreen.go +++ b/internal/app/gamescreen.go @@ -6,8 +6,10 @@ import ( "fmt" "math/bits" "os" + "slices" "strings" "sync" + "sync/atomic" "time" tea "charm.land/bubbletea/v2" @@ -53,6 +55,8 @@ const ( gaRematch gaYes gaNo + gaSearchInfo + gaPlayNow ) // gamePhase is the screen state a key applies in. A finished game and a game @@ -79,8 +83,8 @@ type gameBinding struct { } // gameBindings are the keys the game adds to the board keymap. Keys used while -// a board is active may not collide with ui.DefaultKeymap; -// TestGameKeysDoNotShadowTheBoardKeymap holds that line. +// a board is active may not collide with ui.DefaultKeymap in a context the game +// key acts in; TestGameKeysDoNotShadowTheBoardKeymap holds that line. var gameBindings = []gameBinding{ {gaHint, []string{"?"}, phasePlay, "?", "hint: what to play and why"}, {gaSwap, []string{"s"}, phasePlay, "s", "take the swap option"}, @@ -88,6 +92,10 @@ var gameBindings = []gameBinding{ {gaResign, []string{"r"}, phasePlay, "r", "resign"}, {gaLiftPeg, []string{"p"}, phasePlay, "p", "lift one of your pegs"}, {gaCode, []string{"c"}, phasePlay | phaseFinished | phaseStopped, "c", "the exchange: your code and theirs"}, + // The figures of the search behind the engine's last move. A finished game + // keeps the key, because the move that ended it is the one most worth + // asking about. + {gaSearchInfo, []string{"i"}, phasePlay | phaseFinished | phaseStopped, "i", "stats of the engine's last search"}, // Upper case, because the obvious mnemonic is taken by resign and the two // would be one slip apart on a screen where resign is refused anyway. The // board already uses the shifted letters for its own second family of @@ -95,17 +103,45 @@ var gameBindings = []gameBinding{ {gaRematch, []string{"R"}, phaseFinished, "R", "rematch: another game, sides swapped"}, {gaYes, []string{"y"}, phaseConfirm, "y", "yes"}, {gaNo, []string{"n", "esc"}, phaseConfirm, "n", "no, carry on"}, -} - -func gameKeyLookup(key string) (gameBinding, bool) { + // Escape is also no to a question, above, and leaves link mode on the + // board. gameKeyLookup gives the question its row and gameKeyContexts gives + // link mode the key. This row comes second so that a phase in which neither + // game meaning applies finds the question's row first and passes the key on + // to the board, as it did before escape meant play now. + {gaPlayNow, []string{"esc"}, phasePlay, "esc", "play now, from the search so far"}, +} + +// gameKeyLookup finds the binding a key has in a phase. Escape is the one key +// with two game meanings, no to a question and play now while the engine +// thinks, so the binding live in the phase wins. Otherwise the first binding +// holding the key is returned, which is what lets a key pressed outside its +// phase still be refused with its own reason. +func gameKeyLookup(key string, phase gamePhase) (gameBinding, bool) { + var first gameBinding + found := false for _, b := range gameBindings { - for _, k := range b.keys { - if k == key { - return b, true - } + if !slices.Contains(b.keys, key) { + continue + } + if b.phases&phase != 0 { + return b, true + } + if !found { + first, found = b, true } } - return gameBinding{}, false + return first, found +} + +// gameKeyContexts are the board contexts a game key may act in. Every game key +// works in both except play now, whose key also leaves link mode: a player +// editing links who presses escape means to stop editing rather than to hurry +// the engine, so in link mode the board keeps the key. +func gameKeyContexts(a gameAction) ui.Context { + if a == gaPlayNow { + return ui.CtxBoard + } + return ui.CtxBoard | ui.CtxLink } // keyPhase names the mutually exclusive state whose actions are live. A result @@ -141,6 +177,13 @@ func (s *gameScreen) actionAvailable(phase gamePhase, ga gameAction, board ui.Ac if phases&phase == 0 { return false } + ctx := ui.CtxBoard + if s.linkMode { + ctx = ui.CtxLink + } + if gameKeyContexts(ga)&ctx == 0 { + return false + } switch ga { case gaHint: return s.cfg.Hints && s.cfg.HintFor != nil @@ -152,6 +195,12 @@ func (s *gameScreen) actionAvailable(phase gamePhase, ga gameAction, board ui.Ac return s.corr != nil case gaRematch: return s.rematchOffered() + case gaSearchInfo: + // While a search runs, the last one's figures would read as this + // one's. + return !s.botThinking && s.lastSearch.Generation != 0 + case gaPlayNow: + return s.botThinking && !s.search.early default: return true } @@ -173,15 +222,19 @@ func (s *gameScreen) actionAvailable(phase gamePhase, ga gameAction, board ui.Ac } // botMoveMsg is a move the opponent engine chose. gen names the search it -// answers so a move from a search the screen has moved past is dropped. +// answers so a move from a search the screen has moved past is dropped. final +// is the engine's own account of that search, taken as it ended and before any +// other search could replace it; a zero Generation means the engine gave none. type botMoveMsg struct { - gen int - move game.Point - err error + gen int + move game.Point + final bot.SearchProgress + err error } -// botTickMsg advances the thinking indicator. -type botTickMsg struct{} +// botTickMsg advances the thinking indicator. at is when the tick fired, which +// is the clock the search's elapsed time is read against. +type botTickMsg struct{ at time.Time } // netEventMsg is one thing the remote opponent or the connection did. type netEventMsg struct{ ev netplay.Event } @@ -209,6 +262,10 @@ type gameScreen struct { // divergence — things that stay true until the player leaves. message string notice string + // figures are the finished search's figures as the search key last + // showed them, in every form the status line may use, widest first; + // fitMessage says when they stand. + figures []string // stopped means no further play is possible on this screen: the game ended, // the connection dropped, or the two ends disagree about the position. stopped bool @@ -249,6 +306,13 @@ type gameScreen struct { botThinking bool botCancel context.CancelFunc spinner int + // search is what the screen knows of the engine's move search in flight. + // lastSearch is the engine's final account of the last search whose move + // was played, and lastSearchMove that move; a zero Generation means there + // is none, since the engine numbers its searches from one. + search botSearch + lastSearch bot.SearchProgress + lastSearchMove game.Point session netplay.Session // remoteSide is the side the networked opponent plays, NoPlayer in a local @@ -488,6 +552,7 @@ func (s *gameScreen) update(msg tea.Msg) (tea.Model, tea.Cmd) { case botTickMsg: if s.botThinking && !s.leaving { s.spinner++ + s.watchSearch(msg.at) return s, s.spinnerTick() } case hintMsg: @@ -546,7 +611,9 @@ func (s *gameScreen) handleKey(m tea.KeyPressMsg) tea.Cmd { return s.handleConfirm(key) } s.message = "" - if b, ok := gameKeyLookup(key); ok && + // A game key its context keeps from it goes on to the board keymap, which + // is how escape still leaves link mode. + if b, ok := gameKeyLookup(key, phase); ok && gameKeyContexts(b.action)&ctx != 0 && (b.phases&phase != 0 || b.action == gaRematch || ((phase == phaseFinished || phase == phaseStopped) && b.phases&phasePlay != 0)) { if !s.actionAvailable(phase, b.action, ui.ActNone) { @@ -555,7 +622,8 @@ func (s *gameScreen) handleKey(m tea.KeyPressMsg) tea.Cmd { // arrange another game and a non-correspondence player why there // is no exchange. Finished/stopped mutation and advice actions // stop here, before they reach a mutator or engine. Confirmation - // keys do not claim a board key outside confirmation. + // keys do not claim a board key outside confirmation. Play now's + // refusal is silence, for the reason playNow gives. if phase == phasePlay || b.action == gaRematch || b.action == gaCode { return s.handleGameAction(b.action) } @@ -641,7 +709,7 @@ func (s *gameScreen) confirmKey() tea.Cmd { } func (s *gameScreen) handleConfirm(key string) tea.Cmd { - b, ok := gameKeyLookup(key) + b, ok := gameKeyLookup(key, phaseConfirm) if !ok || !s.actionAvailable(phaseConfirm, b.action, ui.ActNone) { return nil } @@ -675,6 +743,10 @@ func (s *gameScreen) handleGameAction(a gameAction) tea.Cmd { } else { s.corr.open = true } + case gaSearchInfo: + s.showLastSearch() + case gaPlayNow: + s.playNow() case gaResign: if side, ok := s.actingSide(); !ok { s.message = "there is nobody here to resign" @@ -1089,7 +1161,9 @@ func (s *gameScreen) maybeBotMove() tea.Cmd { if s.stopped || s.leaving || s.botThinking || s.g.Result().Over() { return nil } - engine := s.mover().Bot + // Every engine seat was put behind a serialBot when the screen was built, + // so a seat that holds none has no engine to ask. + engine, _ := s.mover().Bot.(*serialBot) if engine == nil { return nil } @@ -1100,22 +1174,34 @@ func (s *gameScreen) maybeBotMove() tea.Cmd { s.botGen++ gen := s.botGen s.spinner = 0 + // The start comes from the wall clock rather than deps.Clock, because it + // stands in for the engine's own start, which the engine takes from the + // wall clock, and the tick times it is subtracted from are the wall + // clock's too. + began := time.Now() + req := new(searchRequest) + s.search = botSearch{engine: engine, req: req, began: began, now: began} + s.lastSearch, s.lastSearchMove = bot.SearchProgress{}, game.Point{} pos := s.g.Clone() return tea.Batch( func() tea.Msg { - move, err := engine.Move(ctx, pos) - return botMoveMsg{gen: gen, move: move, err: err} + move, final, err := engine.move(ctx, pos, req) + return botMoveMsg{gen: gen, move: move, final: final, err: err} }, s.spinnerTick(), ) } func (s *gameScreen) spinnerTick() tea.Cmd { - return tea.Tick(gsSpinnerInterval, func(time.Time) tea.Msg { return botTickMsg{} }) + return tea.Tick(gsSpinnerInterval, func(at time.Time) tea.Msg { return botTickMsg{at: at} }) } func (s *gameScreen) applyBotMove(msg botMoveMsg) tea.Cmd { - if msg.gen != s.botGen || s.leaving { + // A move is taken only from the search the screen is waiting on. Leaving + // drops it, and so does having no search in flight, which is how a rematch + // that has not started searching ignores the answer to a search the + // finished game left running. + if msg.gen != s.botGen || !s.botThinking || s.leaving { return nil } s.botThinking = false @@ -1133,7 +1219,18 @@ func (s *gameScreen) applyBotMove(msg botMoveMsg) tea.Cmd { return nil } s.hint.clear() - s.message = fmt.Sprintf("%s played %s", s.seatName(s.g.Turn().Opponent()), msg.move) + // The engine's account of the search came with the move, read under the + // serialiser's lock as the search ended, so it is this search's even when + // another search has taken the engine since. An engine that reported no + // search for the request sent none. + if msg.final.Generation != 0 { + s.lastSearch, s.lastSearchMove = msg.final, msg.move + } + who := s.seatName(s.g.Turn().Opponent()) + s.message = fmt.Sprintf("%s played %s", who, msg.move) + if s.search.early { + s.message = s.playedEarlyText(who, msg.move) + } if s.g.Result().Over() { return s.finish() } @@ -1147,6 +1244,270 @@ func (s *gameScreen) cancelBot() { } } +// botSearch is what the screen knows of one engine move search while it runs. +type botSearch struct { + engine *serialBot + // req is the request's claim on the engine's progress: the generation its + // search runs under, once the search has the engine. + req *searchRequest + // began is when the screen asked, which stands in for the engine's own + // start until a snapshot of this search has been read, and started is + // that start once one has; now is the time of the latest tick. + began, started, now time.Time + // done is the latest snapshot of this search taken while it was running + // with an iteration finished, and zero before one. The snapshot the search + // publishes as it ends is left out: its counters are the whole search's, + // the iteration it did not finish included, and belong to the finished + // figures that come with the move rather than to a line about completed + // iterations. + done bot.SearchProgress + // early records that the player asked for the move now. + early bool +} + +// searchRequest ties one move request to the search that answers it. +// +// The engine numbers its move searches, but the number a request's search +// runs under is not known when the screen asks: requests queue at the +// serialiser, and they need not reach the engine in the order they were made. +// A finished game's search that had not yet reached the engine can get there +// after the rematch's, and then the engine's latest snapshot is that one's. So +// serialBot.move stores the number here with the engine held, just before the +// search starts, and the screen, reading on its own goroutine, takes only +// snapshots carrying exactly that number. Zero means the search is still +// waiting for the engine. +type searchRequest struct { + gen atomic.Uint64 +} + +// watchSearch reads the engine's progress on a tick. The read goes through +// serialBot.Progress, which does not wait for the search holding the engine, +// so the interface stays live however long the search runs. A snapshot of any +// other search, one that ran before this one or one a finished game had +// queued behind it, is ignored rather than shown as this one's. +func (s *gameScreen) watchSearch(at time.Time) { + if !at.IsZero() { + s.search.now = at + } + want := s.search.req.gen.Load() + if want == 0 { + return + } + p := s.search.engine.Progress() + if p.Generation != want { + return + } + s.search.started = p.Started + if p.Running && p.Completed { + s.search.done = p + } +} + +// searchElapsed is how long the search has been at it. It is derived from when +// the search began rather than read from the engine, because it is the one +// figure that moves between iterations. +func (s *gameScreen) searchElapsed() string { + start := s.search.began + if !s.search.started.IsZero() { + start = s.search.started + } + return gsSeconds(s.search.now.Sub(start)) +} + +// searchDone is the last iteration the search has completed, and false before +// one has: there is no finished work to show, and a depth of nought is not +// one. A win taken without searching completes no iteration either. +func (s *gameScreen) searchDone() (bot.SearchProgress, bool) { + p := s.search.done + if p.Completed && p.Depth > 0 { + return p, true + } + return bot.SearchProgress{}, false +} + +// searchProgressText is the live account of the engine's search: how long it +// has been at it and what it has finished. The depth and node count are those +// of the last iteration the engine completed, so the line never shows work in +// progress as work done, and before the first iteration completes it shows +// the time alone. +func (s *gameScreen) searchProgressText() string { + if !s.botThinking { + return "" + } + text := s.searchElapsed() + if p, ok := s.searchDone(); ok { + text += fmt.Sprintf(" · depth %d done · %d nodes", p.Depth, p.Stats.Nodes) + } + return text +} + +// searchProgressShort is the live account cut down to room cells, for the +// status line of a layout with no panel, which it shares with the play-now key. +// It gives the time and the completed depth while both fit, and then the depth +// alone: a player can count the seconds for themselves, but not the depth. The +// node count is left out, as the figure a line this short can best spare. +func (s *gameScreen) searchProgressShort(room int) string { + if !s.botThinking { + return "" + } + elapsed := s.searchElapsed() + p, ok := s.searchDone() + if !ok { + return elapsed + } + depth := fmt.Sprintf("d%d", p.Depth) + if both := elapsed + " " + depth; ansi.StringWidth(both) <= room { + return both + } + return depth +} + +// playNow asks the engine for its move without waiting for the rest of the +// search. The search's context is cancelled and nothing else: its generation +// is still the one the screen is waiting on, so the move it returns, the +// tier's ordinary choice from the work the search had finished, is played +// exactly as a move that ran its course would be. Leaving and a rematch are +// still what drop a search's move. +// +// Escape did nothing on this board before it meant play now, and it goes on +// doing nothing when the engine is not thinking: it is the key players press +// to back out of things, and a refusal every time would be noise. +func (s *gameScreen) playNow() { + if !s.botThinking || s.search.early { + return + } + s.search.early = true + s.cancelBot() + s.message = fmt.Sprintf("asked %s to play now", s.seatName(s.g.Turn())) +} + +// playedEarlyText says a move came early, and from how much search. The depth +// is the engine's own last completed iteration; with none completed the move +// came from the ordering heuristic alone, and the line says so rather than +// calling that a depth of nought. A search that had already ended on its own +// terms when the request reached it, out of time or on a win it needed no +// search for, played the move it would have played anyway and is reported as +// an ordinary move. "canceled" is bot.SearchStats's reason for a search its +// context stopped. +func (s *gameScreen) playedEarlyText(who string, move game.Point) string { + final := s.lastSearch + switch { + case final.Generation == 0: + return fmt.Sprintf("%s played %s early, as asked", who, move) + case final.Stats.StopReason != "canceled": + return fmt.Sprintf("%s played %s", who, move) + case final.Stats.Depth > 0: + return fmt.Sprintf("%s played %s early, from its completed depth %d", who, move, final.Stats.Depth) + } + return fmt.Sprintf("%s played %s early, before any depth was complete", who, move) +} + +// showLastSearch answers the search key with the figures of the search behind +// the engine's last move, as the engine reported them when Move returned. The +// message is the whole sentence; the status line shows the widest of its forms +// that fits, which fitMessage picks. +func (s *gameScreen) showLastSearch() { + switch { + case s.cfg.Seats[game.Vertical].Bot == nil && s.cfg.Seats[game.Horizontal].Bot == nil: + s.message = "there is no engine in this game" + case s.botThinking: + s.message = "the engine is still searching: its figures come with its move" + case s.lastSearch.Generation == 0: + s.message = "no engine move in this game has search figures to show yet" + default: + s.figures = s.lastSearchForms() + s.message = s.figures[0] + } +} + +// lastSearchForms is the finished search in one line, every figure from the +// engine's final account: the deepest iteration it completed, never a depth of +// nought presented as one, then its work and its time, and why it stopped. The +// nodes and the time are the whole search's, the iteration it was part way +// through when it stopped included, which is why they are said to be in all: +// the thinking line's nodes were the completed iterations' alone, and a larger +// figure here beside the same depth is the unfinished one's work, not a +// discrepancy. +// +// That sentence is the first of several forms, widest first, because the +// status line is the only place the figures are shown, and cut to the width +// the sentence gave them up: at the minimum width its opening words alone +// filled the line, and at forty columns the nodes and the time were cut off. +// Each shorter form leaves out whole items rather than part of one: the opening +// words, which say nothing the key did not, then the reason, then the long +// wording of the depth, then the time and then the nodes, though the time is +// kept on its own where it fits and the nodes do not. The move and its +// completed depth are the last to go. Every form that gives nodes or time +// still says they are in all, so that none of them passes the whole search's +// work off as the completed iteration's. +func (s *gameScreen) lastSearchForms() []string { + st := s.lastSearch.Stats + move := s.lastSearchMove.String() + depth, short := "no depth completed", "no depth" + if st.Depth > 0 { + depth, short = fmt.Sprintf("depth %d completed", st.Depth), fmt.Sprintf("d%d", st.Depth) + } + nodes, secs := fmt.Sprintf("%d nodes", st.Nodes), gsSeconds(st.Elapsed) + figures := fmt.Sprintf("%s: %s · %s and %s in all", move, depth, nodes, secs) + why := "" + if text := searchStopText(st.StopReason); text != "" { + why = " · " + text + } + return []string{ + "the search behind " + figures + why, + figures + why, + figures, + fmt.Sprintf("%s: %s · %s, %s in all", move, short, nodes, secs), + fmt.Sprintf("%s: %s · %s in all", move, short, nodes), + fmt.Sprintf("%s: %s · %s in all", move, short, secs), + move + ": " + short, + } +} + +// fitMessage is the message as a status line width cells wide can show it. +// The finished search's figures are the one message with shorter forms of its +// own, and the forms stand only while the message is still the sentence they +// were made with: whatever writes the message next replaces the sentence, and +// so retires the forms without having to know they exist. +func (s *gameScreen) fitMessage(width int) string { + if len(s.figures) == 0 || s.message != s.figures[0] { + return s.message + } + for _, form := range s.figures { + if ansi.StringWidth(form) <= width { + return form + } + } + return s.figures[len(s.figures)-1] +} + +// searchStopText puts one of bot.SearchStats's stop reasons as a player would. +// A cancelled search is named as play now because that is the only +// cancellation whose move this screen plays: leaving and a finished game drop +// the move of the search they cancel. +func searchStopText(reason string) string { + switch reason { + case "time": + return "out of time" + case "depth": + return "every depth searched" + case "decided": + // The search stops deepening once it finds a win among the moves its + // width caps let it look at. A defence the caps threw away was never + // searched, so this is a claim about the tree and not a proof. + return "found a winning line among the moves it searched, not a proof" + case "nodes": + return "node ceiling reached" + case "immediate": + return "a winning hole, no search needed" + case "canceled": + return "stopped by play now" + case "no-move": + return "nowhere to play" + } + return reason +} + // --- hints ------------------------------------------------------------------ // askHint consults the engine on the player's own position. It is only offered @@ -1609,6 +1970,12 @@ func (s *gameScreen) rematch() tea.Cmd { if err := s.depart(); err != nil { return Fail(err) } + // Generations carry on from this game's. A search this game left running + // is cancelled but not waited for, and its answer goes to whichever screen + // is showing when it arrives, which by then is the rematch. Counting from + // one again, the rematch's first search would share that answer's number + // and play the old game's move on the new board. + next.botGen = s.botGen next.message = "rematch: the sides are swapped" return Replace(next) } @@ -1791,6 +2158,9 @@ func (s *gameScreen) panelLines(arr ui.Arrangement) []string { addWrapped(s.style(s.styles.Message, s.notice)) } else { add(s.headlineText()) + if progress := s.searchProgressText(); progress != "" { + addWrapped(s.style(s.styles.PanelText, progress)) + } } if s.swapOffered() { blank() @@ -1954,8 +2324,12 @@ func (s *gameScreen) headlineText() string { case s.handover: return s.style(s.styles.Message, s.handoverPrompt()) case s.botThinking: - return s.style(s.styles.PanelText, fmt.Sprintf("%s is thinking %s", - s.seatName(s.g.Turn()), gsSpinnerFrames[s.spinner%len(gsSpinnerFrames)])) + doing := "is thinking" + if s.search.early { + doing = "is playing now" + } + return s.style(s.styles.PanelText, fmt.Sprintf("%s %s %s", + s.seatName(s.g.Turn()), doing, gsSpinnerFrames[s.spinner%len(gsSpinnerFrames)])) case !s.mover().Human(): return s.style(s.styles.PanelText, s.waitingText()) } @@ -2208,10 +2582,12 @@ func (s *gameScreen) openingPeg() string { // last keypress when there is one, and otherwise the keys that matter now; when // the terminal is too narrow for a panel it also carries whose turn it is, // because there is nowhere else for that to go, and advice once it has been -// asked for, which leads the line ahead of the turn. +// asked for, which leads the line ahead of the turn. While the engine searches, +// the key that cuts the search short and how far the search has got lead even +// that. func (s *gameScreen) statusLine(arr ui.Arrangement) string { if s.message != "" { - return s.style(s.styles.Status, gsTruncate(s.message, arr.Width)) + return s.style(s.styles.Status, gsTruncate(s.fitMessage(arr.Width), arr.Width)) } phase := s.keyPhase() if phase == phasePlay && s.hint.shown && s.notice == "" { @@ -2221,10 +2597,31 @@ func (s *gameScreen) statusLine(arr ui.Arrangement) string { return s.style(s.styles.Status, s.hint.statusText(arr.Width)) } var parts []string + playNow := "" + if s.actionAvailable(phase, gaPlayNow, ui.ActNone) { + playNow = s.gameKeyLabel(gaPlayNow) + " play now" + } + // lead counts the parts at the front of the line that have to reach the + // screen whole; see the end of this function. + lead := 0 if arr.Panel == ui.PanelNone { if s.notice != "" { return s.style(s.styles.Status, gsTruncate(s.notice, arr.Width)) } + if s.botThinking { + // With no panel this line is the only place the search and the + // key that cuts it short can be seen. The headline used to come + // first, and at the minimum width it filled the line and cut both + // off. The key leads now, then the search, cut down to the room + // the key leaves, and the headline has whatever width is left. + room := arr.Width + if playNow != "" { + parts = append(parts, playNow) + room -= ansi.StringWidth(playNow + " · ") + } + parts = append(parts, s.searchProgressShort(room)) + lead = len(parts) + } parts = append(parts, gsPlain(s.headlineText())) if h := s.hint.statusText(arr.Width); h != "" { parts = append(parts, h) @@ -2258,6 +2655,12 @@ func (s *gameScreen) statusLine(arr ui.Arrangement) string { case s.linkMode: parts = append(parts, s.keymap.HintLine(ui.CtxLink, ui.ActToggleLink, ui.ActExitMode, ui.ActConfirm)) default: + if playNow != "" && arr.Panel != ui.PanelNone { + // The one key that does anything about a search in progress leads + // the line, so a narrow terminal cuts something else first. A line + // with no panel has already put it there, ahead of the search. + parts = append(parts, playNow) + } parts = append(parts, s.keymap.HintLine(ui.CtxBoard, ui.ActPlacePeg, ui.ActConfirm, ui.ActLinkMode, ui.ActAbortTurn), s.quitHint()) if s.actionAvailable(phase, gaCode, ui.ActNone) { @@ -2274,7 +2677,20 @@ func (s *gameScreen) statusLine(arr ui.Arrangement) string { } parts = append(parts, s.gameKeyLabel(gaDraw)+" draw", s.gameKeyLabel(gaResign)+" resign") } - return s.style(s.styles.Status, gsTruncate(strings.Join(parts, " · "), arr.Width)) + line := strings.Join(parts, " · ") + if lead > 0 && ansi.StringWidth(line) > arr.Width { + // A cut line ends in a mark, and ui.Compose shortens such a line to + // the last item it can be sure is whole: an item with the mark + // straight after it may have been cut through, so it goes. Where the + // width leaves no cell past the lead for the separator after it, the + // mark lands straight after the search's figures, and they would go. + // The lead is shown alone then, unmarked: the figures are worth more + // than a mark saying that the headline and the other keys did not fit. + if head := strings.Join(parts[:lead], " · "); ansi.StringWidth(head)+2 > arr.Width { + line = head + } + } + return s.style(s.styles.Status, gsTruncate(line, arr.Width)) } // quitHint is the terse form of the quit key for the status line. A game opened @@ -2462,6 +2878,13 @@ func gsPad(text string, width int) string { return text } +// gsSeconds writes a search time to a tenth of a second, as fine as a line +// redrawn on every spinner frame can usefully show. A time before its own +// start, a tick read against a start stamped after it, is shown as none. +func gsSeconds(d time.Duration) string { + return fmt.Sprintf("%.1fs", max(d, 0).Seconds()) +} + // gsTruncate and gsWrap are the panel's names for the package's one truncator // and wrapper. The truncator marks what it cut: a hard clip reads as though the // product mangled the line, where a marked one reads as a shortened line. @@ -2490,7 +2913,7 @@ func (s *gameScreen) style(st lipgloss.Style, text string) string { // state of its search. The screen runs searches in commands, on their own // goroutines, and the same engine may be asked for a move and for a hint, so the // calls have to take turns. Tier is a constant of the engine and is read while -// drawing, so it does not wait. +// drawing, so it does not wait, and neither does Progress. type serialBot struct { lock *sync.Mutex engine bot.Bot @@ -2504,6 +2927,28 @@ func (s *serialBot) Move(ctx context.Context, g *game.Game) (game.Point, error) return s.engine.Move(ctx, g) } +// move is Move for the screen's own move requests, which need to know which of +// the engine's searches answered them. Both ends of that are settled while the +// lock is held, because only then is the engine this request's alone. The +// search's generation is read just before the search starts, so the search is +// exactly the next one, and stored in req for the screen to read while the +// search runs. The final snapshot is read as soon as the search returns, +// before a request queued behind this one can start another. An engine that +// reported no search under that generation, because it keeps no progress or +// refused the request before searching, gives the zero account. +func (s *serialBot) move(ctx context.Context, g *game.Game, req *searchRequest) (game.Point, bot.SearchProgress, error) { + s.lock.Lock() + defer s.lock.Unlock() + gen := bot.ProgressOf(s.engine).Generation + 1 + req.gen.Store(gen) + move, err := s.engine.Move(ctx, g) + final := bot.ProgressOf(s.engine) + if final.Generation != gen || final.Running { + final = bot.SearchProgress{} + } + return move, final, err +} + func (s *serialBot) Hint(ctx context.Context, g *game.Game) (bot.Hint, error) { s.lock.Lock() defer s.lock.Unlock() @@ -2521,3 +2966,10 @@ func (s *serialBot) Stats() bot.SearchStats { defer s.lock.Unlock() return bot.StatsOf(s.engine) } + +// Progress passes on the engine's report of its move search without taking the +// lock. It is the one accessor that must not: it is read on every spinner tick +// while a search holds the lock, from Update, which a wait would freeze for the +// whole search. bot.ProgressOf promises an answer that does not wait on the +// search, so there is nothing here to serialise. +func (s *serialBot) Progress() bot.SearchProgress { return bot.ProgressOf(s.engine) } diff --git a/internal/app/gamescreen_progress_test.go b/internal/app/gamescreen_progress_test.go new file mode 100644 index 0000000..6dc9426 --- /dev/null +++ b/internal/app/gamescreen_progress_test.go @@ -0,0 +1,884 @@ +package app + +import ( + "context" + "fmt" + "regexp" + "strings" + "sync" + "testing" + "time" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" + + "github.com/BAKocska/twixtui/internal/bot" + "github.com/BAKocska/twixtui/internal/game" + "github.com/BAKocska/twixtui/internal/gamestore" +) + +// --- a search the test runs by hand ----------------------------------------- + +// gpBot is an engine whose move search the test drives. It reports progress +// the way the real engine does, as whole snapshots behind a lock of its own +// that Move never holds while it waits, so a screen reading Progress can only +// be kept waiting by something between it and the engine. A cancelled context +// is answered with a legal move, the best of the last completed iteration or +// the fallback before one, which is what bot.Bot promises. +type gpBot struct { + // hold, when set, keeps Move from starting its search until letStart, + // which is a search holding the engine before it has begun. + hold chan struct{} + holdOnce sync.Once + // release hands Move the move of a search that ran its course. + release chan game.Point + // stubborn makes Move wait for release whatever its context says: a + // search that outlives the screen which asked for it. + stubborn bool + // fallback is what a search cancelled before any completed iteration + // plays, started the start its snapshots report, and final the work it + // reports once Move has returned. + fallback game.Point + started time.Time + final bot.SearchStats + // entered is signalled each time a search begins. + entered chan struct{} + + mu sync.Mutex + progress bot.SearchProgress + ctxs []context.Context +} + +func newGPBot(t *testing.T) *gpBot { + t.Helper() + b := &gpBot{ + release: make(chan game.Point, 4), + entered: make(chan struct{}, 4), + fallback: game.Point{Col: 2, Row: 2}, + started: time.Now(), + } + // A failed test must not leave a search parked for ever. + t.Cleanup(func() { + if b.hold != nil { + b.letStart() + } + close(b.release) + }) + return b +} + +func (b *gpBot) Tier() bot.Tier { return bot.Max } + +func (b *gpBot) Hint(context.Context, *game.Game) (bot.Hint, error) { return bot.Hint{}, nil } + +func (b *gpBot) Move(ctx context.Context, g *game.Game) (game.Point, error) { + if b.hold != nil { + <-b.hold + } + b.mu.Lock() + b.ctxs = append(b.ctxs, ctx) + b.progress = bot.SearchProgress{Generation: b.progress.Generation + 1, Started: b.started, Running: true} + b.mu.Unlock() + b.entered <- struct{}{} + + var move game.Point + reason := "time" + if b.stubborn { + move = <-b.release + } else { + select { + case move = <-b.release: + case <-ctx.Done(): + reason = "canceled" + move = b.fallback + b.mu.Lock() + if b.progress.Completed { + move = b.progress.Recommended + } + b.mu.Unlock() + } + } + b.mu.Lock() + defer b.mu.Unlock() + final := b.final + final.StopReason = reason + b.progress.Running = false + b.progress.Stats = final + return move, nil +} + +func (b *gpBot) Progress() bot.SearchProgress { + b.mu.Lock() + defer b.mu.Unlock() + return b.progress +} + +// complete publishes a finished iteration, as the engine does at the end of +// each one. +func (b *gpBot) complete(depth int, nodes int64, best game.Point) { + b.mu.Lock() + defer b.mu.Unlock() + b.progress.Completed = true + b.progress.Depth = depth + b.progress.Recommended = best + b.progress.Stats = bot.SearchStats{Nodes: nodes, Evaluations: 2 * nodes, Depth: depth} +} + +func (b *gpBot) letStart() { b.holdOnce.Do(func() { close(b.hold) }) } + +func (b *gpBot) contexts() []context.Context { + b.mu.Lock() + defer b.mu.Unlock() + return append([]context.Context(nil), b.ctxs...) +} + +// gpEntered waits for the next search to begin. +func gpEntered(t *testing.T, b *gpBot) { + t.Helper() + select { + case <-b.entered: + case <-time.After(5 * time.Second): + t.Fatal("the engine was never asked for a move") + } +} + +// gpWithin runs f and fails if it has not returned in time. It is how a test +// requires that something does not wait for the search, without hanging when +// it does. +func gpWithin(t *testing.T, what string, f func()) { + t.Helper() + done := make(chan struct{}) + go func() { + defer close(done) + f() + }() + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatalf("%s waited for the engine's search", what) + } +} + +// gpTick delivers one tick fired at the given time. The tick it schedules in +// turn is dropped: the harness already has a tick running, and a second one +// would double the ticks without changing what they read. +func gpTick(t *testing.T, h *gsHarness, at time.Time) { + t.Helper() + gpWithin(t, "a spinner tick", func() { h.s.Update(botTickMsg{at: at}) }) +} + +// gpOffers reports whether the help panel offers a game action, as the +// action's own row in gameBindings describes it. +func gpOffers(h *gsHarness, a gameAction) bool { + for _, b := range gameBindings { + if b.action != a { + continue + } + for _, e := range h.s.helpEntries() { + if e.Label == b.label && e.Help == b.help { + return true + } + } + } + return false +} + +// gpAnswerFrom takes the next engine answer a screen's commands produced, +// without delivering it to that screen. The shell hands every message to the +// screen on top, so after a rematch the answer of a search the finished game +// left running goes to the rematch; routing it there is how the test +// reproduces that. +func gpAnswerFrom(t *testing.T, h *gsHarness) botMoveMsg { + t.Helper() + deadline := time.After(5 * time.Second) + for { + select { + case msg := <-h.msgs: + if m, ok := msg.(botMoveMsg); ok { + return m + } + case <-deadline: + t.Fatal("the finished game's search never answered") + return botMoveMsg{} + } + } +} + +// gpHeldSearch commits the staged turn by hand and returns the command for the +// search the commit asks for, without running it: a request the screen has +// made that has not yet reached the engine, which the test runs when it +// chooses. maybeBotMove batches the search ahead of the first spinner tick. +func gpHeldSearch(t *testing.T, h *gsHarness) tea.Cmd { + t.Helper() + _, cmd := h.s.Update(gsKeyMsg(t, "enter")) + if !h.s.botThinking || cmd == nil { + t.Fatalf("committing the turn did not ask the engine for a move: message %q", h.s.message) + } + msg := cmd() + batch, ok := msg.(tea.BatchMsg) + if !ok || len(batch) != 2 { + t.Fatalf("committing the turn asked for %T, want the search and its first tick", msg) + } + return batch[0] +} + +// gpDepthEitherForm matches a completed depth in either of the thinking line's +// forms: the panel's "depth 2 done" or the panel-less status line's "d2". +var gpDepthEitherForm = regexp.MustCompile(`\bd(?:epth )?(\d+)\b`) + +// gpClaimsDepth reports whether a frame claims depth as completed, in either +// form, anywhere on it. +func gpClaimsDepth(frame string, depth int) bool { + for _, m := range gpDepthEitherForm.FindAllStringSubmatch(frame, -1) { + if m[1] == fmt.Sprint(depth) { + return true + } + } + return false +} + +// gpDepthClaim matches any claim of a completed depth, a depth of nought +// included. +var gpDepthClaim = regexp.MustCompile(`\bdepth \d`) + +// --- the thinking line -------------------------------------------------------- + +// TestTheThinkingLineShowsOnlyThisSearchsFinishedWork reads the engine while +// its search holds the serialiser's lock. Any read that took that lock would +// hang the tick, which gpTick turns into a failure. It then requires the line +// to ignore the engine's account of an earlier search, to claim no depth +// before an iteration has finished, and to show a finished iteration's depth +// and nodes with the time measured from the engine's own start. +func TestTheThinkingLineShowsOnlyThisSearchsFinishedWork(t *testing.T) { + engine := newGPBot(t) + // The search starts a minute after the screen asks for it, as one queued + // behind another search would, so a time measured from the screen's own + // request is a minute out. + engine.started = time.Now().Add(time.Minute) + // The engine still carries the final account of an earlier search, as the + // engine a rematch inherits does. + engine.progress = bot.SearchProgress{ + Generation: 7, Started: engine.started.Add(-time.Hour), Completed: true, Depth: 9, + Stats: bot.SearchStats{Nodes: 987654, Depth: 9, StopReason: "time"}, + } + engine.hold = make(chan struct{}) + h := newGSHarness(t, gsTestDeps(t), gsVersusBot(6, engine), 120, 40) + + h.playTurn(game.Point{Col: 1, Row: 0}) + if !h.s.botThinking { + t.Fatal("the engine is not thinking, so there is no line to read") + } + gpTick(t, h, time.Now()) + if frame := h.frame(); strings.Contains(frame, "987654") || gpDepthClaim.MatchString(frame) { + t.Fatalf("the thinking line shows an earlier search's work as this one's:\n%s", frame) + } + engine.letStart() + gpEntered(t, engine) + gpTick(t, h, time.Now()) + if frame := h.frame(); gpDepthClaim.MatchString(frame) || strings.Contains(frame, "987654") { + t.Fatalf("the thinking line claims a depth before any iteration finished:\n%s", frame) + } + + engine.complete(2, 4321, game.Point{Col: 4, Row: 2}) + gpTick(t, h, engine.started.Add(2500*time.Millisecond)) + frame := h.frame() + // Whole numbers, so that a time measured from the screen's request, 62.5s, + // cannot pass for the 2.5s since the engine's start. + for _, want := range []string{`\bdepth 2\b`, `\b4321 nodes\b`, `\b2\.5s\b`} { + if !regexp.MustCompile(want).MatchString(frame) { + t.Errorf("the thinking line does not match %s once an iteration has finished:\n%s", want, frame) + } + } + if strings.Contains(frame, "987654") { + t.Errorf("the earlier search's nodes came back:\n%s", frame) + } + gsCheckFrame(t, "thinking with progress", frame, h.width, h.height) + + engine.release <- game.Point{Col: 5, Row: 1} + h.waitFor("the engine's move", func() bool { + return h.s.g.At(game.Point{Col: 5, Row: 1}) == game.Horizontal + }) + if h.s.searchProgressText() != "" || strings.Contains(h.frame(), "4321") { + t.Errorf("the finished search is still shown as running:\n%s", h.frame()) + } +} + +// TestTheThinkingLineKeepsToCompletedIterations lets the search end, and the +// engine publish its final account, before the screen has handled the move, +// with a tick reading the engine in between. The final account's nodes are the +// whole search's, the iteration it was part way through included, so shown +// beside the completed depth they would pass that unfinished work off as the +// completed iteration's. They belong to the finished figures alone. +func TestTheThinkingLineKeepsToCompletedIterations(t *testing.T) { + engine := newGPBot(t) + engine.final = bot.SearchStats{Nodes: 250, Evaluations: 400, Depth: 2, Elapsed: 3 * time.Second} + h := newGSHarness(t, gsTestDeps(t), gsVersusBot(6, engine), 120, 40) + h.playTurn(game.Point{Col: 1, Row: 0}) + gpEntered(t, engine) + + best := game.Point{Col: 4, Row: 2} + engine.complete(2, 100, best) + gpTick(t, h, engine.started.Add(time.Second)) + h.mustContain("the completed iteration's work", "100 nodes") + + engine.release <- best + answer := gpAnswerFrom(t, h) + gpTick(t, h, engine.started.Add(3*time.Second)) + frame := h.frame() + if regexp.MustCompile(`\b250\b`).MatchString(frame) { + t.Fatalf("the thinking line shows the whole search's nodes beside the completed depth:\n%s", frame) + } + for _, want := range []string{`\bdepth 2 done\b`, `\b100 nodes\b`} { + if !regexp.MustCompile(want).MatchString(frame) { + t.Errorf("the thinking line lost the completed iteration's %s once the search had ended:\n%s", want, frame) + } + } + + h.feed(answer) + if h.s.g.At(best) != game.Horizontal { + t.Fatalf("the search's move %v was not played:\n%s", best, h.s.g) + } + h.press("i") + if msg := h.s.message; !regexp.MustCompile(`\b250 nodes\b`).MatchString(msg) || !regexp.MustCompile(`\bdepth 2\b`).MatchString(msg) { + t.Errorf("the finished figures %q do not give the whole search's nodes with its completed depth", msg) + } +} + +// TestAWinTakenWithoutSearchingClaimsNoDepth hands the thinking line a running +// snapshot that has completed at depth nought, which is how the engine counts +// a winning hole it took without searching. The engine only publishes that as +// its search ends, and the line leaves final snapshots out, so the snapshot is +// delivered running here to reach the line's own rule: there is no iteration +// behind it, and no layout may present it as a completed depth. +func TestAWinTakenWithoutSearchingClaimsNoDepth(t *testing.T) { + for _, size := range shellSizes { + t.Run(fmt.Sprintf("%dx%d", size[0], size[1]), func(t *testing.T) { + engine := newGPBot(t) + h := newGSHarness(t, gsTestDeps(t), gsVersusBot(6, engine), size[0], size[1]) + h.playTurn(game.Point{Col: 1, Row: 0}) + gpEntered(t, engine) + // The commit's own line answers the key that made it, and holds + // the status line until the next key. + h.press("j") + + engine.complete(0, 0, game.Point{Col: 4, Row: 2}) + gpTick(t, h, engine.started.Add(time.Second)) + frame := h.frame() + if gpClaimsDepth(frame, 0) { + t.Errorf("the thinking line presents a win taken without searching as depth nought:\n%s", frame) + } + if !strings.Contains(frame, "1.0s") { + t.Errorf("the thinking line lost the search's time:\n%s", frame) + } + }) + } +} + +// TestPlayNowAndTheSearchShowAtEverySize keeps the key that cuts a search short, +// and how far the search has got, on screen at every supported size. Without a +// panel the status line is the only place for either, and the headline used to +// lead it and fill the minimum width by itself. +func TestPlayNowAndTheSearchShowAtEverySize(t *testing.T) { + for _, size := range shellSizes { + t.Run(fmt.Sprintf("%dx%d", size[0], size[1]), func(t *testing.T) { + engine := newGPBot(t) + h := newGSHarness(t, gsTestDeps(t), gsVersusBot(6, engine), size[0], size[1]) + h.playTurn(game.Point{Col: 1, Row: 0}) + gpEntered(t, engine) + // The commit's own line answers the key that made it, and holds + // the status line until the next key. + h.press("j") + key := h.s.gameKeyLabel(gaPlayNow) + " play now" + + gpTick(t, h, engine.started.Add(1500*time.Millisecond)) + frame := h.frame() + if !strings.Contains(frame, key) || !strings.Contains(frame, "1.5s") { + t.Errorf("before any iteration, the frame does not show %q and the search's time:\n%s", key, frame) + } + + engine.complete(2, 4321, game.Point{Col: 4, Row: 2}) + gpTick(t, h, engine.started.Add(2500*time.Millisecond)) + frame = h.frame() + if !strings.Contains(frame, key) { + t.Errorf("the frame does not offer %q while the engine thinks:\n%s", key, frame) + } + if !gpClaimsDepth(frame, 2) { + t.Errorf("the frame does not show the completed depth 2:\n%s", frame) + } + gsCheckFrame(t, "thinking", frame, h.width, h.height) + }) + } +} + +// --- play now ----------------------------------------------------------------- + +// TestPlayNowPlaysTheSearchsOwnMoveOnce presses escape during a search that has +// finished an iteration. The keyboard has to answer while the search holds the +// engine, the search's own context has to be cancelled, and the move it then +// returns has to be played exactly once, under the generation it was asked +// under. The figures shown afterwards have to be the engine's final account, +// not the last snapshot the thinking line showed. +func TestPlayNowPlaysTheSearchsOwnMoveOnce(t *testing.T) { + engine := newGPBot(t) + engine.final = bot.SearchStats{Nodes: 5000, Evaluations: 9000, Depth: 3, Elapsed: 1500 * time.Millisecond} + h := newGSHarness(t, gsTestDeps(t), gsVersusBot(6, engine), 120, 40) + + if gpOffers(h, gaPlayNow) { + t.Error("play now is offered before the engine has anything to play") + } + h.playTurn(game.Point{Col: 1, Row: 0}) + gpEntered(t, engine) + + key := gsKeyMsg(t, "j") + before := h.s.board.Cursor + gpWithin(t, "a key", func() { h.s.Update(key) }) + if h.s.board.Cursor == before { + t.Error("the cursor did not move while the search held the engine") + } + + best := game.Point{Col: 4, Row: 2} + engine.complete(3, 4321, best) + gpTick(t, h, time.Now()) + h.mustContain("the completed depth", "depth 3") + if !gpOffers(h, gaPlayNow) { + t.Fatal("the help does not offer play now while the engine thinks") + } + if footer := gsStatusLine(h); !strings.Contains(footer, h.s.gameKeyLabel(gaPlayNow)) { + t.Errorf("the footer does not name the play-now key while the engine thinks: %q", footer) + } + + gen := h.s.botGen + h.press("esc") + ctxs := engine.contexts() + if len(ctxs) != 1 { + t.Fatalf("the engine was asked for %d moves, want 1", len(ctxs)) + } + select { + case <-ctxs[0].Done(): + case <-time.After(2 * time.Second): + t.Fatal("play now did not cancel the search") + } + h.waitFor("the search's move", func() bool { return h.s.g.At(best) == game.Horizontal }) + h.pump() + + if h.s.botGen != gen { + t.Errorf("play now moved the search generation from %d to %d", gen, h.s.botGen) + } + if got := h.s.g.Entries(); got != 2 { + t.Fatalf("the game holds %d entries after one move each, want 2:\n%s", got, h.s.g) + } + if h.s.g.Turn() != game.Vertical || h.s.botThinking { + t.Errorf("after play now it is %v to move, thinking %v; want the player to move", h.s.g.Turn(), h.s.botThinking) + } + if n := len(engine.contexts()); n != 1 { + t.Errorf("the engine was asked for %d moves, want 1", n) + } + if msg := h.s.message; !strings.Contains(msg, best.String()) || !regexp.MustCompile(`\bdepth 3\b`).MatchString(msg) { + t.Errorf("the move's line %q does not name the move and the depth it was completed at", msg) + } + // Any key clears the move's line from the footer, which then shows the + // keys that work now. + h.press("j") + if gpOffers(h, gaPlayNow) || strings.Contains(gsStatusLine(h), h.s.gameKeyLabel(gaPlayNow)) { + t.Errorf("play now is still offered with no search to cut short: footer %q", gsStatusLine(h)) + } + + if !gpOffers(h, gaSearchInfo) { + t.Fatal("the finished search's figures are not offered") + } + h.press("i") + msg := h.s.message + for _, want := range []string{best.String(), "5000", "1.5s", searchStopText("canceled")} { + if !strings.Contains(msg, want) { + t.Errorf("the search's figures %q do not include %q", msg, want) + } + } + if !regexp.MustCompile(`\bdepth 3\b`).MatchString(msg) { + t.Errorf("the search's figures %q do not give the depth it completed", msg) + } + if strings.Contains(msg, "4321") { + t.Errorf("the search's figures %q are the last live snapshot rather than its final account", msg) + } +} + +// TestPlayNowBeforeAnIterationClaimsNoDepth cuts a search short before its +// first iteration completes: the engine's fallback is played, and nothing on +// screen presents a depth of nought as a completed one. +func TestPlayNowBeforeAnIterationClaimsNoDepth(t *testing.T) { + engine := newGPBot(t) + engine.final = bot.SearchStats{Nodes: 40, Evaluations: 60, Elapsed: 100 * time.Millisecond} + h := newGSHarness(t, gsTestDeps(t), gsVersusBot(6, engine), 120, 40) + + h.playTurn(game.Point{Col: 1, Row: 0}) + gpEntered(t, engine) + gpTick(t, h, time.Now()) + if frame := h.frame(); gpDepthClaim.MatchString(frame) { + t.Fatalf("the thinking line claims a depth before any iteration finished:\n%s", frame) + } + + h.press("esc") + h.waitFor("the fallback move", func() bool { return h.s.g.At(engine.fallback) == game.Horizontal }) + h.pump() + if got := h.s.g.Entries(); got != 2 { + t.Fatalf("the game holds %d entries after one move each, want 2", got) + } + if msg := h.s.message; gpDepthClaim.MatchString(msg) || !strings.Contains(msg, engine.fallback.String()) { + t.Errorf("the move's line %q claims a depth, or does not name the move", msg) + } + h.press("i") + if msg := h.s.message; gpDepthClaim.MatchString(msg) || !strings.Contains(msg, "40") { + t.Errorf("the search's figures %q claim a depth, or lose its nodes", msg) + } +} + +// TestEscapeKeepsItsOtherMeanings holds the two things escape already did: +// answer no to a question, including one asked while the engine thinks, and +// leave link mode. Where neither applies and there is no search, it still does +// nothing at all. +func TestEscapeKeepsItsOtherMeanings(t *testing.T) { + t.Run("a question asked while the engine thinks", func(t *testing.T) { + engine := newGPBot(t) + h := newGSHarness(t, gsTestDeps(t), gsVersusBot(6, engine), 120, 40) + h.playTurn(game.Point{Col: 1, Row: 0}) + gpEntered(t, engine) + + h.press("r") + if h.s.confirm != gaResign { + t.Fatalf("resign did not ask first: message %q", h.s.message) + } + h.press("esc") + if h.s.confirm != gaNone || h.s.g.Result().Over() { + t.Fatalf("escape did not answer no: confirm %v, result %v", h.s.confirm, h.s.g.Result()) + } + select { + case <-engine.contexts()[0].Done(): + t.Fatal("escape at a question also cut the search short") + default: + } + if !h.s.botThinking || !gpOffers(h, gaPlayNow) { + t.Error("the search, or the offer to cut it short, did not survive the question") + } + + engine.release <- game.Point{Col: 5, Row: 1} + h.waitFor("the engine's move", func() bool { + return h.s.g.At(game.Point{Col: 5, Row: 1}) == game.Horizontal + }) + }) + + t.Run("link mode", func(t *testing.T) { + h := newGSHarness(t, gsTestDeps(t), gsVersusBot(6, newGPBot(t)), 120, 40) + h.press("x") + if !h.s.linkMode { + t.Fatalf("link mode did not open: message %q", h.s.message) + } + h.press("esc") + if h.s.linkMode { + t.Error("escape no longer leaves link mode") + } + }) + + t.Run("nothing to answer and nothing to hurry", func(t *testing.T) { + engine := newGPBot(t) + h := newGSHarness(t, gsTestDeps(t), gsVersusBot(6, engine), 120, 40) + before := h.frame() + h.press("esc") + if len(h.done) != 0 || h.s.g.Entries() != 0 || h.s.message != "" || len(engine.contexts()) != 0 { + t.Errorf("escape on an idle board did something: departures %d, entries %d, message %q, searches %d", + len(h.done), h.s.g.Entries(), h.s.message, len(engine.contexts())) + } + if after := h.frame(); after != before { + t.Errorf("escape on an idle board changed the screen\nbefore:\n%s\nafter:\n%s", before, after) + } + }) +} + +// --- leaving and rematches ---------------------------------------------------- + +// TestALateMoveAfterLeavingIsNotPlayed leaves while a search is running and has +// it answer afterwards, as a search slow to notice its cancellation does. +func TestALateMoveAfterLeavingIsNotPlayed(t *testing.T) { + engine := newGPBot(t) + engine.stubborn = true + d := gsTestDeps(t) + h := newGSHarness(t, d, gsVersusBot(6, engine), 120, 40) + h.playTurn(game.Point{Col: 1, Row: 0}) + gpEntered(t, engine) + + h.press("q") + if len(h.done) != 1 { + t.Fatalf("leaving produced %d departures, want 1", len(h.done)) + } + late := game.Point{Col: 5, Row: 1} + engine.release <- late + h.waitFor("the late answer to be delivered", func() bool { + return h.inflight.Load() == 0 && len(h.msgs) == 0 + }) + if h.s.g.At(late) != game.NoPlayer || h.s.g.Entries() != 1 { + t.Fatalf("the move of a search the player left was played:\n%s", h.s.g) + } + sv, err := d.Games.Get(h.s.storeID) + if err != nil { + t.Fatalf("the left game was not kept: %v", err) + } + saved, err := sv.Game() + if err != nil { + t.Fatalf("the left game does not replay: %v", err) + } + if saved.Entries() != 1 { + t.Errorf("the stored game holds %d entries, want the player's one", saved.Entries()) + } +} + +// TestARematchDoesNotPlayTheLastGamesMove resigns while the engine is still +// searching, starts a rematch at once, and then has the finished game's search +// answer. The shell delivers that answer to the rematch, which must not play +// it, whether or not the rematch is itself searching by then; the rematch's +// own search is then played once. +func TestARematchDoesNotPlayTheLastGamesMove(t *testing.T) { + t.Run("the engine opens the rematch", func(t *testing.T) { + engine := newGPBot(t) + engine.stubborn = true + d := gsTestDeps(t) + h := newGSHarness(t, d, gsVersusBot(6, engine), 120, 40) + h.playTurn(game.Point{Col: 1, Row: 0}) + gpEntered(t, engine) + h.press("r") + h.press("y") + h.waitFor("the resignation", func() bool { return h.s.g.Result().Over() }) + + rh := gsAdopt(t, gsRematchScreen(h), 120, 40) + if !rh.s.botThinking { + t.Fatal("the engine did not open the rematch") + } + stale := game.Point{Col: 2, Row: 2} + engine.release <- stale + rh.feed(gpAnswerFrom(t, h)) + if got := rh.s.g.Entries(); got != 0 { + t.Fatalf("the rematch played the finished game's move %v:\n%s", stale, rh.s.g) + } + + gpEntered(t, engine) + fresh := game.Point{Col: 3, Row: 3} + engine.release <- fresh + rh.waitFor("the rematch's own move", func() bool { return rh.s.g.At(fresh) == game.Vertical }) + rh.pump() + if got := rh.s.g.Entries(); got != 1 || rh.s.g.At(stale) != game.NoPlayer { + t.Fatalf("the rematch holds %d entries after the engine's one move:\n%s", got, rh.s.g) + } + if rh.s.g.Turn() != game.Horizontal { + t.Errorf("after the engine's opening it is %v to move, want the player", rh.s.g.Turn()) + } + }) + + t.Run("the player opens the rematch", func(t *testing.T) { + engine := newGPBot(t) + engine.stubborn = true + d := gsTestDeps(t) + cfg := GameConfig{ + Kind: gamestore.VersusBot, + Rules: gsRules(6), + Seats: map[game.Player]Seat{ + game.Vertical: {Bot: engine}, + game.Horizontal: {Profile: "ada"}, + }, + } + h := newGSHarness(t, d, cfg, 120, 40) + gpEntered(t, engine) + opening := game.Point{Col: 2, Row: 2} + engine.release <- opening + h.waitFor("the engine's opening", func() bool { return h.s.g.At(opening) == game.Vertical }) + h.playTurn(game.Point{Col: 5, Row: 1}) + gpEntered(t, engine) + h.press("r") + h.press("y") + h.waitFor("the resignation", func() bool { return h.s.g.Result().Over() }) + + rh := gsAdopt(t, gsRematchScreen(h), 120, 40) + if rh.s.botThinking || rh.s.g.Turn() != game.Vertical || !rh.s.mover().Human() { + t.Fatal("the rematch does not open with the player to move") + } + stale := game.Point{Col: 3, Row: 3} + engine.release <- stale + rh.feed(gpAnswerFrom(t, h)) + if got := rh.s.g.Entries(); got != 0 || rh.s.g.At(stale) != game.NoPlayer { + t.Fatalf("the rematch played the finished game's move %v for the player:\n%s", stale, rh.s.g) + } + + rh.playTurn(game.Point{Col: 1, Row: 0}) + gpEntered(t, engine) + fresh := game.Point{Col: 5, Row: 1} + engine.release <- fresh + rh.waitFor("the engine's reply", func() bool { return rh.s.g.At(fresh) == game.Horizontal }) + rh.pump() + if got := rh.s.g.Entries(); got != 2 { + t.Fatalf("the rematch holds %d entries after one move each, want 2:\n%s", got, rh.s.g) + } + }) +} + +// TestARematchShowsOnlyItsOwnSearch has two games' requests reach the one +// engine out of order. The finished game asked for a search that had not yet +// reached the engine when the player resigned; the rematch's search takes the +// engine first, and the finished game's takes it next, before the rematch has +// handled its own move. While that other search runs, and once it has ended, +// its snapshots are the engine's latest. The rematch has to go on showing its +// own search's completed work, and give its own search's final figures for +// the move it plays. +func TestARematchShowsOnlyItsOwnSearch(t *testing.T) { + engine := newGPBot(t) + engine.stubborn = true + h := newGSHarness(t, gsTestDeps(t), gsVersusBot(6, engine), 120, 40) + h.goTo(game.Point{Col: 1, Row: 0}) + h.press("space") + queued := gpHeldSearch(t, h) + h.press("r") + h.press("y") + h.waitFor("the resignation", func() bool { return h.s.g.Result().Over() }) + + rh := gsAdopt(t, gsRematchScreen(h), 120, 40) + if !rh.s.botThinking { + t.Fatal("the engine did not open the rematch") + } + gpEntered(t, engine) + own := game.Point{Col: 3, Row: 3} + engine.complete(3, 3000, own) + gpTick(t, rh, engine.started.Add(2*time.Second)) + rh.mustContain("the rematch's completed iteration", "3000 nodes") + engine.final = bot.SearchStats{Nodes: 3500, Evaluations: 7000, Depth: 3, Elapsed: 2 * time.Second} + engine.release <- own + answer := gpAnswerFrom(t, rh) + + late := make(chan tea.Msg, 1) + go func() { late <- queued() }() + gpEntered(t, engine) + other := game.Point{Col: 4, Row: 4} + engine.complete(5, 99999, other) + gpTick(t, rh, engine.started.Add(3*time.Second)) + frame := rh.frame() + if strings.Contains(frame, "99999") || regexp.MustCompile(`\bdepth 5\b`).MatchString(frame) { + t.Fatalf("the rematch shows the finished game's search as its own:\n%s", frame) + } + if !strings.Contains(frame, "3000 nodes") { + t.Errorf("the rematch lost its own search's completed work:\n%s", frame) + } + engine.final = bot.SearchStats{Nodes: 88888, Evaluations: 90000, Depth: 5, Elapsed: 4 * time.Second} + engine.release <- other + var stale tea.Msg + select { + case stale = <-late: + case <-time.After(5 * time.Second): + t.Fatal("the finished game's search never answered") + } + + rh.feed(answer) + if rh.s.g.At(own) != game.Vertical { + t.Fatalf("the rematch did not play its own search's move %v:\n%s", own, rh.s.g) + } + rh.feed(stale) + if got := rh.s.g.Entries(); got != 1 || rh.s.g.At(other) != game.NoPlayer { + t.Fatalf("the rematch holds %d entries after the engine's one move:\n%s", got, rh.s.g) + } + rh.press("i") + msg := rh.s.message + if strings.Contains(msg, "88888") || !strings.Contains(msg, "3500") || !strings.Contains(msg, own.String()) { + t.Errorf("the rematch's search figures %q are not its own search's final account", msg) + } +} + +// --- the finished search's figures ------------------------------------------- + +// TestSearchFiguresAreOfferedOnlyOnceASearchHasFinished keeps the key off the +// help until the engine has played a move of this game, and off it again while +// the next search runs, when the last one's figures would read as this one's. +func TestSearchFiguresAreOfferedOnlyOnceASearchHasFinished(t *testing.T) { + engine := newGPBot(t) + engine.final = bot.SearchStats{Nodes: 777, Evaluations: 900, Depth: 2, Elapsed: 1500 * time.Millisecond} + h := newGSHarness(t, gsTestDeps(t), gsVersusBot(6, engine), 120, 40) + + if gpOffers(h, gaSearchInfo) { + t.Error("search figures are offered before the engine has searched") + } + h.press("i") + if h.s.g.Entries() != 0 || strings.Contains(h.s.message, "777") { + t.Errorf("the search key did something before any search: message %q", h.s.message) + } + + h.playTurn(game.Point{Col: 1, Row: 0}) + gpEntered(t, engine) + engine.complete(2, 500, game.Point{Col: 5, Row: 1}) + gpTick(t, h, time.Now()) + if gpOffers(h, gaSearchInfo) { + t.Error("search figures are offered while a search is running") + } + h.press("i") + if msg := h.s.message; strings.Contains(msg, "777") || strings.Contains(msg, "500") { + t.Errorf("the search key showed figures while the search was running: %q", msg) + } + + move := game.Point{Col: 5, Row: 1} + engine.release <- move + h.waitFor("the engine's move", func() bool { return h.s.g.At(move) == game.Horizontal }) + if !gpOffers(h, gaSearchInfo) { + t.Fatal("the finished search's figures are not offered") + } + h.press("i") + msg := h.s.message + for _, want := range []string{move.String(), "777", "1.5s", searchStopText("time")} { + if !strings.Contains(msg, want) { + t.Errorf("the search's figures %q do not include %q", msg, want) + } + } + if !regexp.MustCompile(`\bdepth 2\b`).MatchString(msg) { + t.Errorf("the search's figures %q do not give the depth it completed", msg) + } +} + +// TestTheSearchFiguresShowAtEverySize asks for a finished search's figures at +// every supported size and reads them where the player does, on the status row +// of the composed frame. They used to be one sentence cut to the width, whose +// opening words alone filled the minimum width, so neither the move nor any +// figure showed there, and at forty columns the nodes and the time were cut off. +// The move and its completed depth have to show at every size, the nodes and +// the time from forty columns up, nothing may be cut part way through, and +// nodes shown at all are still said to be the whole search's. +func TestTheSearchFiguresShowAtEverySize(t *testing.T) { + for _, size := range shellSizes { + t.Run(fmt.Sprintf("%dx%d", size[0], size[1]), func(t *testing.T) { + engine := newGPBot(t) + engine.final = bot.SearchStats{Nodes: 210304, Evaluations: 400000, Depth: 5, Elapsed: 4600 * time.Millisecond} + h := newGSHarness(t, gsTestDeps(t), gsVersusBot(6, engine), size[0], size[1]) + h.playTurn(game.Point{Col: 1, Row: 0}) + gpEntered(t, engine) + + // Play now, the way the cut sentence was found: its figures carry + // a stop reason as well as the rest. + best := game.Point{Col: 4, Row: 2} + engine.complete(5, 4321, best) + h.press("esc") + h.waitFor("the search's move", func() bool { return h.s.g.At(best) == game.Horizontal }) + h.pump() + + h.press("i") + frame := h.frame() + gsCheckFrame(t, "the search's figures", frame, h.width, h.height) + rows := strings.Split(frame, "\n") + status := ansi.Strip(rows[len(rows)-1]) + if !strings.Contains(status, best.String()) || !gpClaimsDepth(status, 5) { + t.Errorf("the status row %q does not give the move %v and its completed depth 5", status, best) + } + if h.width >= 40 { + for _, want := range []string{`\b210304 nodes\b`, `\b4\.6s\b`} { + if !regexp.MustCompile(want).MatchString(status) { + t.Errorf("the status row %q does not match %s at %d columns", status, want, h.width) + } + } + } + if strings.Contains(status, ellipsis) { + t.Errorf("the status row %q was cut rather than shortened by whole items", status) + } + if strings.Contains(status, "nodes") && !strings.Contains(status, "in all") { + t.Errorf("the status row %q gives the nodes without saying they are the whole search's", status) + } + }) + } +} diff --git a/internal/app/gamescreen_test.go b/internal/app/gamescreen_test.go index 902d6da..0940604 100644 --- a/internal/app/gamescreen_test.go +++ b/internal/app/gamescreen_test.go @@ -2564,7 +2564,9 @@ func TestNewGameScreenRefusesImpossibleConfigurations(t *testing.T) { // TestGameKeysDoNotShadowTheBoardKeymap keeps the two tables disjoint where it // matters. A confirmation intercepts the keyboard before the board keymap is // consulted, so its keys may repeat a board key; a key live on a board in any -// other phase would silently take a board action away. +// other phase would silently take a board action away. A game key that +// gameKeyContexts keeps out of a context may repeat a board key there, since in +// that context the board is what answers it. func TestGameKeysDoNotShadowTheBoardKeymap(t *testing.T) { km := ui.DefaultKeymap() boardPhases := phasePlay | phaseFinished | phaseStopped @@ -2574,6 +2576,9 @@ func TestGameKeysDoNotShadowTheBoardKeymap(t *testing.T) { } for _, key := range b.keys { for _, ctx := range []ui.Context{ui.CtxBoard, ui.CtxLink} { + if gameKeyContexts(b.action)&ctx == 0 { + continue + } if existing, ok := km.Lookup(ctx, key); ok { t.Errorf("game key %q also drives board action %v", key, existing.Action) } diff --git a/internal/bot/bot.go b/internal/bot/bot.go index 7fe9e4f..4ef44ac 100644 --- a/internal/bot/bot.go +++ b/internal/bot/bot.go @@ -13,7 +13,9 @@ // // Limits and NewWithLimits replace a tier's guards with the caller's own, which // is how a measurement asks for work rather than for wall-clock time, and -// StatsOf reports what the last search actually spent. +// StatsOf reports what the last search actually spent. ProgressOf reports how +// far a search has got while it is still running, and can be read from another +// goroutine without waiting for it. // // Analyze reads one position outside a game and outside the Bot interface: one // bounded search, the candidates it kept with what it established about each, @@ -29,6 +31,7 @@ import ( "math/rand/v2" "slices" "strings" + "sync/atomic" "time" "github.com/BAKocska/twixtui/internal/game" @@ -303,6 +306,10 @@ type engine struct { p params play *searcher hint *searcher + // progress is the latest snapshot of a Move search, published by the + // search as it goes and read by Progress without a lock. It is the one + // field of the engine another goroutine may read while Move runs. + progress atomic.Pointer[SearchProgress] } // New returns a bot of the given tier. A tier that does not exist gives the @@ -479,10 +486,18 @@ func (e *engine) Move(ctx context.Context, g *game.Game) (game.Point, error) { return game.Point{}, ErrNoMove } + // Progress is published from here on, once the request is one the search + // will run, and the deferred finish reports the search as ended on every + // way out of it, errors and fallbacks included. + run := e.startProgress() + defer run.finish() res, err := e.play.root(ctx, g) if err != nil { return game.Point{}, err } + if res.immediate { + run.immediate(res.best) + } move := res.best if e.p.temperature > 0 && !res.immediate { move = sampleMove(res.moves, e.p.temperature, rand.New(rand.NewPCG(uint64(e.seed), res.an.hash))) diff --git a/internal/bot/progress.go b/internal/bot/progress.go new file mode 100644 index 0000000..e354c18 --- /dev/null +++ b/internal/bot/progress.go @@ -0,0 +1,148 @@ +package bot + +import ( + "sync/atomic" + "time" + + "github.com/BAKocska/twixtui/internal/game" +) + +// SearchProgress is an immutable snapshot of an engine's current or last Move +// search. +// +// It exists for a screen that wants to show what the engine is doing while it +// thinks. Stats cannot answer that: it describes a search that has already +// happened, and a caller that serialises its bot behind the Move lock would +// wait out the whole search to read it. A snapshot is published whole at the +// start of a search, at the end of every deepening iteration that finished, +// and when Move returns, and it is never edited after that, so reading one +// costs a load and a copy and never waits on the search. +// +// What it reports is completed work only. An iteration still running has +// scored some root moves at the new depth and the rest at the old one, so its +// best move and its counters describe nothing in particular; a snapshot keeps +// showing the last iteration that finished until the next one does. +type SearchProgress struct { + // Generation counts the Move searches this engine has started, so a + // reader can tell a new search from the one it looked at last. Zero means + // none has started yet. + Generation uint64 + // Started is when that search began. + Started time.Time + // Running is true from the moment the search starts until Move returns. + Running bool + // Completed says at least one deepening iteration finished, or a winning + // hole was taken without searching. Depth, Recommended and Stats mean + // something only when it is true: before then the only answer the search + // has is the ordering heuristic's guess, and that is not a search. + Completed bool + // Depth is the deepest completed iteration, and zero for a win taken + // without searching. + Depth int + // Recommended is the best move of the last completed iteration. It is the + // search's own choice, before the beginner tier samples among the + // alternatives, so it need not be the move Move returns on that tier. + Recommended game.Point + // Stats is the work as of the last completed iteration while Running is + // true, with an empty StopReason because the search has not stopped. Once + // Running is false it is what StatsOf reports for the same search. + Stats SearchStats +} + +// ProgressOf reports b's latest search progress without blocking and without +// starting any work, or the zero SearchProgress for a bot that does not report +// it. +// +// Like StatsOf it is optional: an implementation that reports progress offers +// Progress() SearchProgress, which is what this asks for. Unlike StatsOf it is +// meant to be read from another goroutine while Move is running, so an +// implementation has to answer without waiting for the search. +func ProgressOf(b Bot) SearchProgress { + if p, ok := b.(interface{ Progress() SearchProgress }); ok { + return p.Progress() + } + return SearchProgress{} +} + +// Progress reports the engine's latest Move search as it stood when it was +// last published, and the zero value before the first one. It takes no lock: +// the search stores a fresh snapshot at every publication and never touches +// one again, so the copy returned here is the caller's own. The hint search is +// left out of it for the same reason Stats leaves it out. +func (e *engine) Progress() SearchProgress { + if p := e.progress.Load(); p != nil { + return *p + } + return SearchProgress{} +} + +// progressRun is the writing side of one Move search's progress. It lives on +// the goroutine running the search, which is the only one that edits cur; a +// reader only ever sees a copy of cur, stored whole. +type progressRun struct { + dst *atomic.Pointer[SearchProgress] + s *searcher + cur SearchProgress +} + +// startProgress publishes the start of a Move search and hooks the play +// searcher so that every iteration it finishes is published as well. The hook +// is the one Analyze reports its iterations through, and it belongs to this +// search alone: finish takes it off again, so a search the engine did not +// start through Move reports nothing here. +func (e *engine) startProgress() *progressRun { + r := &progressRun{ + dst: &e.progress, + s: e.play, + cur: SearchProgress{ + Generation: e.Progress().Generation + 1, + Started: time.Now(), + Running: true, + }, + } + r.publish() + r.s.onDepth = r.iteration + return r +} + +// iteration publishes a finished iteration. The searcher only records its +// elapsed time when it stops, so the boundary's own figure is the one that +// means anything here, and the stop reason is left empty because the search +// has not stopped: a reader sees the work that iteration finished with and +// nothing the next one has spent since. +func (r *progressRun) iteration(res *rootResult, elapsed time.Duration) { + st := r.s.stats() + st.Elapsed, st.StopReason = elapsed, "" + r.cur.Completed = true + r.cur.Depth = res.depth + r.cur.Recommended = res.best + r.cur.Stats = st + r.publish() +} + +// immediate records a winning hole taken without searching. That is not an +// iteration, but it is a finished answer rather than a guess, so it counts as +// completed at depth zero. It is published with the rest of the ending. +func (r *progressRun) immediate(hole game.Point) { + r.cur.Completed = true + r.cur.Depth = 0 + r.cur.Recommended = hole +} + +// finish takes the hook off the play searcher and publishes the search as +// ended, with the same figures StatsOf now reports for it. Whether it counts +// as completed is whatever the iterations, or an immediate win, already said. +func (r *progressRun) finish() { + r.s.onDepth = nil + r.cur.Running = false + r.cur.Stats = r.s.stats() + r.publish() +} + +// publish stores a copy of the snapshot as it now stands. The copy is what +// makes the published value immutable: cur goes on changing, and a reader +// holding an earlier publication must not see it do so. +func (r *progressRun) publish() { + snap := r.cur + r.dst.Store(&snap) +} diff --git a/internal/bot/progress_test.go b/internal/bot/progress_test.go new file mode 100644 index 0000000..88f965e --- /dev/null +++ b/internal/bot/progress_test.go @@ -0,0 +1,523 @@ +package bot + +import ( + "context" + "runtime" + "testing" + "time" + + "github.com/BAKocska/twixtui/internal/game" +) + +// pacedContext paces a Move search against a progress poller on another +// goroutine. +// +// The search calls Err at its work boundaries, on its own goroutine, and the +// first of those calls after an iteration has been published waits until the +// poller acknowledges having seen that iteration. So the poller observes every +// iteration the search publishes while it runs, however the scheduler treats +// the two goroutines, and what a test asserts about those observations does not +// depend on timing luck. The wait is bounded: a poller that never looks slows +// the search down and marks the context stalled rather than hanging the test. +// +// Its fields belong to the goroutine running Move, which has to be the test's +// own; the poller only ever touches ack. +type pacedContext struct { + context.Context + b Bot + ack chan int + acked int + stalled bool +} + +func newPacedContext(parent context.Context, b Bot) *pacedContext { + return &pacedContext{Context: parent, b: b, ack: make(chan int)} +} + +func (c *pacedContext) Err() error { + if p := ProgressOf(c.b); p.Running && p.Completed && p.Depth > c.acked { + select { + case c.acked = <-c.ack: + case <-time.After(10 * time.Second): + c.acked, c.stalled = p.Depth, true + } + } + return c.Context.Err() +} + +// progressPoller reads ProgressOf on a goroutine of its own, the way a screen +// polls a bot that is thinking on another, and keeps every snapshot that +// differs from the one before it. A running snapshot with a completed iteration +// it has not acknowledged yet is handed to onCompleted, if set, and then +// acknowledged to the pacedContext the search runs under. +type progressPoller struct { + done chan struct{} + out chan []SearchProgress +} + +func startProgressPoller(b Bot, ack chan<- int, onCompleted func(SearchProgress)) *progressPoller { + pp := &progressPoller{done: make(chan struct{}), out: make(chan []SearchProgress, 1)} + go func() { + var seen []SearchProgress + keep := func(p SearchProgress) { + if len(seen) == 0 || p != seen[len(seen)-1] { + seen = append(seen, p) + } + } + acked := 0 + for { + select { + case <-pp.done: + // One more read after Move has returned, so that the + // snapshot it left behind is the last one in the list. + keep(ProgressOf(b)) + pp.out <- seen + return + default: + } + p := ProgressOf(b) + keep(p) + if p.Running && p.Completed && p.Depth > acked { + if onCompleted != nil { + onCompleted(p) + } + select { + case ack <- p.Depth: + acked = p.Depth + case <-pp.done: + } + } + runtime.Gosched() + } + }() + return pp +} + +// stop ends the poll and returns what it saw, in the order it saw it. +func (pp *progressPoller) stop() []SearchProgress { + close(pp.done) + return <-pp.out +} + +// TestProgressIsZeroUntilASearchStarts holds the zero value to meaning that no +// search has started: a bot with no search has nothing to report, an engine +// that has not searched has nothing yet, and a request the engine refuses +// before searching is not a search. +func TestProgressIsZeroUntilASearchStarts(t *testing.T) { + if got := ProgressOf(scriptedBot{}); got != (SearchProgress{}) { + t.Errorf("a bot with no search reports %+v, want the zero value", got) + } + b := New(Max, 1) + if got := ProgressOf(b); got != (SearchProgress{}) { + t.Errorf("an engine that has not searched reports %+v, want the zero value", got) + } + over := game.MustNew(smallRules(8)) + if err := over.Resign(game.Vertical); err != nil { + t.Fatalf("Resign: %v", err) + } + if _, err := b.Move(context.Background(), over); err == nil { + t.Fatal("Move accepted a finished game") + } + if got := ProgressOf(b); got != (SearchProgress{}) { + t.Errorf("a request refused before searching published %+v, want the zero value", got) + } +} + +// TestProgressAfterACompletedMove checks the snapshot a finished search leaves +// behind: not running, the first search, completed to its depth ceiling, with +// the counters StatsOf reports and the move the search chose. +func TestProgressAfterACompletedMove(t *testing.T) { + const depth = 2 + b, err := NewWithLimits(Max, 1, Limits{Depth: depth, Time: time.Hour}) + if err != nil { + t.Fatalf("NewWithLimits: %v", err) + } + g := quietPosition(t) + before := time.Now() + move, err := b.Move(context.Background(), g) + after := time.Now() + if err != nil { + t.Fatalf("Move: %v", err) + } + p := ProgressOf(b) + if p.Running { + t.Errorf("Move has returned and the snapshot still says it is running: %+v", p) + } + if p.Generation != 1 { + t.Errorf("the first search is generation %d, want 1", p.Generation) + } + if !p.Completed || p.Depth != depth { + t.Fatalf("the snapshot reports completed=%v at depth %d, want the %d-ply ceiling reached: %+v", p.Completed, p.Depth, depth, p) + } + if st := StatsOf(b); p.Stats != st { + t.Errorf("the snapshot reports %+v and StatsOf %+v for the same search", p.Stats, st) + } + if p.Stats.StopReason != stopDepth || p.Stats.Depth != p.Depth { + t.Errorf("the snapshot's counters say %+v, want the search ended on its ceiling at depth %d", p.Stats, p.Depth) + } + // The max tier plays the move its search found, so the recommendation and + // the move are the same hole. + if p.Recommended != move { + t.Errorf("the snapshot recommends %v and Move played %v", p.Recommended, move) + } + if p.Started.Before(before) || p.Started.After(after) { + t.Errorf("the search is dated %v, outside the call that ran it (%v to %v)", p.Started, before, after) + } +} + +// TestProgressOfAnImmediateWin covers the one answer that is finished without +// an iteration: a winning hole taken at the root counts as completed at depth +// zero and recommends the hole. +func TestProgressOfAnImmediateWin(t *testing.T) { + b, err := NewWithLimits(Max, 1, Limits{Depth: 2, Time: time.Hour}) + if err != nil { + t.Fatalf("NewWithLimits: %v", err) + } + g := winThreat(t) + move, err := b.Move(context.Background(), g) + if err != nil { + t.Fatalf("Move: %v", err) + } + probe := g.Clone() + res, err := probe.PlayPeg(move) + if err != nil || res.Winner() != g.Turn() { + t.Fatalf("control: Move played %v, which does not win at once (%v)\n%s", move, err, g) + } + p := ProgressOf(b) + if p.Running || p.Generation != 1 { + t.Errorf("the snapshot reports running=%v in generation %d, want a finished first search", p.Running, p.Generation) + } + if !p.Completed || p.Depth != 0 || p.Stats.StopReason != stopImmediate { + t.Errorf("the snapshot reports completed=%v at depth %d stopped for %q, want an immediate win completed at depth 0", + p.Completed, p.Depth, p.Stats.StopReason) + } + if p.Recommended != move { + t.Errorf("the snapshot recommends %v, want the winning hole %v", p.Recommended, move) + } + if st := StatsOf(b); p.Stats != st { + t.Errorf("the snapshot reports %+v and StatsOf %+v for the same search", p.Stats, st) + } +} + +// TestProgressGenerationCountsMoveSearchesOnly holds the generation to Move +// searches. A hint and an analysis on the engine's own hint searcher are +// searches too, and the hint here is given a deeper ceiling than the move, so +// one that published would show as a depth the move never reached as well as +// in the generation. +func TestProgressGenerationCountsMoveSearchesOnly(t *testing.T) { + ctx := context.Background() + b, err := NewWithLimits(Max, 1, Limits{Depth: 1, Time: time.Hour}) + if err != nil { + t.Fatalf("NewWithLimits: %v", err) + } + e := b.(*engine) + hs := e.hintSearcher() + hs.p.maxDepth, hs.p.budget = 2, time.Hour + g := quietPosition(t) + + if _, err := b.Move(ctx, g); err != nil { + t.Fatalf("Move: %v", err) + } + first := ProgressOf(b) + if first.Generation != 1 || first.Running || !first.Completed || first.Depth != 1 { + t.Fatalf("the first search reports %+v, want generation 1 finished at depth 1", first) + } + + if _, err := b.Hint(ctx, g); err != nil { + t.Fatalf("Hint: %v", err) + } + if got := ProgressOf(b); got != first { + t.Errorf("a hint changed the move's progress from %+v to %+v", first, got) + } + reports := 0 + if _, _, _, err := analyzeOn(ctx, hs, g, func(AnalysisProgress) { reports++ }); err != nil { + t.Fatalf("analyze: %v", err) + } + if reports == 0 { + t.Fatal("control: the analysis reported no finished iteration, so it could not have published one") + } + if got := ProgressOf(b); got != first { + t.Errorf("an analysis on the engine changed the move's progress from %+v to %+v", first, got) + } + + if _, err := b.Move(ctx, g); err != nil { + t.Fatalf("second Move: %v", err) + } + second := ProgressOf(b) + if second.Generation != 2 { + t.Errorf("the second search is generation %d, want 2", second.Generation) + } + if second.Running || !second.Completed || second.Depth != 1 { + t.Errorf("the second search reports %+v, want it finished at depth 1", second) + } + if second.Started.Before(first.Started) { + t.Errorf("the second search is dated %v, before the first at %v", second.Started, first.Started) + } + if st := StatsOf(b); second.Stats != st { + t.Errorf("the snapshot reports %+v and StatsOf %+v for the same search", second.Stats, st) + } +} + +// TestProgressOfASearchCanceledBeforeItsFirstIteration: a search stopped +// before any iteration finished answers from the ordering heuristic, and that +// guess must not be presented as a completed iteration — nor may the previous +// search's completion be carried into this one. +func TestProgressOfASearchCanceledBeforeItsFirstIteration(t *testing.T) { + b, err := NewWithLimits(Max, 1, Limits{Depth: 1, Time: time.Hour}) + if err != nil { + t.Fatalf("NewWithLimits: %v", err) + } + g := quietPosition(t) + if _, err := b.Move(context.Background(), g); err != nil { + t.Fatalf("Move: %v", err) + } + if p := ProgressOf(b); !p.Completed || p.Depth != 1 { + t.Fatalf("control: the first search reports %+v, want it finished at depth 1", p) + } + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + move, err := b.Move(ctx, g) + if err != nil { + t.Fatalf("Move on a cancelled context: %v", err) + } + if err := g.CanPlace(g.Turn(), move); err != nil { + t.Fatalf("Move on a cancelled context returned illegal %v: %v", move, err) + } + p := ProgressOf(b) + if p.Generation != 2 || p.Running { + t.Errorf("the cancelled search reports generation %d running=%v, want generation 2 finished", p.Generation, p.Running) + } + if p.Completed || p.Depth != 0 { + t.Errorf("a search cancelled before its first iteration reports completed=%v at depth %d: %+v", p.Completed, p.Depth, p) + } + if p.Stats.StopReason != stopCanceled || p.Stats.Depth != 0 { + t.Errorf("the cancelled search's counters say %+v, want it cancelled at depth 0", p.Stats) + } + if st := StatsOf(b); p.Stats != st { + t.Errorf("the snapshot reports %+v and StatsOf %+v for the same search", p.Stats, st) + } +} + +// TestProgressOfASearchCanceledAfterAnIteration cancels from the poller's side +// once it sees a completed iteration, the way a "play now" key would, and holds +// the ending to that work: the search stops on what it had finished, the last +// snapshot published while it ran is what the final one reports, and the move +// is that iteration's. +func TestProgressOfASearchCanceledAfterAnIteration(t *testing.T) { + // The clock is out of the way and the depth ceiling far off, so only the + // cancellation ends the search. The guard only bounds the test if the + // poller never gets to cancel. + b, err := NewWithLimits(Max, 1, Limits{Time: time.Hour}) + if err != nil { + t.Fatalf("NewWithLimits: %v", err) + } + g := quietPosition(t) + guard, stopGuard := context.WithTimeout(context.Background(), 30*time.Second) + defer stopGuard() + parent, cancel := context.WithCancel(guard) + defer cancel() + ctx := newPacedContext(parent, b) + + var canceledAt SearchProgress + poller := startProgressPoller(b, ctx.ack, func(p SearchProgress) { + if canceledAt.Generation == 0 { + canceledAt = p + cancel() + } + }) + move, err := b.Move(ctx, g) + seen := poller.stop() + if err != nil { + t.Fatalf("Move: %v", err) + } + if err := g.CanPlace(g.Turn(), move); err != nil { + t.Fatalf("Move returned illegal %v after a cancellation: %v", move, err) + } + if ctx.stalled { + t.Fatal("the poller stopped acknowledging iterations, so it did not see all of them") + } + if !canceledAt.Completed || canceledAt.Depth < 1 { + t.Fatalf("the poller never saw a completed iteration to cancel after: %+v", seen) + } + + final := ProgressOf(b) + if final.Stats.StopReason != stopCanceled { + t.Fatalf("the search stopped for %q, want the cancellation: %+v", final.Stats.StopReason, final) + } + if len(seen) == 0 || seen[len(seen)-1] != final { + t.Fatalf("the poller's last snapshot is not the one Move left behind: %+v", seen) + } + var last SearchProgress + for _, p := range seen { + if p.Running && p.Completed { + last = p + } + } + if final.Running || !final.Completed { + t.Errorf("the ended search reports running=%v completed=%v, want finished with an iteration behind it", final.Running, final.Completed) + } + if final.Depth != last.Depth || final.Recommended != last.Recommended { + t.Errorf("the search ended at depth %d recommending %v, but the last iteration published while it ran was depth %d recommending %v", + final.Depth, final.Recommended, last.Depth, last.Recommended) + } + if final.Depth < canceledAt.Depth { + t.Errorf("the search ended at depth %d, shallower than the depth %d it was cancelled after", final.Depth, canceledAt.Depth) + } + if final.Stats.Depth != final.Depth { + t.Errorf("the snapshot's depth is %d and its counters' %d", final.Depth, final.Stats.Depth) + } + if final.Stats.Nodes < last.Stats.Nodes { + t.Errorf("the search ended with %d nodes, fewer than the %d its last iteration had", final.Stats.Nodes, last.Stats.Nodes) + } + if st := StatsOf(b); final.Stats != st { + t.Errorf("the snapshot reports %+v and StatsOf %+v for the same search", final.Stats, st) + } + if move != final.Recommended { + t.Errorf("Move played %v, not %v from the last completed iteration", move, final.Recommended) + } +} + +// TestProgressPolledWhileMoveRuns reads the progress from another goroutine for +// the whole of a search and holds what it sees to completed work: nothing goes +// backwards, a snapshot with no finished iteration carries no work, and each +// iteration's snapshot carries exactly that iteration's counters and move. +// +// The last is checked against the same search stopped at each shallower depth. +// Its first iterations do the same work whatever its ceiling, so counters read +// at any other moment than the end of the iteration would differ from theirs. +func TestProgressPolledWhileMoveRuns(t *testing.T) { + const depth = 3 + ctx0 := context.Background() + g := quietPosition(t) + + type reference struct { + move game.Point + stats SearchStats + } + refs := map[int]reference{} + for d := 1; d < depth; d++ { + rb, err := NewWithLimits(Max, 1, Limits{Depth: d, Time: time.Hour}) + if err != nil { + t.Fatalf("NewWithLimits: %v", err) + } + m, err := rb.Move(ctx0, g) + if err != nil { + t.Fatalf("reference Move at depth %d: %v", d, err) + } + st := StatsOf(rb) + if st.StopReason != stopDepth || st.Depth != d { + t.Fatalf("control: the reference at depth %d stopped with %+v", d, st) + } + refs[d] = reference{move: m, stats: st} + } + + b, err := NewWithLimits(Max, 1, Limits{Depth: depth, Time: time.Hour}) + if err != nil { + t.Fatalf("NewWithLimits: %v", err) + } + guard, stopGuard := context.WithTimeout(ctx0, time.Minute) + defer stopGuard() + ctx := newPacedContext(guard, b) + poller := startProgressPoller(b, ctx.ack, nil) + move, err := b.Move(ctx, g) + seen := poller.stop() + if err != nil { + t.Fatalf("Move: %v", err) + } + if ctx.stalled { + t.Fatal("the poller stopped acknowledging iterations, so it did not see all of them") + } + final := ProgressOf(b) + if final.Stats.StopReason != stopDepth || final.Depth != depth { + t.Fatalf("the search stopped with %+v, want it to reach its %d-ply ceiling", final.Stats, depth) + } + if len(seen) == 0 || seen[len(seen)-1] != final { + t.Fatalf("the poller's last snapshot is not the one Move left behind: %+v", seen) + } + + var prev SearchProgress + var iterations []SearchProgress + for i, p := range seen { + if p.Generation < prev.Generation || p.Generation > 1 { + t.Errorf("snapshot %d is generation %d after %d, for a single search", i, p.Generation, prev.Generation) + } + if p.Generation == 0 && p != (SearchProgress{}) { + t.Errorf("snapshot %d names no search but carries %+v", i, p) + } + if p.Generation == 1 && prev.Generation == 1 { + if p.Depth < prev.Depth { + t.Errorf("snapshot %d went back from depth %d to %d", i, prev.Depth, p.Depth) + } + if prev.Completed && !p.Completed { + t.Errorf("snapshot %d lost the completed iteration snapshot %d had", i, i-1) + } + if !prev.Running && p.Running { + t.Errorf("snapshot %d is running after snapshot %d had ended", i, i-1) + } + if p.Running && p.Stats.Nodes < prev.Stats.Nodes { + t.Errorf("snapshot %d reports %d nodes after %d", i, p.Stats.Nodes, prev.Stats.Nodes) + } + } + if p.Running { + if p.Stats.StopReason != "" { + t.Errorf("running snapshot %d says the search stopped for %q", i, p.Stats.StopReason) + } + if !p.Completed && (p.Depth != 0 || p.Stats != (SearchStats{})) { + t.Errorf("running snapshot %d has no finished iteration but reports depth %d and %+v", i, p.Depth, p.Stats) + } + if p.Completed { + iterations = append(iterations, p) + } + } + prev = p + } + + // The pacing lets the poller see every iteration the search published. + if len(iterations) != depth { + t.Fatalf("the poller saw %d running iterations, want one for each of the %d depths: %+v", len(iterations), depth, iterations) + } + for i, p := range iterations { + d := i + 1 + if p.Depth != d || p.Stats.Depth != d { + t.Errorf("iteration %d is reported at depth %d with counters at depth %d", d, p.Depth, p.Stats.Depth) + } + want, wantMove := final.Stats, move + if r, ok := refs[d]; ok { + want, wantMove = r.stats, r.move + } + if p.Stats.Nodes != want.Nodes || p.Stats.Evaluations != want.Evaluations { + t.Errorf("the depth-%d snapshot reports %d nodes and %d analyses, the search to that depth spent %d and %d", + d, p.Stats.Nodes, p.Stats.Evaluations, want.Nodes, want.Evaluations) + } + if p.Recommended != wantMove { + t.Errorf("the depth-%d snapshot recommends %v, the search to that depth chose %v", d, p.Recommended, wantMove) + } + if p.Stats.Elapsed > final.Stats.Elapsed { + t.Errorf("the depth-%d snapshot is dated %v, past the %v the whole search took", d, p.Stats.Elapsed, final.Stats.Elapsed) + } + } +} + +// TestProgressSnapshotsBelongToTheCaller: a snapshot is the caller's to edit, +// and editing it cannot reach what the engine reports next. +func TestProgressSnapshotsBelongToTheCaller(t *testing.T) { + b, err := NewWithLimits(Max, 1, Limits{Depth: 1, Time: time.Hour}) + if err != nil { + t.Fatalf("NewWithLimits: %v", err) + } + if _, err := b.Move(context.Background(), quietPosition(t)); err != nil { + t.Fatalf("Move: %v", err) + } + got := ProgressOf(b) + want := got + got.Generation, got.Started, got.Running, got.Completed, got.Depth = 99, time.Time{}, true, false, 99 + got.Recommended = game.Point{Col: -1, Row: -1} + got.Stats.Nodes, got.Stats.Depth, got.Stats.StopReason = -1, 99, "edited" + if got == want { + t.Fatal("control: the edits left the copy as it was") + } + if again := ProgressOf(b); again != want { + t.Errorf("editing a snapshot changed the next one from %+v to %+v", want, again) + } +} diff --git a/internal/bot/search.go b/internal/bot/search.go index 77509d3..72953d9 100644 --- a/internal/bot/search.go +++ b/internal/bot/search.go @@ -247,6 +247,12 @@ type searcher struct { // without searching do not reach it: what it reports is completed work. // The result it is handed is the root's own, so a hook that needs to keep // anything copies it. + // + // It runs on the search's own goroutine before the next iteration starts, + // so the counters it reads are the finished iteration's and nothing more. + // Analyze reports its iterations through it and Move publishes its + // progress through it; either way it is set for one request and taken off + // when that request ends. onDepth func(res *rootResult, elapsed time.Duration) // One analysis and one move buffer per ply: a node needs its own view of diff --git a/internal/e2e/progress_test.go b/internal/e2e/progress_test.go new file mode 100644 index 0000000..bb18b0b --- /dev/null +++ b/internal/e2e/progress_test.go @@ -0,0 +1,154 @@ +package e2e + +import ( + "regexp" + "strconv" + "strings" + "testing" + "time" + + "github.com/BAKocska/twixtui/internal/game" + "github.com/BAKocska/twixtui/internal/gamestore" +) + +// maxBudget is the time the max tier may spend on a move. A move that arrives +// well inside it after play now was pressed was cut short rather than left to +// run out its clock. +const maxBudget = 10 * time.Second + +var ( + progressDepth = regexp.MustCompile(`depth (\d+) done`) + // playedEarly is the announcement of a move play now cut short, in both + // its forms: from a completed iteration, or before one had finished. + playedEarly = regexp.MustCompile(`played ([A-Z]{1,2}\d{1,2}) early, (?:from its completed depth (\d+)|before any depth was complete)`) +) + +// TestPlayNowCutsAMaxSearchShort plays against the max engine on a full-size +// board, where its opening reply searches for seconds, and presses escape +// while it is still thinking. The compiled program has to play exactly one +// legal reply long before the engine's budget would have run out, hand the +// move back to the player, and then report that search's figures on request. +// A completed iteration shown on the thinking line has to be one the move was +// played from. The stored record is the judge of the move: it replays under +// the rules and counts its entries. +// +// How far the search gets before escape is the machine's business. A slow or +// busy runner may not finish depth one in the time the test watches for it, +// and play now before any iteration is valid behaviour with an announcement of +// its own, so either outcome passes; what each one has to be consistent with +// is what the screen showed. +func TestPlayNowCutsAMaxSearchShort(t *testing.T) { + t.Parallel() + cfg := t.TempDir() + tm := sessionIn(t, cfg, 120, 40, "play", "bot", "--tier", "max", "--side", "vertical", "--seed", "1") + + // Positive control: the game is up and waiting for the player. + frame := tm.MustWaitFor("vertical to move", 20*time.Second) + if !tm.Alive() { + t.Fatalf("the program exited instead of starting the game:\n%s", frame) + } + frame = tm.WaitSettled(10 * time.Second) + + // The cursor starts on the centre hole: place there and commit. + tm.SendKeys("Space") + tm.WaitChanged(frame, 10*time.Second) + tm.SendKeys("Enter") + tm.MustWaitFor("is thinking", 20*time.Second) + + // The thinking line is watched for a completed iteration for a share of + // the budget, and escape is pressed once one shows or the share is up. + // Either way the search still has most of its budget left, so a move that + // follows soon after can only be play now's. + shown := 0 + watch := time.Now().Add(maxBudget * 2 / 5) + for { + screen := tm.Capture() + if !strings.Contains(screen, "is thinking") || playedEarly.MatchString(screen) { + t.Fatalf("the engine was no longer thinking when play now was about to be pressed:\n%s", screen) + } + if found := progressDepth.FindStringSubmatch(screen); found != nil { + depth, err := strconv.Atoi(found[1]) + if err != nil || depth < 1 { + t.Fatalf("the thinking line claims an impossible completed depth %q:\n%s", found[1], screen) + } + shown = depth + break + } + if time.Now().After(watch) { + break + } + time.Sleep(pollInterval) + } + + pressed := time.Now() + tm.SendKeys("Escape") + var found []string + for { + screen := tm.Capture() + if found = playedEarly.FindStringSubmatch(screen); found != nil { + break + } + if time.Since(pressed) > maxBudget/2 { + t.Fatalf("the engine had not played %s after play now was pressed:\n%s", maxBudget/2, screen) + } + time.Sleep(pollInterval) + } + move := found[1] + // A depth the thinking line showed as done was finished work, so the move + // has to come from it or a deeper one. With none shown, either form is + // right: an iteration can finish in the moment between the last look at + // the screen and the key reaching the program. The form played before any + // iteration has no depth, which reads as nought here. + from, _ := strconv.Atoi(found[2]) + switch { + case shown > 0 && from < shown: + t.Fatalf("the thinking line showed depth %d done, but the move was announced as %q", shown, found[0]) + case shown == 0: + t.Logf("no completed depth showed within %s; the move was announced as %q", maxBudget*2/5, found[0]) + } + after := tm.MustWaitFor("vertical to move", 10*time.Second) + if strings.Contains(after, "is thinking") { + t.Fatalf("the engine is still thinking after its move was played:\n%s", after) + } + tm.AssertFits() + + // The figures of that search. Escape and the next key sent quickly can + // arrive as one alt-modified key, which is why the move was waited for + // first. + tm.SendKeys("i") + stats := tm.MustWaitFor("nodes", 10*time.Second) + var line string + for _, l := range strings.Split(stats, "\n") { + if strings.Contains(l, "nodes") { + line = l + } + } + if !strings.Contains(line, move) || !strings.Contains(line, "play now") { + t.Errorf("the search's figures %q do not name the move %s and the play now that ended the search", line, move) + } + + tm.SendKeys("q") + if code, exited := tm.WaitExit(20 * time.Second); !exited || code != 0 { + t.Fatalf("the program did not leave cleanly: exited=%v status=%d\n%s", exited, code, tm.Capture()) + } + + store, err := gamestore.Open(cfg) + if err != nil { + t.Fatal(err) + } + saved := store.List() + if len(saved) != 1 { + t.Fatalf("%d games stored, want 1", len(saved)) + } + g, err := saved[0].Game() + if err != nil { + t.Fatalf("the stored game does not replay: %v", err) + } + if g.Entries() != 2 || g.Turn() != game.Vertical { + t.Fatalf("the stored game holds %d entries with %v to move, want the player's move and one reply:\n%s", + g.Entries(), g.Turn(), g) + } + if reply := g.History()[1]; reply.Player != game.Horizontal || reply.Peg.String() != move { + t.Errorf("the stored reply is %v at %s, want horizontal at %s", reply.Player, reply.Peg, move) + } +}