ferravex_play/navigation/
search.rs

1use super::{Cell, Connectivity, Grid, NavigationError, heuristic};
2use crate::ai::WorkBudget;
3pub const MAX_SEARCH_CELLS: usize = 4_000_000;
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5pub enum SearchStatus {
6    /// No search is running, including after explicit cancellation.
7    Idle,
8    /// Cell expansion is pending; another work allowance can resume it.
9    Searching,
10    /// The goal was reached, but budgeted path reconstruction is pending.
11    Tracing,
12    Found,
13    /// The reachable frontier was exhausted without reaching the goal.
14    /// A planner also uses this for rejected requests; consult [`PathPlanner::result`].
15    NoPath,
16    /// The supplied grid no longer matches the searched grid snapshot.
17    Stale,
18}
19#[derive(Clone, Copy, Debug)]
20pub struct SearchProgress {
21    pub status: SearchStatus,
22    /// Work consumed by this call, including path reconstruction.
23    pub work: u32,
24}
25impl SearchProgress {
26    /// Whether a running search yielded because its work allowance ran out.
27    ///
28    /// This includes a zero allowance while searching or tracing. A terminal
29    /// outcome such as [`SearchStatus::NoPath`] takes precedence even when the
30    /// call consumed the exact allowance. An idle planner with queued requests
31    /// has not started a search and returns `false`.
32    ///
33    /// ```
34    /// use ferravex_play::navigation::{Cell, Connectivity, Grid, SearchScratch, SearchStatus};
35    /// let mut grid = Grid::new(3, 1).unwrap();
36    /// let mut search = SearchScratch::new(3).unwrap();
37    /// search.begin(&grid, Cell { x: 0, y: 0 }, Cell { x: 2, y: 0 }, Connectivity::Four).unwrap();
38    /// assert!(search.step(&grid, 1).budget_exhausted());
39    /// assert_eq!(search.step(&grid, 5).status, SearchStatus::Found);
40    /// grid.set_blocked(Cell { x: 1, y: 0 }, true).unwrap();
41    /// search.restart(&grid).unwrap();
42    /// let progress = search.step(&grid, 1);
43    /// assert_eq!(progress.status, SearchStatus::NoPath);
44    /// assert!(!progress.budget_exhausted());
45    /// ```
46    pub fn budget_exhausted(&self) -> bool {
47        matches!(self.status, SearchStatus::Searching | SearchStatus::Tracing)
48    }
49}
50/// Indexed binary heap: at most one open entry per cell. Scratch, heap and route
51/// storage are allocated once; decreases do not insert duplicate heap entries.
52pub struct SearchScratch {
53    stamps: Vec<u32>,
54    distance: Vec<u64>,
55    parent: Vec<usize>,
56    positions: Vec<usize>,
57    open: Vec<usize>,
58    route: Vec<Cell>,
59    epoch: u32,
60    status: SearchStatus,
61    total_work: u64,
62    width: u32,
63    height: u32,
64    revision: u64,
65    identity: u64,
66    start: usize,
67    end: usize,
68    trace: usize,
69    connectivity: Connectivity,
70}
71impl SearchScratch {
72    pub fn new(capacity: usize) -> Result<Self, NavigationError> {
73        if capacity == 0 || capacity > MAX_SEARCH_CELLS {
74            return Err(NavigationError::Capacity);
75        }
76        Ok(Self {
77            stamps: vec![0; capacity],
78            distance: vec![0; capacity],
79            parent: vec![usize::MAX; capacity],
80            positions: vec![usize::MAX; capacity],
81            open: Vec::with_capacity(capacity),
82            route: Vec::with_capacity(capacity),
83            epoch: 0,
84            status: SearchStatus::Idle,
85            total_work: 0,
86            width: 0,
87            height: 0,
88            revision: 0,
89            identity: 0,
90            start: 0,
91            end: 0,
92            trace: 0,
93            connectivity: Connectivity::Four,
94        })
95    }
96    pub fn capacity(&self) -> usize {
97        self.stamps.len()
98    }
99    pub fn status(&self) -> SearchStatus {
100        self.status
101    }
102    /// Work consumed since the last successful [`Self::begin`] or [`Self::restart`].
103    ///
104    /// Counts both expanded cells and traced parents. Cancellation, stale-grid
105    /// detection and rejected requests preserve this count; a fresh search
106    /// resets it. This is observed work, not an estimate of work remaining.
107    ///
108    /// ```
109    /// use ferravex_play::navigation::{Cell, Connectivity, Grid, SearchScratch};
110    /// let grid = Grid::new(2, 1).unwrap();
111    /// let mut search = SearchScratch::new(2).unwrap();
112    /// search.begin(&grid, Cell { x: 0, y: 0 }, Cell { x: 1, y: 0 }, Connectivity::Four).unwrap();
113    /// search.step(&grid, 1);
114    /// search.step(&grid, 1);
115    /// assert_eq!(search.total_work(), 2);
116    /// search.step(&grid, 2); // Two cells of path reconstruction.
117    /// assert_eq!(search.total_work(), 4);
118    /// ```
119    pub fn total_work(&self) -> u64 {
120        self.total_work
121    }
122    /// Discard pending work and any path, returning whether the status changed.
123    ///
124    /// Sets the status to [`SearchStatus::Idle`] without allocating or spending
125    /// search work. Repeated cancellation returns `false`. The last request and
126    /// its [`Self::total_work`] remain available for inspection and restart.
127    ///
128    /// ```
129    /// use ferravex_play::navigation::{Cell, Connectivity, Grid, SearchScratch, SearchStatus};
130    /// let grid = Grid::new(2, 1).unwrap();
131    /// let mut search = SearchScratch::new(2).unwrap();
132    /// search.begin(&grid, Cell { x: 0, y: 0 }, Cell { x: 1, y: 0 }, Connectivity::Four).unwrap();
133    /// search.step(&grid, 1);
134    /// assert!(search.cancel());
135    /// assert!(!search.cancel());
136    /// assert_eq!(search.step(&grid, 10).status, SearchStatus::Idle);
137    /// assert_eq!(search.total_work(), 1);
138    /// assert!(search.reverse_path().is_none());
139    /// ```
140    pub fn cancel(&mut self) -> bool {
141        let changed = self.status != SearchStatus::Idle;
142        self.open.clear();
143        self.route.clear();
144        self.status = SearchStatus::Idle;
145        changed
146    }
147    /// Restart the last successful request against the supplied grid snapshot.
148    ///
149    /// Reuses the original cell coordinates and connectivity, even if the grid
150    /// identity or dimensions changed. This also works after cancellation or a
151    /// terminal outcome. Returns [`NavigationError::InvalidInput`] if no request
152    /// has ever begun; other errors are the same as [`Self::begin`]. Every error
153    /// leaves the existing search and its work count unchanged. Like `begin`,
154    /// this reuses storage and only clears stamps on generation wrap.
155    ///
156    /// ```
157    /// use ferravex_play::navigation::{Cell, Connectivity, Grid, NavigationError, SearchScratch};
158    /// let mut grid = Grid::new(3, 1).unwrap();
159    /// let mut search = SearchScratch::new(3).unwrap();
160    /// assert_eq!(search.restart(&grid), Err(NavigationError::InvalidInput));
161    /// search.begin(&grid, Cell { x: 0, y: 0 }, Cell { x: 2, y: 0 }, Connectivity::Four).unwrap();
162    /// search.step(&grid, 1);
163    /// search.cancel();
164    /// grid.set_cost(Cell { x: 1, y: 0 }, 2).unwrap();
165    /// search.restart(&grid).unwrap();
166    /// assert_eq!(search.total_work(), 0);
167    /// assert!(search.step(&grid, 1).budget_exhausted());
168    /// ```
169    pub fn restart(&mut self, grid: &Grid) -> Result<(), NavigationError> {
170        if self.epoch == 0 {
171            return Err(NavigationError::InvalidInput);
172        }
173        self.begin(
174            grid,
175            self.cell(self.start),
176            self.cell(self.end),
177            self.connectivity,
178        )
179    }
180    /// Invalid requests leave an existing search unchanged. A valid request resets
181    /// it without allocation. Generation wrap clears stamps once in 2^32 starts.
182    pub fn begin(
183        &mut self,
184        grid: &Grid,
185        start: Cell,
186        end: Cell,
187        connectivity: Connectivity,
188    ) -> Result<(), NavigationError> {
189        let start = grid.index(start)?;
190        let end = grid.index(end)?;
191        if grid.costs.len() > self.capacity() {
192            return Err(NavigationError::Capacity);
193        }
194        if grid.costs[start] == 0 || grid.costs[end] == 0 {
195            return Err(NavigationError::BlockedEndpoint);
196        }
197        self.epoch = self.epoch.wrapping_add(1);
198        if self.epoch == 0 {
199            self.stamps.fill(0);
200            self.epoch = 1;
201        }
202        self.open.clear();
203        self.route.clear();
204        self.width = grid.width;
205        self.height = grid.height;
206        self.revision = grid.revision;
207        self.identity = grid.identity;
208        self.start = start;
209        self.end = end;
210        self.trace = end;
211        self.connectivity = connectivity;
212        self.status = SearchStatus::Searching;
213        self.total_work = 0;
214        self.stamps[start] = self.epoch;
215        self.distance[start] = 0;
216        self.parent[start] = usize::MAX;
217        self.positions[start] = 0;
218        self.open.push(start);
219        Ok(())
220    }
221    fn cell(&self, index: usize) -> Cell {
222        Cell {
223            x: index as u32 % self.width,
224            y: index as u32 / self.width,
225        }
226    }
227    fn less(&self, a: usize, b: usize) -> bool {
228        let end = self.cell(self.end);
229        let ea = self.distance[a] + heuristic(self.cell(a), end, self.connectivity);
230        let eb = self.distance[b] + heuristic(self.cell(b), end, self.connectivity);
231        (ea, self.distance[a], a) < (eb, self.distance[b], b)
232    }
233    fn swap(&mut self, a: usize, b: usize) {
234        self.open.swap(a, b);
235        self.positions[self.open[a]] = a;
236        self.positions[self.open[b]] = b;
237    }
238    fn up(&mut self, mut index: usize) {
239        while index > 0 {
240            let parent = (index - 1) / 2;
241            if !self.less(self.open[index], self.open[parent]) {
242                break;
243            }
244            self.swap(index, parent);
245            index = parent;
246        }
247    }
248    fn pop(&mut self) -> Option<usize> {
249        let first = *self.open.first()?;
250        let last = self.open.pop().unwrap();
251        self.positions[first] = usize::MAX;
252        if !self.open.is_empty() {
253            self.open[0] = last;
254            self.positions[last] = 0;
255            let mut i = 0;
256            loop {
257                let left = i * 2 + 1;
258                if left >= self.open.len() {
259                    break;
260                }
261                let right = left + 1;
262                let best =
263                    if right < self.open.len() && self.less(self.open[right], self.open[left]) {
264                        right
265                    } else {
266                        left
267                    };
268                if !self.less(self.open[best], self.open[i]) {
269                    break;
270                }
271                self.swap(i, best);
272                i = best;
273            }
274        }
275        Some(first)
276    }
277    /// One work unit pops/expands one cell (up to eight fixed neighbors), or
278    /// reconstructs one parent. Both phases honor the same tick allowance.
279    /// An empty frontier reports `NoPath` in the same call as its last expansion,
280    /// even when that expansion uses the final work unit. A zero allowance does
281    /// no expansion or tracing, but still invalidates results from another grid
282    /// snapshot, including an earlier `NoPath` result.
283    pub fn step(&mut self, grid: &Grid, max_work: u32) -> SearchProgress {
284        if matches!(
285            self.status,
286            SearchStatus::Searching
287                | SearchStatus::Tracing
288                | SearchStatus::Found
289                | SearchStatus::NoPath
290        ) && (grid.identity != self.identity
291            || grid.width != self.width
292            || grid.height != self.height
293            || grid.revision != self.revision)
294        {
295            self.status = SearchStatus::Stale;
296            self.route.clear();
297        }
298        let mut work = 0;
299        while work < max_work {
300            if self.status == SearchStatus::Tracing {
301                work += 1;
302                self.route.push(self.cell(self.trace));
303                if self.trace == self.start {
304                    self.status = SearchStatus::Found;
305                    break;
306                }
307                self.trace = self.parent[self.trace];
308                continue;
309            }
310            if self.status != SearchStatus::Searching {
311                break;
312            }
313            let Some(current) = self.pop() else {
314                self.status = SearchStatus::NoPath;
315                break;
316            };
317            work += 1;
318            if current == self.end {
319                self.trace = current;
320                self.status = SearchStatus::Tracing;
321                continue;
322            }
323            let c = self.cell(current);
324            for (dx, dy) in [
325                (-1_i64, 0_i64),
326                (0, -1),
327                (1, 0),
328                (0, 1),
329                (-1, -1),
330                (1, -1),
331                (1, 1),
332                (-1, 1),
333            ] {
334                let diagonal = dx != 0 && dy != 0;
335                if diagonal && self.connectivity == Connectivity::Four {
336                    continue;
337                }
338                let x = i64::from(c.x) + dx;
339                let y = i64::from(c.y) + dy;
340                if x < 0 || y < 0 || x >= i64::from(grid.width) || y >= i64::from(grid.height) {
341                    continue;
342                }
343                let next = Cell {
344                    x: x as u32,
345                    y: y as u32,
346                };
347                let index = (next.y * grid.width + next.x) as usize;
348                if grid.costs[index] == 0
349                    || diagonal
350                        && (!grid.walkable(Cell { x: next.x, y: c.y })
351                            || !grid.walkable(Cell { x: c.x, y: next.y }))
352                {
353                    continue;
354                }
355                let cost = self.distance[current]
356                    + u64::from(grid.costs[index]) * if diagonal { 14 } else { 10 };
357                if self.stamps[index] != self.epoch || cost < self.distance[index] {
358                    let was_open =
359                        self.stamps[index] == self.epoch && self.positions[index] != usize::MAX;
360                    self.stamps[index] = self.epoch;
361                    self.distance[index] = cost;
362                    self.parent[index] = current;
363                    if !was_open {
364                        self.positions[index] = self.open.len();
365                        self.open.push(index);
366                    }
367                    self.up(self.positions[index]);
368                }
369            }
370        }
371        if self.status == SearchStatus::Searching && self.open.is_empty() {
372            self.status = SearchStatus::NoPath;
373        }
374        self.total_work += u64::from(work);
375        SearchProgress {
376            status: self.status,
377            work,
378        }
379    }
380    pub fn step_budgeted(&mut self, grid: &Grid, budget: &mut WorkBudget) -> SearchProgress {
381        let result = self.step(grid, budget.remaining_path_steps());
382        assert!(budget.spend_path_steps(result.work));
383        result
384    }
385    /// Goal-to-start order avoids an unbudgeted reversal at completion.
386    pub fn reverse_path(&self) -> Option<&[Cell]> {
387        (self.status == SearchStatus::Found).then_some(&self.route)
388    }
389    /// Copying is explicit host work, bounded by the supplied output and path size.
390    /// Failure leaves output unchanged.
391    pub fn copy_path(&self, output: &mut [Cell]) -> Result<usize, NavigationError> {
392        let route = self.reverse_path().ok_or(NavigationError::NoPath)?;
393        if route.len() > output.len() {
394            return Err(NavigationError::Capacity);
395        }
396        for (out, cell) in output.iter_mut().zip(route.iter().rev()) {
397            *out = *cell;
398        }
399        Ok(route.len())
400    }
401}
402#[derive(Clone, Copy, Debug, PartialEq, Eq)]
403pub struct PathRequest {
404    pub agent: u64,
405    pub start: Cell,
406    pub end: Cell,
407    pub connectivity: Connectivity,
408}
409#[derive(Clone, Copy, Debug, PartialEq, Eq)]
410pub enum RequestStatus {
411    Queued,
412    Updated,
413    AlreadyActive,
414    Full,
415}
416/// Bounded FIFO planner. A ready result owns the scratch route until acknowledge;
417/// polling never discards it. Agent IDs/generations belong to the host.
418pub struct PathPlanner {
419    scratch: SearchScratch,
420    queue: Vec<PathRequest>,
421    capacity: usize,
422    active: Option<PathRequest>,
423    ready: bool,
424    dropped: u64,
425    error: Option<NavigationError>,
426}
427impl PathPlanner {
428    pub fn new(cells: usize, requests: usize) -> Result<Self, NavigationError> {
429        if requests == 0 || requests > 1024 {
430            return Err(NavigationError::Capacity);
431        }
432        Ok(Self {
433            scratch: SearchScratch::new(cells)?,
434            queue: Vec::with_capacity(requests),
435            capacity: requests,
436            active: None,
437            ready: false,
438            dropped: 0,
439            error: None,
440        })
441    }
442    pub fn request(&mut self, request: PathRequest) -> RequestStatus {
443        if self.active == Some(request) {
444            return RequestStatus::AlreadyActive;
445        }
446        if let Some(existing) = self.queue.iter_mut().find(|r| r.agent == request.agent) {
447            *existing = request;
448            return RequestStatus::Updated;
449        }
450        if self.queue.len() == self.capacity {
451            self.dropped = self.dropped.saturating_add(1);
452            return RequestStatus::Full;
453        }
454        self.queue.push(request);
455        RequestStatus::Queued
456    }
457    pub fn step(&mut self, grid: &Grid, budget: &mut WorkBudget) -> SearchProgress {
458        if self.ready {
459            return if self.error.is_some() {
460                SearchProgress {
461                    status: SearchStatus::NoPath,
462                    work: 0,
463                }
464            } else {
465                self.scratch.step(grid, 0)
466            };
467        }
468        if self.active.is_none() {
469            if self.queue.is_empty() || budget.remaining_path_steps() == 0 {
470                return SearchProgress {
471                    status: SearchStatus::Idle,
472                    work: 0,
473                };
474            }
475            let request = self.queue.remove(0);
476            self.active = Some(request);
477            if let Err(error) =
478                self.scratch
479                    .begin(grid, request.start, request.end, request.connectivity)
480            {
481                self.error = Some(error);
482                self.ready = true;
483                return SearchProgress {
484                    status: SearchStatus::NoPath,
485                    work: 0,
486                };
487            }
488        }
489        let progress = self.scratch.step_budgeted(grid, budget);
490        self.ready = matches!(
491            progress.status,
492            SearchStatus::Found | SearchStatus::NoPath | SearchStatus::Stale
493        );
494        progress
495    }
496    pub fn result(&self) -> Option<(PathRequest, Result<&[Cell], NavigationError>)> {
497        if !self.ready {
498            return None;
499        }
500        Some((
501            self.active.unwrap(),
502            if let Some(error) = self.error {
503                Err(error)
504            } else {
505                self.scratch
506                    .reverse_path()
507                    .ok_or(if self.scratch.status() == SearchStatus::Stale {
508                        NavigationError::InvalidInput
509                    } else {
510                        NavigationError::NoPath
511                    })
512            },
513        ))
514    }
515    pub fn acknowledge(&mut self) {
516        if self.ready {
517            self.active = None;
518            self.ready = false;
519            self.error = None;
520        }
521    }
522    pub fn cancel(&mut self, agent: u64) {
523        self.queue.retain(|r| r.agent != agent);
524        if self.active.is_some_and(|r| r.agent == agent) {
525            self.active = None;
526            self.ready = false;
527            self.error = None;
528        }
529    }
530    pub fn clear(&mut self) {
531        self.queue.clear();
532        self.active = None;
533        self.ready = false;
534        self.error = None;
535    }
536    pub fn dropped(&self) -> u64 {
537        self.dropped
538    }
539    pub fn pending(&self) -> usize {
540        self.queue.len() + usize::from(self.active.is_some())
541    }
542}
543
544#[cfg(test)]
545mod tests {
546    use super::*;
547
548    fn c(x: u32, y: u32) -> Cell {
549        Cell { x, y }
550    }
551
552    #[test]
553    fn exhaustion_distinguishes_searching_tracing_and_exact_completion() {
554        let grid = Grid::new(2, 1).unwrap();
555        let mut scratch = SearchScratch::new(2).unwrap();
556        assert!(!scratch.step(&grid, 0).budget_exhausted());
557        scratch
558            .begin(&grid, c(0, 0), c(1, 0), Connectivity::Four)
559            .unwrap();
560        let zero = scratch.step(&grid, 0);
561        assert!(zero.budget_exhausted());
562        assert_eq!(zero.work, 0);
563        assert_eq!(scratch.total_work(), 0);
564
565        let mut budget = WorkBudget::new(0, 0, 2);
566        let progress = scratch.step_budgeted(&grid, &mut budget);
567        assert_eq!(progress.status, SearchStatus::Tracing);
568        assert!(progress.budget_exhausted());
569        assert_eq!(progress.work, 2);
570        assert_eq!(budget.remaining_path_steps(), 0);
571        assert_eq!(budget.counts().path_steps, 2);
572        assert!(scratch.reverse_path().is_none());
573        assert_eq!(scratch.step_budgeted(&grid, &mut budget).work, 0);
574        assert_eq!(scratch.total_work(), 2);
575
576        let mut budget = WorkBudget::new(0, 0, 1);
577        assert!(scratch.step_budgeted(&grid, &mut budget).budget_exhausted());
578        assert!(scratch.reverse_path().is_none());
579        let mut budget = WorkBudget::new(0, 0, 1);
580        let progress = scratch.step_budgeted(&grid, &mut budget);
581        assert_eq!(progress.status, SearchStatus::Found);
582        assert!(!progress.budget_exhausted());
583        assert_eq!(progress.work, 1);
584        assert_eq!(scratch.total_work(), 4);
585        assert_eq!(scratch.reverse_path(), Some([c(1, 0), c(0, 0)].as_slice()));
586        assert_eq!(scratch.step(&grid, u32::MAX).work, 0);
587        assert_eq!(scratch.total_work(), 4);
588    }
589
590    #[test]
591    fn same_cell_request_still_budgets_reconstruction() {
592        let grid = Grid::new(1, 1).unwrap();
593        let mut scratch = SearchScratch::new(1).unwrap();
594        scratch
595            .begin(&grid, c(0, 0), c(0, 0), Connectivity::Eight)
596            .unwrap();
597        assert!(scratch.step(&grid, 1).budget_exhausted());
598        assert_eq!(scratch.status(), SearchStatus::Tracing);
599        assert!(scratch.step(&grid, 0).budget_exhausted());
600        assert_eq!(scratch.step(&grid, 1).status, SearchStatus::Found);
601        assert_eq!(scratch.total_work(), 2);
602        assert_eq!(scratch.reverse_path(), Some([c(0, 0)].as_slice()));
603    }
604
605    #[test]
606    fn unreachable_is_reported_on_the_last_allowed_expansion() {
607        let mut grid = Grid::new(4, 1).unwrap();
608        grid.set_blocked(c(2, 0), true).unwrap();
609        let mut scratch = SearchScratch::new(4).unwrap();
610        scratch
611            .begin(&grid, c(0, 0), c(3, 0), Connectivity::Four)
612            .unwrap();
613        assert!(scratch.step(&grid, 1).budget_exhausted());
614        let mut budget = WorkBudget::new(0, 0, 1);
615        let progress = scratch.step_budgeted(&grid, &mut budget);
616        assert_eq!(progress.status, SearchStatus::NoPath);
617        assert!(!progress.budget_exhausted());
618        assert_eq!(progress.work, 1);
619        assert_eq!(budget.counts().path_steps, 1);
620        assert_eq!(scratch.total_work(), 2);
621        assert_eq!(scratch.step(&grid, 0).status, SearchStatus::NoPath);
622        assert_eq!(scratch.step(&grid, 100).work, 0);
623
624        scratch.restart(&grid).unwrap();
625        let mut budget = WorkBudget::new(0, 0, 100);
626        assert_eq!(scratch.step_budgeted(&grid, &mut budget).work, 2);
627        assert_eq!(budget.remaining_path_steps(), 98);
628        assert_eq!(scratch.total_work(), 2);
629    }
630
631    #[test]
632    fn cancel_is_idempotent_in_every_phase_and_retains_restart_request() {
633        for status in [
634            SearchStatus::Searching,
635            SearchStatus::Tracing,
636            SearchStatus::Found,
637            SearchStatus::NoPath,
638            SearchStatus::Stale,
639        ] {
640            let mut grid = Grid::new(3, 1).unwrap();
641            let mut scratch = SearchScratch::new(3).unwrap();
642            if status == SearchStatus::NoPath {
643                grid.set_blocked(c(1, 0), true).unwrap();
644            }
645            scratch
646                .begin(&grid, c(0, 0), c(2, 0), Connectivity::Four)
647                .unwrap();
648            match status {
649                SearchStatus::Searching | SearchStatus::NoPath => {
650                    scratch.step(&grid, 1);
651                }
652                SearchStatus::Tracing => {
653                    scratch.step(&grid, 4);
654                }
655                SearchStatus::Found => {
656                    scratch.step(&grid, 6);
657                }
658                SearchStatus::Stale => {
659                    scratch.step(&grid, 1);
660                    grid.set_cost(c(1, 0), 2).unwrap();
661                    scratch.step(&grid, 0);
662                }
663                SearchStatus::Idle => unreachable!(),
664            }
665            assert_eq!(scratch.status(), status);
666            let work = scratch.total_work();
667            assert!(scratch.cancel());
668            assert!(!scratch.cancel());
669            assert!(scratch.reverse_path().is_none());
670            let mut output = [c(99, 99); 3];
671            assert_eq!(scratch.copy_path(&mut output), Err(NavigationError::NoPath));
672            assert_eq!(output, [c(99, 99); 3]);
673            grid.set_blocked(c(1, 0), false).unwrap();
674            let mut budget = WorkBudget::new(0, 0, 100);
675            let progress = scratch.step_budgeted(&grid, &mut budget);
676            assert_eq!(progress.status, SearchStatus::Idle);
677            assert!(!progress.budget_exhausted());
678            assert_eq!(progress.work, 0);
679            assert_eq!(scratch.total_work(), work);
680            assert_eq!(budget.remaining_path_steps(), 100);
681
682            scratch.restart(&grid).unwrap();
683            assert_eq!(scratch.total_work(), 0);
684            assert_eq!(scratch.step(&grid, 6).status, SearchStatus::Found);
685            assert_eq!(scratch.total_work(), 6);
686            assert_eq!(scratch.copy_path(&mut output), Ok(3));
687            assert_eq!(output, [c(0, 0), c(1, 0), c(2, 0)]);
688        }
689    }
690
691    #[test]
692    fn restart_uses_cell_coordinates_when_grid_dimensions_change() {
693        let original = Grid::new(4, 2).unwrap();
694        let replacement = Grid::new(3, 3).unwrap();
695        let mut scratch = SearchScratch::new(9).unwrap();
696        assert!(!scratch.cancel());
697        assert_eq!(
698            scratch.restart(&original),
699            Err(NavigationError::InvalidInput)
700        );
701        assert_eq!(
702            scratch.begin(&original, c(4, 0), c(0, 0), Connectivity::Four),
703            Err(NavigationError::OutOfBounds)
704        );
705        assert_eq!(
706            scratch.restart(&original),
707            Err(NavigationError::InvalidInput)
708        );
709        scratch
710            .begin(&original, c(1, 1), c(2, 1), Connectivity::Eight)
711            .unwrap();
712        scratch.step(&original, 1);
713        scratch.restart(&replacement).unwrap();
714        assert_eq!(scratch.step(&replacement, 4).status, SearchStatus::Found);
715        assert_eq!(scratch.reverse_path(), Some([c(2, 1), c(1, 1)].as_slice()));
716    }
717
718    #[test]
719    fn rejected_restart_preserves_progress_and_completed_route() {
720        let grid = Grid::new(3, 2).unwrap();
721        let too_small = Grid::new(2, 2).unwrap();
722        let too_large = Grid::new(4, 2).unwrap();
723        let mut blocked = Grid::new(3, 2).unwrap();
724        blocked.set_blocked(c(2, 1), true).unwrap();
725        for allowance in [1, 100] {
726            let mut scratch = SearchScratch::new(6).unwrap();
727            scratch
728                .begin(&grid, c(0, 0), c(2, 1), Connectivity::Eight)
729                .unwrap();
730            scratch.step(&grid, allowance);
731            let status = scratch.status();
732            let work = scratch.total_work();
733            let route = scratch.reverse_path().map(<[Cell]>::to_vec);
734            for (replacement, error) in [
735                (&too_small, NavigationError::OutOfBounds),
736                (&too_large, NavigationError::Capacity),
737                (&blocked, NavigationError::BlockedEndpoint),
738            ] {
739                assert_eq!(scratch.restart(replacement), Err(error));
740                assert_eq!(scratch.status(), status);
741                assert_eq!(scratch.total_work(), work);
742                assert_eq!(scratch.reverse_path(), route.as_deref());
743            }
744            assert_eq!(scratch.step(&grid, 100).status, SearchStatus::Found);
745            let mut output = [c(99, 99); 6];
746            let count = scratch.copy_path(&mut output).unwrap();
747            assert_eq!(
748                output[..count],
749                grid.path(c(0, 0), c(2, 1), Connectivity::Eight).unwrap()
750            );
751            scratch.restart(&grid).unwrap();
752            assert_eq!(scratch.total_work(), 0);
753            assert_eq!(scratch.status(), SearchStatus::Searching);
754        }
755    }
756
757    #[test]
758    fn unreachable_results_become_stale_without_spending_work() {
759        let mut grid = Grid::new(3, 1).unwrap();
760        grid.set_blocked(c(1, 0), true).unwrap();
761        let replacement = Grid::new(3, 1).unwrap();
762        let mut scratch = SearchScratch::new(3).unwrap();
763        scratch
764            .begin(&grid, c(0, 0), c(2, 0), Connectivity::Four)
765            .unwrap();
766        assert_eq!(scratch.step(&grid, 1).status, SearchStatus::NoPath);
767        let progress = scratch.step(&replacement, 0);
768        assert_eq!(progress.status, SearchStatus::Stale);
769        assert!(!progress.budget_exhausted());
770        assert_eq!(progress.work, 0);
771        assert_eq!(scratch.total_work(), 1);
772
773        scratch.restart(&grid).unwrap();
774        assert_eq!(scratch.step(&grid, 1).status, SearchStatus::NoPath);
775        grid.set_blocked(c(1, 0), false).unwrap();
776        let mut budget = WorkBudget::new(0, 0, 10);
777        assert_eq!(
778            scratch.step_budgeted(&grid, &mut budget).status,
779            SearchStatus::Stale
780        );
781        assert_eq!(budget.remaining_path_steps(), 10);
782        assert_eq!(scratch.total_work(), 1);
783        scratch.restart(&grid).unwrap();
784        assert_eq!(scratch.step(&grid, 6).status, SearchStatus::Found);
785    }
786
787    #[test]
788    fn restarts_and_budget_splits_preserve_tie_breaking_and_total_work() {
789        let mut grid = Grid::new(5, 3).unwrap();
790        grid.set_blocked(c(2, 1), true).unwrap();
791        grid.set_cost(c(1, 1), 10).unwrap();
792        let mut scratch = SearchScratch::new(15).unwrap();
793        for connectivity in [Connectivity::Four, Connectivity::Eight] {
794            let expected = grid.path(c(0, 1), c(4, 1), connectivity).unwrap();
795            // Equal-cost detours choose the lower cell index (the upper row).
796            assert_eq!(
797                expected[1],
798                c(u32::from(connectivity == Connectivity::Eight), 0)
799            );
800            scratch
801                .begin(&grid, c(0, 1), c(4, 1), connectivity)
802                .unwrap();
803            assert_eq!(scratch.step(&grid, 100).status, SearchStatus::Found);
804            let expected_work = scratch.total_work();
805            for allowance in [1, 2, 3, 7, 100] {
806                scratch.restart(&grid).unwrap();
807                let mut consumed = 0;
808                for _ in 0..100 {
809                    assert_eq!(scratch.step(&grid, 0).work, 0);
810                    let mut budget = WorkBudget::new(0, 0, allowance);
811                    let progress = scratch.step_budgeted(&grid, &mut budget);
812                    assert!(progress.work <= allowance);
813                    assert_eq!(progress.work, budget.counts().path_steps);
814                    consumed += u64::from(progress.work);
815                    assert_eq!(scratch.total_work(), consumed);
816                    if !progress.budget_exhausted() {
817                        break;
818                    }
819                }
820                assert_eq!(scratch.status(), SearchStatus::Found);
821                assert_eq!(scratch.total_work(), expected_work);
822                let mut output = [c(99, 99); 15];
823                let count = scratch.copy_path(&mut output).unwrap();
824                assert_eq!(output[..count], expected);
825            }
826        }
827    }
828
829    #[test]
830    fn planner_delivers_unreachable_at_exact_budget_and_invalidates_it_on_edit() {
831        let mut grid = Grid::new(3, 1).unwrap();
832        grid.set_blocked(c(1, 0), true).unwrap();
833        let mut planner = PathPlanner::new(3, 1).unwrap();
834        let request = PathRequest {
835            agent: 1,
836            start: c(0, 0),
837            end: c(2, 0),
838            connectivity: Connectivity::Four,
839        };
840        assert_eq!(planner.request(request), RequestStatus::Queued);
841        let mut zero = WorkBudget::new(0, 0, 0);
842        assert_eq!(planner.step(&grid, &mut zero).status, SearchStatus::Idle);
843        assert!(planner.result().is_none());
844        let mut budget = WorkBudget::new(0, 0, 1);
845        let progress = planner.step(&grid, &mut budget);
846        assert_eq!(progress.status, SearchStatus::NoPath);
847        assert!(!progress.budget_exhausted());
848        assert_eq!(
849            planner.result(),
850            Some((request, Err(NavigationError::NoPath)))
851        );
852        grid.set_blocked(c(1, 0), false).unwrap();
853        assert_eq!(planner.step(&grid, &mut zero).status, SearchStatus::Stale);
854        assert_eq!(
855            planner.result(),
856            Some((request, Err(NavigationError::InvalidInput)))
857        );
858        planner.acknowledge();
859        assert_eq!(planner.request(request), RequestStatus::Queued);
860        let mut budget = WorkBudget::new(0, 0, 6);
861        assert_eq!(planner.step(&grid, &mut budget).status, SearchStatus::Found);
862        assert_eq!(
863            planner.result().unwrap().1.unwrap(),
864            [c(2, 0), c(1, 0), c(0, 0)]
865        );
866    }
867
868    #[test]
869    fn scratch_epoch_wrap_clears_old_stamps_and_capacity_is_bounded() {
870        let grid = Grid::new(4, 4).unwrap();
871        let mut scratch = SearchScratch::new(16).unwrap();
872        scratch.epoch = u32::MAX;
873        scratch.stamps.fill(1);
874        scratch
875            .begin(
876                &grid,
877                Cell { x: 0, y: 0 },
878                Cell { x: 3, y: 3 },
879                Connectivity::Eight,
880            )
881            .unwrap();
882        assert_eq!(scratch.step(&grid, 100).status, SearchStatus::Found);
883        assert!(scratch.open.len() <= 16);
884        assert!(scratch.route.len() <= 16);
885        let old = scratch.reverse_path().unwrap().to_vec();
886        assert_eq!(
887            scratch.begin(
888                &grid,
889                Cell { x: 8, y: 8 },
890                Cell { x: 0, y: 0 },
891                Connectivity::Four
892            ),
893            Err(NavigationError::OutOfBounds)
894        );
895        assert_eq!(scratch.reverse_path().unwrap(), old);
896    }
897}