From 9d44c3fea09a6030cfcd1941c29c5ca22a589c1a Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sun, 25 Oct 2026 04:56:51 +0300 Subject: [PATCH] Play against Maia: the tester's findings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Leaving a game in progress any way (window closed, Find in database, an update restart) asks «The game is on» first; «Resign and leave» asks nothing more. Find in database and the game data are hidden during the game. - Maia's pause is at most a fortieth of her time plus most of the increment, and her clock takes the pause only, not the computing: she never flags. - Take back gives the clock back to the user (and a first move stays free). - Maia plays no move a tenth as likely as her best: human mistakes, not a 2600 hanging her queen. - The clocks stand on screen while «The game is on» is open. - The moves played are not undone with Ctrl+Z after the end. - The dialog body scrolls in a low window; its buttons stay in view. - «Viewing an earlier position» has its own strip above the user's clock. - Weights that do not load are removed, so the dialog offers them again. - Who could not mate when time ran out is said right. - The checkpoint reader: checked sizes and offsets, bounded memo values. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/app.rs | 24 +++++- apps/desktop/src/game_view.rs | 127 ++++++++++++++++++++---------- apps/desktop/src/i18n.rs | 11 +++ apps/desktop/src/maia_download.rs | 9 +++ apps/desktop/src/play.rs | 96 +++++++++++++++------- crates/chess-core/src/game.rs | 9 +++ crates/maia/src/checkpoint.rs | 47 +++++++++-- 7 files changed, 240 insertions(+), 83 deletions(-) diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 38b387a..5f8f237 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -1748,10 +1748,15 @@ impl App { } fn request_close(&mut self, ctx: &egui::Context, intent: CloseIntent) { - // A comment being written goes into the game first; a game against Maia still - // being played ends (resigned, or dropped before the first moves). + // A comment being written goes into the game first. A game against Maia in + // progress asks «The game is on» (its answer leaves, or not); before its first + // moves it is just dropped. if let Some(g) = self.game.as_mut() { g.commit_editor(); + if g.playing_started() { + g.ask_leave(intent); + return; + } g.resign_if_playing(); } if self.game.as_ref().is_some_and(|g| g.game.is_modified()) { @@ -2079,7 +2084,12 @@ impl eframe::App for App { && let Some(g) = self.game.as_mut() { g.commit_editor(); - g.resign_if_playing(); + if g.playing_started() { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + g.ask_leave(CloseIntent::QuitApp); + } else { + g.resign_if_playing(); + } } // Quitting with a modified game left for another (reference tab): show that one, // so the question "save?" is about the game that has the changes. @@ -2094,9 +2104,13 @@ impl eframe::App for App { self.previous_games.truncate(k + 1); self.game = self.previous_games.pop(); } + // (A game against Maia in progress has asked «The game is on» instead.) if ctx.input(|i| i.viewport().close_requested()) && !self.allow_quit - && self.game.as_ref().is_some_and(|g| g.game.is_modified()) + && self + .game + .as_ref() + .is_some_and(|g| g.game.is_modified() && !g.playing_started()) { ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); self.confirm_close = Some(CloseIntent::QuitApp); @@ -2214,6 +2228,8 @@ impl eframe::App for App { self.toast(&ctx, msg); } GameAction::Save => self.save_current(&ctx, None), + GameAction::Leave(intent) => self.request_close(&ctx, intent), + GameAction::SaveAndLeave(intent) => self.save_current(&ctx, Some(intent)), GameAction::Rematch => { let next = self .game diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index 71487c0..b29fd93 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -69,8 +69,8 @@ pub struct GameView { /// What the play started with (for the end, a rematch). play_start: Option, /// «The game is on» asked (leaving during a game); the clocks wait meanwhile. - /// `true`: back to the previous game, not to the library. - play_leave: Option<(bool, std::time::Instant)>, + /// Where leaving goes, and since when the question is open. + play_leave: Option<(crate::app::CloseIntent, std::time::Instant)>, show_diagnostics: bool, engine_settings_open: bool, review: Review, @@ -103,6 +103,10 @@ pub enum GameAction { Save, /// After a game against Maia: the same again with colours swapped. Rematch, + /// Leaving after «The game is on» was answered. + Leave(crate::app::CloseIntent), + /// Saving into a database, then leaving. + SaveAndLeave(crate::app::CloseIntent), /// After a game against Maia: the play dialog. PlayAgain, /// Ctrl+Shift+S: choose the database to add the game to. @@ -941,12 +945,12 @@ impl GameView { let title = self.title(); ui.allocate_ui(vec2((title_room - result_w - mark_w).max(0.0), height), |ui| { // The title opens the game's data (players, event, date…). - if ui - .add( - egui::Label::new(RichText::new(&title).strong().size(16.0)) - .truncate() - .sense(Sense::click()), - ) + let label = egui::Label::new(RichText::new(&title).strong().size(16.0)) + .truncate(); + if self.play.is_some() { + ui.add(label); + } else if ui + .add(label.sense(Sense::click())) .on_hover_text(tr("Game data (F2)")) .on_hover_cursor(egui::CursorIcon::PointingHand) .clicked() @@ -990,7 +994,9 @@ impl GameView { // Find the position in a database: the last chosen one, or another. let searchable = self.search_line().is_some(); let why = tr("After a null move (--) this is a teaching scheme, not a position of a game: it is not searched"); - ui.add_enabled_ui(searchable && !databases.is_empty(), |ui| { + // Not during a game against Maia: it would leave the game. + let playing = self.play.is_some(); + if !playing { ui.add_enabled_ui(searchable && !databases.is_empty(), |ui| { ui.menu_button("⏷", |ui| { for db in databases { let name = db @@ -1013,7 +1019,7 @@ impl GameView { { actions.push(GameAction::FindPosition(None)); } - }); + }); } if let Some(text) = notes && ui .button(text) @@ -1991,7 +1997,6 @@ impl GameView { user_elo: start.user_elo, clock: start.clock.map(Clock::new), opponent: Opponent::start(weights, ctx), - warned: false, resign_asked: false, }); self.play_start = Some(start); @@ -2073,7 +2078,12 @@ impl GameView { /// A move at the end of the main line by the side to move: the clock, `[%clk]`, the /// sound, the end of the game, Maia's turn. - fn play_add(&mut self, m: Move, actions: &mut Vec) { + fn play_add( + &mut self, + m: Move, + spent: Option, + actions: &mut Vec, + ) { let end = self.play_end_node(); let mover = self.play_turn(); let Ok(id) = self.game.add_move(end, m) else { @@ -2083,14 +2093,13 @@ impl GameView { if let Some(s) = self.play.as_mut() { s.resign_asked = false; if let Some(c) = s.clock.as_mut() { - c.moved(mover, now); + c.moved(mover, now, spent); let left = c.left(mover, now); let _ = self .game .annotate(id, Vec::new(), vec![crate::play::clk_command(left)]); } } - // The moves of a game played are not undone as edits (the take-back is). self.goto(id); if let Some(snd) = self.sound_for(id) { actions.push(GameAction::Sound(snd)); @@ -2109,7 +2118,7 @@ impl GameView { self.goto(end); return; } - self.play_add(m, actions); + self.play_add(m, None, actions); } /// The clock and Maia's answers, each frame. @@ -2119,6 +2128,7 @@ impl GameView { } let Some(s) = self.play.as_mut() else { return }; if let Some(err) = s.opponent.failed() { + crate::maia_download::forget_broken(); actions.push(GameAction::Toast(trf( "Maia did not start: {e}", &[("e", &err)], @@ -2128,8 +2138,9 @@ impl GameView { actions.push(GameAction::Back); return; } - if let Some(m) = s.opponent.answer() { - self.play_add(m, actions); + if let Some((m, pause)) = s.opponent.answer() { + // Maia's clock takes her pause, not the program's computing. + self.play_add(m, Some(pause), actions); } let now = std::time::Instant::now(); let end_pos = self.game.position(self.play_end_node()).cloned(); @@ -2144,9 +2155,6 @@ impl GameView { self.finish_play(crate::play::Ending::Time { loser: side, draw }, actions); return; } - if side == s.user && left <= c.low() { - s.warned = true; - } ctx.request_repaint_after(std::time::Duration::from_millis(100)); } } @@ -2165,6 +2173,7 @@ impl GameView { }); self.game.set_result(ending.result()); self.game.set_tag("Termination", ending.termination()); + self.game.forget_history(); let end = self.play_end_node(); self.goto(end); if matches!(ending, crate::play::Ending::Checkmate { .. }) { @@ -2216,6 +2225,15 @@ impl GameView { && let Ok(parent) = self.game.delete_variation(id) { self.goto(parent); + let moved = self.game.mainline().iter().any(|&n| { + self.game + .parent(n) + .and_then(|p| self.game.position(p)) + .is_some_and(|p| p.turn() == user) + }); + if let Some(c) = self.play.as_mut().and_then(|s| s.clock.as_mut()) { + c.take_back(user, moved, std::time::Instant::now()); + } } self.ask_maia(); } @@ -2293,8 +2311,12 @@ impl GameView { if let Some(k) = leaving { let a = actions.remove(k); if self.play_started() { - let previous = matches!(a, GameAction::ReturnToPrevious); - self.play_leave = Some((previous, std::time::Instant::now())); + let intent = if matches!(a, GameAction::ReturnToPrevious) { + crate::app::CloseIntent::ReturnToPrevious + } else { + crate::app::CloseIntent::BackToLibrary + }; + self.ask_leave(intent); } else { if let Some(s) = self.play.as_mut() { s.opponent.forget(); @@ -2306,16 +2328,24 @@ impl GameView { } } + /// Leaving a game in progress (any way: back, the window closed, …) asks first; + /// the clocks wait while the question is open. + pub fn ask_leave(&mut self, intent: crate::app::CloseIntent) { + if self.play_leave.is_none() { + self.play_leave = Some((intent, std::time::Instant::now())); + } + } + + /// A game is in progress and its first moves are made (leaving it costs a result). + pub fn playing_started(&self) -> bool { + self.play.is_some() && self.play_started() + } + /// «The game is on»: resign and add, resign and leave, keep playing. fn leave_question(&mut self, ctx: &egui::Context, actions: &mut Vec) { - let Some((previous, since)) = self.play_leave else { + let Some((intent, since)) = self.play_leave else { return; }; - let action = if previous { - GameAction::ReturnToPrevious - } else { - GameAction::Back - }; let mut choice = None; egui::Modal::new(egui::Id::new("play_leave")).show(ctx, |ui| { ui.set_width(460.0); @@ -2345,13 +2375,16 @@ impl GameView { c.pause(waited); } match choice { + // Then the game goes on where the user was going once it is saved. 0 => { self.resign_if_playing(); - actions.push(GameAction::Save); + actions.push(GameAction::SaveAndLeave(intent)); } + // Leaving was the answer: no second question about saving. 1 => { self.resign_if_playing(); - actions.push(action); + self.game.mark_saved(); + actions.push(GameAction::Leave(intent)); } _ => {} } @@ -2384,6 +2417,24 @@ impl GameView { egui::Panel::top("play_card_top") .show_separator_line(false) .show(ui, |ui| self.clock_card(ui, top, user)); + if self.cursor != self.play_end_node() { + egui::Panel::bottom("play_viewing") + .show_separator_line(false) + .show(ui, |ui| { + if ui + .link( + RichText::new(tr( + "Viewing an earlier position · back to the game — End", + )) + .weak(), + ) + .clicked() + { + let end = self.play_end_node(); + self.goto(end); + } + }); + } egui::CentralPanel::default().show(ui, |ui| { egui::ScrollArea::vertical() .auto_shrink(false) @@ -2404,24 +2455,16 @@ impl GameView { } self.scroll_to_cursor = false; }); - if self.cursor != self.play_end_node() - && ui - .link( - RichText::new(tr("Viewing an earlier position · back to the game — End")) - .weak(), - ) - .clicked() - { - let end = self.play_end_node(); - self.goto(end); - } }); } /// A player's card: name, rating, the clock and what is going on. fn clock_card(&self, ui: &mut Ui, side: Color, user: Color) { let Some(s) = &self.play else { return }; - let now = std::time::Instant::now(); + // While «The game is on» is open, the clocks stand at the moment it opened. + let now = self + .play_leave + .map_or_else(std::time::Instant::now, |(_, since)| since); let turn = self.play_turn(); let active = turn == side; let left = s.clock.as_ref().map(|c| c.left(side, now)); diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 5c8cb61..1313391 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -10891,6 +10891,17 @@ const ROWS: &[[&str; 9]] = &[ "vaqt tugadi", "уақыт бітті", ], + [ + "Maia's time is up, but you cannot checkmate", + "у Maia вышло время, но вам нечем поставить мат", + "le temps de Maia est écoulé, mais vous ne pouvez pas mater", + "Maias Zeit ist abgelaufen, aber Sie können nicht mattsetzen", + "a Maia se le acabó el tiempo, pero no puedes dar mate", + "il tempo di Maia è scaduto, ma non puoi dare scacco matto", + "o tempo de Maia acabou, mas você não consegue dar mate", + "Maiada vaqt tugadi, lekin sizda mot qilishga yetarli kuch yo‘q", + "Maia-ның уақыты бітті, бірақ сізде мат қоюға күш жоқ", + ], ]; #[cfg(test)] diff --git a/apps/desktop/src/maia_download.rs b/apps/desktop/src/maia_download.rs index 7bbf15e..4482fef 100644 --- a/apps/desktop/src/maia_download.rs +++ b/apps/desktop/src/maia_download.rs @@ -30,6 +30,15 @@ pub fn installed() -> Option { p.is_file().then_some(p) } +/// The downloaded weights did not load: removed, so that the dialog offers them again. +pub fn forget_broken() { + if std::env::var_os("CP_MAIA").is_none() + && let Some(d) = dir() + { + let _ = std::fs::remove_file(d.join(FILE)); + } +} + #[derive(Clone, Debug, PartialEq)] pub enum Stage { Downloading { done: u64 }, diff --git a/apps/desktop/src/play.rs b/apps/desktop/src/play.rs index cf4c119..d23f1ca 100644 --- a/apps/desktop/src/play.rs +++ b/apps/desktop/src/play.rs @@ -218,17 +218,33 @@ impl Clock { } /// `c` has moved: its time is taken (not on its first move), the increment added, - /// the other side's clock starts. - pub fn moved(&mut self, c: Color, now: Instant) { + /// the other side's clock starts. `spent`: the time to take instead of what passed + /// (Maia's pause: the program's own computing is not her thinking). + pub fn moved(&mut self, c: Color, now: Instant, spent: Option) { let i = idx(c); if self.moved[i] { - self.left[i] = self.left(c, now); + self.left[i] = match spent { + Some(d) => self.left[i].saturating_sub(d), + None => self.left(c, now), + }; } self.moved[i] = true; self.left[i] += Duration::from_secs(u64::from(self.control.increment)); self.running = Some((!c, now)); } + /// A take-back: `side` moves now (its clock runs from `now`); `moved`: it has + /// moved before in the game left (else its next move is its first, free one). + pub fn take_back(&mut self, side: Color, moved: bool, now: Instant) { + if let Some((c, since)) = self.running + && self.moved[idx(c)] + { + self.left[idx(c)] = self.left[idx(c)].saturating_sub(now - since); + } + self.moved[idx(side)] = moved; + self.running = Some((side, now)); + } + /// The side to move, its clock running (after its first move). pub fn running(&self) -> Option { self.running.map(|(c, _)| c).filter(|c| self.moved[idx(*c)]) @@ -369,7 +385,7 @@ struct Request { /// An answer for an older generation (after a take-back, a resignation) is dropped. pub struct Opponent { tx: Sender, - rx: Receiver<(u64, Option)>, + rx: Receiver<(u64, Option, Duration)>, generation: u64, /// Loading failed: why (shown to the user). pub error: Arc>>, @@ -402,11 +418,16 @@ impl Opponent { r = newer; } let started = Instant::now(); - let p = maia.predict(&r.positions, r.self_elo, r.oppo_elo); + let mut p = maia.predict(&r.positions, r.self_elo, r.oppo_elo); + // Human mistakes, not accidents: a move less than a tenth as likely as + // the most likely one is not played (a 2600 does not hang the queen + // one time in five thousand). + let top = p.moves.first().map_or(0.0, |(_, pr)| *pr); + p.moves.retain(|(_, pr)| *pr >= 0.1 * top); let m = maia::pick(&p, 1.0, random_unit()); let rest = r.pause.saturating_sub(started.elapsed()); std::thread::sleep(rest); - if ans_tx.send((r.generation, m)).is_err() { + if ans_tx.send((r.generation, m, r.pause)).is_err() { return; } ctx.request_repaint(); @@ -440,13 +461,13 @@ impl Opponent { self.thinking = false; } - /// The move asked for last, when it has come. - pub fn answer(&mut self) -> Option { + /// The move asked for last, when it has come, with the pause it was given. + pub fn answer(&mut self) -> Option<(Move, Duration)> { let mut out = None; - while let Ok((g, m)) = self.rx.try_recv() { + while let Ok((g, m, pause)) = self.rx.try_recv() { if g == self.generation { self.thinking = false; - out = m; + out = m.map(|m| (m, pause)); } } out @@ -475,15 +496,16 @@ pub fn pause(clock: Option<(Duration, u32)>, ply: usize, only_move: bool) -> Dur None => 0.5 + 1.5 * r, Some((left, inc)) => { let left = left.as_secs_f32(); - if left < 10.0 { - 0.2 + 0.8 * r - } else { - let mut t = (left / 30.0 + 0.75 * inc as f32) * factor; - if ply < 10 { - t *= 0.3; - } - t.clamp(0.4, (left / 8.0).min(60.0)) + let inc = inc as f32; + let mut t = (left / 30.0 + 0.75 * inc) * factor; + if ply < 10 { + t *= 0.3; } + // Never more than a fortieth of the time left plus most of the increment: + // the clock only shrinks geometrically and never runs out, however long the + // game (a move also costs about 0.1 s of computing). + let most = (left / 40.0 + 0.8 * inc).min(60.0); + t.min(most).max(0.4f32.min(most)) } }; let secs = if only_move { @@ -544,10 +566,10 @@ mod tests { increment: 2, }); let t0 = Instant::now(); - c.moved(Color::White, t0); // the first move takes nothing + c.moved(Color::White, t0, None); // the first move takes nothing assert_eq!(c.left(Color::White, t0), Duration::from_secs(62)); // Black's first move: no time taken either. - c.moved(Color::Black, t0 + Duration::from_secs(5)); + c.moved(Color::Black, t0 + Duration::from_secs(5), None); assert_eq!( c.left(Color::Black, t0 + Duration::from_secs(5)), Duration::from_secs(62) @@ -555,7 +577,7 @@ mod tests { // White thinks 10 s. let t1 = t0 + Duration::from_secs(15); assert_eq!(c.left(Color::White, t1), Duration::from_secs(52)); - c.moved(Color::White, t1); + c.moved(Color::White, t1, None); assert_eq!(c.left(Color::White, t1), Duration::from_secs(54)); assert_eq!(c.running(), Some(Color::Black)); assert_eq!(clock_text(Duration::from_millis(9_450)), "0:09.4"); @@ -610,11 +632,16 @@ mod tests { #[test] fn pauses_never_lose_on_time() { - for _ in 0..200 { - let p = pause(Some((Duration::from_secs(20), 0)), 30, false); - assert!(p <= Duration::from_millis(2500), "{p:?}"); - let p = pause(Some((Duration::from_secs(5), 0)), 30, false); - assert!(p <= Duration::from_millis(1000)); + // Whole games of 300 moves at 1+0, 3+0, 5+0 with 0.1 s of computing per move. + for base in [60.0f32, 180.0, 300.0] { + for _ in 0..20 { + let mut left = base; + for ply in 0..300 { + let p = pause(Some((Duration::from_secs_f32(left), 0)), ply * 2, false); + left -= p.as_secs_f32(); + assert!(left > 0.0, "flagged at {ply} with {base}"); + } + } } assert_eq!(strength_like(1350), 1400); assert_eq!(strength_like(300), 600); @@ -630,8 +657,6 @@ pub struct Session { pub user_elo: Option, pub clock: Option, pub opponent: Opponent, - /// The low-time warning was given (once). - pub warned: bool, /// «Resign?» waits for the second click. pub resign_asked: bool, } @@ -694,9 +719,15 @@ impl Dialog { use egui::RichText; let mut out = None; let installed = crate::maia_download::installed(); + let body_h = (ctx.content_rect().height() - 140.0).max(160.0); egui::Modal::new(egui::Id::new("play_dialog")).show(ctx, |ui| { ui.set_width(460.0); ui.heading(tr("Play against the computer")); + // The body scrolls in a low window; the buttons below it stay in view. + let (ready, rating) = egui::ScrollArea::vertical() + .max_height(body_h) + .auto_shrink([false, true]) + .show(ui, |ui| { ui.label( RichText::new(tr( "Maia plays like a human of the chosen rating: it makes the moves people of that level make, mistakes included.", @@ -875,7 +906,9 @@ impl Dialog { } } } - + (ready, rating) + }) + .inner; ui.add_space(6.0); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let play = ui @@ -954,7 +987,10 @@ impl End { Ending::InsufficientMaterial => tr("neither side can checkmate"), Ending::Threefold => tr("the position occurred three times"), Ending::FiftyMoves => tr("50 moves without a capture or a pawn move"), - Ending::Time { draw: true, .. } => tr("time is up, but Maia cannot checkmate"), + Ending::Time { draw: true, loser } if loser == self.user => { + tr("time is up, but Maia cannot checkmate") + } + Ending::Time { draw: true, .. } => tr("Maia's time is up, but you cannot checkmate"), Ending::Time { .. } => tr("time is up"), Ending::Resigned { .. } => "", } diff --git a/crates/chess-core/src/game.rs b/crates/chess-core/src/game.rs index c2b9a43..8ff7767 100644 --- a/crates/chess-core/src/game.rs +++ b/crates/chess-core/src/game.rs @@ -591,6 +591,15 @@ impl Game { self.unsaved_meta || self.saved_depth != Some(self.undo_stack.len()) } + /// Forgets the undo and redo history (the moves of a game played against the + /// computer are not edits to undo); whether the game is saved stays as it is. + pub fn forget_history(&mut self) { + let saved = self.saved_depth == Some(self.undo_stack.len()); + self.undo_stack.clear(); + self.redo_stack.clear(); + self.saved_depth = saved.then_some(0); + } + pub fn mark_saved(&mut self) { self.saved_depth = Some(self.undo_stack.len()); self.unsaved_meta = false; diff --git a/crates/maia/src/checkpoint.rs b/crates/maia/src/checkpoint.rs index 0a3fe27..def50f6 100644 --- a/crates/maia/src/checkpoint.rs +++ b/crates/maia/src/checkpoint.rs @@ -76,6 +76,18 @@ enum Value { None, } +/// How many values `v` holds (a value too big to be a checkpoint's is refused: clones +/// of the memo could otherwise grow without end). +fn size(v: &Value) -> usize { + match v { + Value::Tuple(items) => 1 + items.iter().map(size).sum::(), + Value::Dict(items) => 1 + items.iter().map(|(k, v)| size(k) + size(v)).sum::(), + _ => 1, + } +} + +const MAX_VALUE: usize = 100_000; + fn as_usizes(v: &Value) -> Result, WeightsError> { match v { Value::Tuple(items) => items @@ -121,12 +133,20 @@ fn unpickle(p: &[u8]) -> Result { b'(' => stack.push(Value::Mark), // MARK b'q' => { // BINPUT - memo.insert(usize::from(byte(i)?), stack.last().ok_or_else(bad)?.clone()); + let v = stack.last().ok_or_else(bad)?; + if size(v) > MAX_VALUE { + return Err(bad()); + } + memo.insert(usize::from(byte(i)?), v.clone()); i += 1; } b'r' => { // LONG_BINPUT - memo.insert(le(i, 4)?, stack.last().ok_or_else(bad)?.clone()); + let v = stack.last().ok_or_else(bad)?; + if size(v) > MAX_VALUE { + return Err(bad()); + } + memo.insert(le(i, 4)?, v.clone()); i += 4; } b'h' => { @@ -213,7 +233,9 @@ fn unpickle(p: &[u8]) -> Result { }; match f.as_str() { "torch._utils._rebuild_tensor_v2" => match args.as_slice() { - [Value::Storage(key), Value::Int(offset), shape, stride, ..] => { + [Value::Storage(key), Value::Int(offset), shape, stride, ..] + if *offset >= 0 => + { stack.push(Value::Tensor( key.clone(), *offset as usize, @@ -280,11 +302,14 @@ pub fn read(bytes: &[u8]) -> Result, WeightsError> { let (Value::Str(name), Value::Tensor(key, offset, shape, stride)) = (k, v) else { continue; }; - let n: usize = shape.iter().product(); + let n = shape + .iter() + .try_fold(1usize, |a, &d| a.checked_mul(d)) + .ok_or(WeightsError::Format)?; // Contiguous, row-major: what a saved state dict holds. let mut want = vec![1usize; shape.len()]; for d in (0..shape.len().saturating_sub(1)).rev() { - want[d] = want[d + 1] * shape[d + 1]; + want[d] = want[d + 1].saturating_mul(shape[d + 1]); } if n > 1 && stride != want { return Err(WeightsError::Format); @@ -292,7 +317,13 @@ pub fn read(bytes: &[u8]) -> Result, WeightsError> { let raw = members .get(&format!("{root}data/{key}")) .ok_or(WeightsError::Format)? - .get(offset * 4..(offset + n) * 4) + .get( + offset.checked_mul(4).ok_or(WeightsError::Format)? + ..offset + .checked_add(n) + .and_then(|e| e.checked_mul(4)) + .ok_or(WeightsError::Format)?, + ) .ok_or(WeightsError::Format)?; let data = raw .as_chunks::<4>() @@ -315,7 +346,9 @@ mod tests { assert!(read(b"PK\x05\x06garbage").is_err()); assert!(read(&[0u8; 100]).is_err()); // A pickle that calls anything but the state-dict constructors is refused. - assert!(unpickle(b"\x80\x02cos\nsystem\nq\x00X\x02\x00\x00\x00lsq\x01\x85q\x02R.").is_err()); + assert!( + unpickle(b"\x80\x02cos\nsystem\nq\x00X\x02\x00\x00\x00lsq\x01\x85q\x02R.").is_err() + ); assert!(unpickle(b"\x80\x02}q\x00.").is_ok()); } }