tilezz 0.2.0

Utilities to work with perfect-precision polygonal tiles built on top of cyclotomic integer rings.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
//! Heesch-number filter -- the surroundability stage of the candidate-filter
//! pipeline, generalising "first corona" to "how many coronas".
//!
//! The **Heesch number** of a tile is the maximum number of times it can be
//! completely surrounded by successive coronas (rings of copies, rotations
//! only -- single-chirality glue). A tile that tiles the plane has infinite
//! Heesch number; a **finite** Heesch number is a *sound* proof the tile
//! *cannot* tile. So:
//!
//! - Heesch 0  -> cannot even be surrounded once -> reject (the `bound = 1` case);
//! - Heesch k (0 < k < bound) -> dies after k coronas -> reject;
//! - Heesch >= bound -> reached our search horizon -> candidate.
//!
//! All claims are within the pipeline's scope -- single chirality (see the
//! [`classify`](crate::classify) module docs). The search itself is
//! edge-to-edge, which is no loss for the cannot-tile verdicts by the
//! edge-to-edge reduction theorem (`docs/math/edge-to-edge-reduction.md`).
//!
//! [`heesch_number`] computes it up to `bound` coronas by exhaustive
//! backtracking. The central tile is patch-instance 0; a corona is complete
//! when the frozen patch is fully SURROUNDED -- every boundary edge buried
//! AND every boundary vertex sealed to a full turn (the true-Heesch test;
//! see the "Corona completion" block below -- edge burial alone is only an
//! upper bound). Corona k+1 then buries the whole corona-k patch (every
//! instance placed so far -- a `threshold` on instance ids).
//! "First corona" is just `bound = 1`. A node budget caps the search; hitting
//! it yields [`Heesch::Unknown`] (a lower bound -- never a wrong reject).

// FxHashSet (fixed-seed) for the search-hot frozen/cursed sets: membership
// tests run per boundary vertex per search node, and only membership is used
// (no iteration-order dependence), so the faster hasher is a free win.
use rustc_hash::FxHashSet as HashSet;
use std::sync::Arc;

use crate::classify::grow;
use crate::combinatorics::junctiontypes::OpenJunctionTypeIndex;
use crate::cyclotomic::IsRing;
use crate::geom::matches::PatchMatch;
use crate::geom::patch::{EPatch, Patch};
use crate::geom::rat::Rat;
use crate::geom::tileset::TileSet;
use crate::geom::vertices::OpenJunctionType;

/// The "cursed" (Dead or Undead) open junction types of `tileset`: local junction
/// configurations that provably can NEVER be closed (completed to a full turn),
/// by the reachability fixpoint in [`OpenJunctionTypeIndex`]. A frozen patch vertex
/// that matches one of these can never be sealed, so any corona forcing it is
/// doomed -- the forward-check prune for [`heesch_number`] that abandons a dead
/// branch long before it would otherwise bottom out. Empty for tiles whose every
/// junction type is closable (e.g. tilers), making the check a free no-op there.
/// Sound because junction types are faithful (every junction's `inner` reproduces
/// its boundary angle; see `update_inner_petals` in patch/mod.rs), so a cursed type
/// is a genuinely non-closable local configuration.
pub(crate) fn cursed_junction_types<T: IsRing>(
    tileset: &Arc<TileSet<T>>,
) -> HashSet<OpenJunctionType> {
    OpenJunctionTypeIndex::new(tileset.clone())
        .entries()
        .iter()
        .filter(|e| e.is_cursed())
        .map(|e| e.jtype().clone())
        .collect()
}

/// Whether any frozen boundary vertex of `patch` currently carries a cursed
/// (non-closable) junction type -- i.e. this partial corona can never complete.
/// Only junctions have a type; a frozen corner not yet a junction is
/// still open and uncommitted, so it is skipped.
///
/// The junction typing is supplied as `junction_at` (a `(patch, position) ->
/// junction type` lookup), so the burial search stays bounded on the core
/// [`Patch`] surface and never depends on the interior junction layer: the
/// cursed-set caller passes the real junction type at each vertex, and a junctionless caller
/// (the grower, which runs with an empty `cursed`) passes a `None`-returning stub
/// that the short-circuit below never even reaches.
fn has_cursed_frozen<T: IsRing, P: Patch<T>, J: Fn(&P, usize) -> Option<OpenJunctionType>>(
    patch: &P,
    frozen: &HashSet<T>,
    cursed: &HashSet<OpenJunctionType>,
    junction_at: &J,
) -> bool {
    if cursed.is_empty() {
        return false;
    }
    let pos = patch.boundary_positions();
    for (i, p) in pos.iter().enumerate().take(patch.angles().len()) {
        if frozen.contains(p)
            && let Some(jt) = junction_at(patch, i)
            && cursed.contains(&jt)
        {
            return true;
        }
    }
    false
}

/// Result of a Heesch search up to a corona bound.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Heesch {
    /// Exact, proven Heesch number, strictly below the bound. `Finite(0)`
    /// means the tile cannot be surrounded at all. Any `Finite` is a sound
    /// "cannot tile".
    Finite(usize),
    /// Reached the corona bound: Heesch number >= the bound -- a candidate
    /// for the next filter.
    AtLeast(usize),
    /// Budget exhausted before deciding; Heesch number >= the carried lower
    /// bound, exact value unknown. Must not be read as a reject.
    Unknown(usize),
}

impl Heesch {
    /// Whether this is a sound "cannot tile" verdict.
    pub fn cannot_tile(self) -> bool {
        matches!(self, Heesch::Finite(_))
    }
}

// ---------------------------------------------------------------------------
// Corona completion: TRUE Heesch via a frozen-vertex COORDINATE snapshot.
//
// A corona is complete when the frozen patch is fully SURROUNDED: every
// boundary EDGE buried AND every boundary VERTEX sealed (its incident tile
// angles summing to a full turn, so the vertex leaves the boundary). An
// edge-only test ("no frozen instance owns a boundary edge") would compute
// edge-Heesch, an UPPER BOUND on true Heesch -- a frozen corner can have both
// its edges covered yet still sit on the boundary as an unsealed wedge. We
// compute TRUE Heesch via a vertex test keyed on COORDINATES:
//   - at each corona start, [`frozen_coords`] snapshots the frozen patch's
//     boundary-vertex coordinates;
//   - the corona is complete iff none of those coords remains on the current
//     boundary ([`frozen_open`] `== 0`). This subsumes the edge test: an exposed
//     frozen edge has frozen endpoints on the boundary.
//   - wedge sealing is driven by `get_matches_touching_vertex(i)` at an
//     offending coord, with [`frozen_open`] (total open wedge angle over frozen
//     vertices) as the strictly-decreasing progress measure.
//
// WHY COORDINATES, NOT INDICES. add_tile renumbers boundary positions (a glue
// shifts the following indices) and normalize rotates them, so any INDEX-keyed
// "is this junction still here?" test is fooled: a vertex that merely moved to a
// new index looks "gone". Coordinates sidestep that, by three VERIFIED
// EPatch invariants (patch/mod.rs):
//   1. add_tile SPLICES positions -- carries surviving boundary coords forward
//      UNCHANGED and appends the new tile's vertices in the same absolute frame;
//      it never re-traces from origin. A vertex's coord is stable from when it
//      appears until it leaves the boundary (reindexed, never moved).
//   2. normalize only REINDEXES (rotates the array); coord VALUES are untouched.
//   3. positions are exact ring elements (T); coord equality is exact.
// So a surviving-but-reindexed vertex keeps its coord (still found), while a
// truly sealed vertex has its coord REMOVED from boundary_positions (it is now
// interior), not merely renumbered. The set membership is index-shift immune.
//
// SHADOWING cannot fool it either: a NEW corona vertex can land on a frozen
// coord X, but only when X is genuinely unsealed -- you cannot corner a tile at
// a fully-surrounded point (no angular room; the exact overlap check rejects
// it), and a sealed interior vertex never returns to the boundary. So
// "X in frozen_coords AND X on the current boundary" <=> a frozen corner at X is
// genuinely still on the boundary. No per-vertex provenance is needed.
// ---------------------------------------------------------------------------

/// Total OPEN wedge angle (ring units; a full turn is `T::turn()`) summed over
/// the current boundary vertices whose coordinate is in `frozen`. At a boundary
/// vertex the incident tiles cover interior angle `C`; the boundary turn there
/// is `angles()[i] = turn/2 - C`, so the still-open wedge is
/// `turn - C = turn/2 + angles()[i]`. It is `0` exactly when a frozen corner is
/// fully surrounded (it then leaves the boundary), so the sum is `0` iff the
/// frozen patch is fully surrounded -- edges buried AND wedges sealed. It also
/// strictly decreases whenever a tile fills a frozen wedge, so it doubles as the
/// search's progress measure.
fn frozen_open<T: IsRing, P: Patch<T>>(patch: &P, frozen: &HashSet<T>) -> i64 {
    let pos = patch.boundary_positions();
    let ang = patch.angles();
    let half = T::turn() as i64 / 2;
    (0..ang.len())
        .filter(|&i| frozen.contains(&pos[i]))
        .map(|i| half + ang[i] as i64)
        .sum()
}

/// Snapshot the boundary-vertex coordinates of the frozen patch (instances
/// `< threshold`) at a corona start, as the endpoints of the frozen boundary
/// edges. Valid as a snapshot because at a corona start the frozen set has no
/// hidden UNSEALED corner missing from it: a frozen corner strictly inside a
/// glued run is already a sealed interior vertex -- a glue match pairs edges
/// by reverse-complement, so at each interior junction of the run the two
/// tiles' angles sum to exactly a full turn -- and sealed vertices never
/// return to the boundary; every other frozen corner is an endpoint of some
/// frozen boundary edge and hence in the snapshot. Wedges form DURING the
/// corona and are then detected by [`frozen_open`] against this fixed
/// snapshot.
fn frozen_coords<T: IsRing, P: Patch<T>>(patch: &P, threshold: usize) -> HashSet<T> {
    let pos = patch.boundary_positions();
    let pt = patch.patch_tile_ids();
    let mut s = HashSet::default();
    for i in 0..pt.len() {
        if pt[i] < threshold {
            s.insert(pos[i]);
            s.insert(pos[i + 1]); // positions repeats the closing vertex, so i+1 is in range
        }
    }
    s
}

/// Number of boundary edges still owned by the frozen patch (instance id below
/// `threshold`) -- the edges that must be buried this corona. Cheap (it reads
/// `patch_tile_ids`) and gives a tight progress measure for the bulk of the
/// search; the vertex-seal check ([`frozen_open`]) only runs once these are 0.
fn exposed<T: IsRing, P: Patch<T>>(patch: &P, threshold: usize) -> usize {
    patch
        .patch_tile_ids()
        .iter()
        .filter(|&&id| id < threshold)
        .count()
}

/// Max coronas (capped at `bound`) reachable from `patch`, where `completed`
/// coronas are already built. The frozen patch is given two ways: `threshold`
/// (instance ids `< threshold`) drives the cheap edge-burial, and `frozen` (its
/// boundary-vertex coordinate snapshot) drives the true-completion test.
///
/// Two phases, cheap-first. While a frozen EDGE is exposed we bury it
/// (`get_matches_in_edge_range`, prune on the frozen-edge count -- the fast,
/// tight original logic). Once no frozen edge remains, the corona is truly
/// complete iff every frozen VERTEX is also sealed (`frozen_open == 0`);
/// otherwise we seal the residual wedges (`get_matches_touching_vertex`, prune
/// on the open-angle measure). Edge-burial does the bulk; wedge-sealing -- much
/// branchier -- runs only on the leftover wedges.
/// Records tiles as [`bury`] places them, so a caller that reaches its target can
/// read off the witnessing recipe. The search calls `push` before recursing into
/// a branch and `pop` on backtrack, so on SUCCESS (target reached, the winning
/// return unwinds without popping) the sink holds exactly the winning path.
/// `push` returns `false` to VETO a branch it cannot record (skip it, no recurse,
/// no matching `pop`) -- e.g. the grower's placement sink drops a tile whose
/// geometry it cannot capture in the base frame.
pub(crate) trait TileSink<T: IsRing, P: Patch<T>> {
    fn push(&mut self, pm: &PatchMatch, patch: &P, new_id: usize) -> bool;
    fn pop(&mut self);
    /// Notified when a corona CLOSES at `depth` coronas surrounded, with the
    /// `patch` at that closure -- the single ring-completion point in [`bury`].
    /// Default no-op; [`BestPathSink`] uses `depth` to snapshot the deepest
    /// witness recipe, and the grower's sink clones `patch`'s adjacency graph at
    /// the winning closure (the one point the search's final patch is in hand).
    /// First-success sinks ([`PathSink`]) ignore it.
    fn mark(&mut self, _depth: usize, _patch: &P) {}
}

/// Records the `PatchMatch` recipe of the search path (the corona-witness build).
pub(crate) struct PathSink<'a> {
    pub path: &'a mut Vec<PatchMatch>,
}
impl<T: IsRing, P: Patch<T>> TileSink<T, P> for PathSink<'_> {
    fn push(&mut self, pm: &PatchMatch, _: &P, _: usize) -> bool {
        self.path.push(*pm);
        true
    }
    fn pop(&mut self) {
        self.path.pop();
    }
}

/// Captures the DEEPEST gap-free corona witness reached during an exhaustion, so
/// the Heesch-number search returns its `build` recipe in the SAME pass -- no
/// separate re-derivation. `current` mirrors the live descent (push/pop); `best`
/// is snapshotted from `current` whenever a corona closes at a NEW maximum depth
/// ([`mark`](TileSink::mark)). `PatchMatch` is `Copy`, so the per-node push/pop is trivial next to
/// bury's per-node `patch.clone()`, and a snapshot happens only O(max coronas)
/// times -- capturing the witness in the exhaustion is ~free.
pub(crate) struct BestPathSink {
    current: Vec<PatchMatch>,
    best: Vec<PatchMatch>,
    best_depth: usize,
}
impl BestPathSink {
    fn new() -> Self {
        Self {
            current: Vec::new(),
            best: Vec::new(),
            best_depth: 0,
        }
    }
    /// Begin a fresh seed candidate: the live path restarts at its first glue (the
    /// grow match), mirroring `corona_witness`'s `path = vec![first]`. `best`
    /// persists across candidates, so it keeps the deepest witness seen so far.
    fn restart(&mut self, first: &PatchMatch) {
        self.current.clear();
        self.current.push(*first);
    }
}
impl<T: IsRing, P: Patch<T>> TileSink<T, P> for BestPathSink {
    fn push(&mut self, pm: &PatchMatch, _: &P, _: usize) -> bool {
        self.current.push(*pm);
        true
    }
    fn pop(&mut self) {
        self.current.pop();
    }
    fn mark(&mut self, depth: usize, _patch: &P) {
        if depth > self.best_depth {
            self.best_depth = depth;
            self.best.clone_from(&self.current);
        }
    }
}

/// The search-wide state of one corona-burial search: the fixed knobs (the
/// corona `bound`, the node `budget`, the `cursed` forward-check prune set,
/// `edge_only` mode) plus the mutable accounting (`spent` nodes, `budget_hit`).
/// One instance threads through a whole [`bury`] recursion -- and, for the
/// callers that share a budget across several seed candidates, through all of
/// their searches; the per-ring state (threshold / frozen / completed) stays
/// in the call frames.
pub(crate) struct BurySearch<'a> {
    pub bound: usize,
    pub budget: usize,
    pub spent: usize,
    pub budget_hit: bool,
    pub cursed: &'a HashSet<OpenJunctionType>,
    pub edge_only: bool,
    /// Enumeration mode: when set, [`branch`] does NOT short-circuit on
    /// reaching `bound`, so the search exhausts every sibling placement
    /// instead of stopping at the first success. Combined with `bound == k`
    /// and a [`CollectSink`], this visits every `k`-corona (each fires
    /// `mark(k)`). Off for the number / witness / grower searches.
    pub enumerate: bool,
}

impl<'a> BurySearch<'a> {
    /// A fresh search at `bound` coronas / `budget` nodes with the given prune
    /// set; `edge_only` selects the grower discipline (see [`bury`]).
    pub fn new(
        bound: usize,
        budget: usize,
        cursed: &'a HashSet<OpenJunctionType>,
        edge_only: bool,
    ) -> Self {
        BurySearch {
            bound,
            budget,
            spent: 0,
            budget_hit: false,
            cursed,
            edge_only,
            enumerate: false,
        }
    }
}

/// THE systematic corona-burial search -- the single implementation behind the
/// Heesch number, the corona witness, and the periodic-patch grower.
///
/// Buries every exposed frozen boundary edge, most-concave-first with
/// backtracking; then (unless `edge_only`) seals the residual frozen wedges the
/// same way; then recurses ring by ring, up to `bound` coronas. Returns the max
/// coronas reached, CAPPED at `bound` -- so a caller with `bound == target`
/// reads success as "returned `>= target`" (and finds the recipe in its `sink`),
/// while the Heesch search runs with `bound` = its search horizon and reads the
/// returned value as the Heesch number (or `bound` if the tile reaches it).
///
/// Knobs: `edge_only` skips the wedge phase (a growth corona closes on edge
/// burial alone -- the grower wants a compact periodic patch, not a surroundable
/// one). `cursed` is the forward-check prune set (empty = pruneless). `sink`
/// records the path (see [`TileSink`]); [`BestPathSink`] banks the deepest witness
/// as the exhaustion runs.
pub(crate) fn bury<
    T: IsRing,
    P: Patch<T>,
    S: TileSink<T, P>,
    J: Fn(&P, usize) -> Option<OpenJunctionType>,
>(
    patch: &P,
    threshold: usize,
    frozen: &HashSet<T>,
    completed: usize,
    ctx: &mut BurySearch<'_>,
    sink: &mut S,
    junction_at: &J,
) -> usize {
    let (bound, edge_only) = (ctx.bound, ctx.edge_only);
    let exp = exposed(patch, threshold);
    if exp > 0 {
        // EDGE-BURIAL phase: cover a frozen edge (cheap, tight prune). Any
        // frozen edge must eventually be buried, so the choice is free; pick the
        // most concave one (smallest boundary angle) -- a tight pocket admits the
        // fewest tiles, so this is fail-first ordering and collapses the tree.
        let ids = patch.patch_tile_ids();
        let angles = patch.angles();
        let edge = (0..ids.len())
            .filter(|&i| ids[i] < threshold)
            .min_by_key(|&i| angles[i])
            .expect("exp > 0");
        return branch(
            patch,
            threshold,
            frozen,
            completed,
            ctx,
            sink,
            junction_at,
            patch.get_matches_in_edge_range(edge, edge),
            // must bury a frozen edge (progress)
            |next| exposed(next, threshold) < exp,
        );
    }

    // All frozen edges buried (`exp == 0`). True completion also needs every
    // frozen wedge sealed (a corner with both edges covered but angle < a full
    // turn) -- UNLESS `edge_only`, where a corona is done the moment its edges
    // are buried (the grower's discipline). Burying edges is necessary for a
    // true corona, so an edge-only 0 (no edge-corona at all) already proves true
    // Heesch 0. `exp == 0 && m == 0` here IS [`corona_closed`] (its non-edge_only
    // form); kept componentwise because `exp`/`m` also drive the phase prunes.
    let m = if edge_only {
        0
    } else {
        frozen_open(patch, frozen)
    };
    if m == 0 {
        let done = completed + 1;
        sink.mark(done, patch); // corona closed: bank the witness / graph here
        if done >= bound {
            return bound;
        }
        // Bury the whole current patch: next corona's frozen set is all of it.
        let next_threshold = patch.next_tile_id();
        let next_frozen = frozen_coords(patch, next_threshold);
        return bury(
            patch,
            next_threshold,
            &next_frozen,
            done,
            ctx,
            sink,
            junction_at,
        );
    }

    // WEDGE-SEALING phase (residual): seal one unsealed frozen vertex. Picking
    // any one is complete -- every completion must seal it, and we branch over
    // every tile touching it (backtracking covers all orders). Pick the most
    // concave (smallest boundary angle): the tightest wedge admits the fewest
    // tiles, so this is fail-first ordering. Coordinate-keyed, so reindexing
    // between glues is irrelevant.
    let pos = patch.boundary_positions();
    let angles = patch.angles();
    let vi = (0..angles.len())
        .filter(|&i| frozen.contains(&pos[i]))
        .min_by_key(|&i| angles[i])
        .expect("frozen_open > 0 means a frozen vertex is on the boundary");
    branch(
        patch,
        threshold,
        frozen,
        completed,
        ctx,
        sink,
        junction_at,
        patch.get_matches_touching_vertex(vi),
        // must shrink the open wedge angle (progress)
        |next| frozen_open(next, frozen) < m,
    )
}

/// The shared branch loop of both [`bury`] phases: try each candidate glue,
/// keep only branches that make progress (the phase's strictly-decreasing
/// measure, supplied as `progress`) and pass the cursed forward-check, recurse,
/// and short-circuit at the bound (the winning path stays in the sink -- no pop
/// on success). Budget accounting charges one node per candidate tried.
#[allow(clippy::too_many_arguments)] // bury's own frame, threaded through
fn branch<
    T: IsRing,
    P: Patch<T>,
    S: TileSink<T, P>,
    J: Fn(&P, usize) -> Option<OpenJunctionType>,
>(
    patch: &P,
    threshold: usize,
    frozen: &HashSet<T>,
    completed: usize,
    ctx: &mut BurySearch<'_>,
    sink: &mut S,
    junction_at: &J,
    candidates: Vec<PatchMatch>,
    progress: impl Fn(&P) -> bool,
) -> usize {
    let (bound, budget) = (ctx.bound, ctx.budget);
    let mut best = completed;
    for pm in candidates {
        if ctx.spent >= budget {
            ctx.budget_hit = true;
            break;
        }
        ctx.spent += 1;
        let new_id = patch.next_tile_id();
        let mut next = patch.clone();
        if next.add_tile(&pm).is_none() {
            continue;
        }
        if !progress(&next) {
            continue;
        }
        if has_cursed_frozen(&next, frozen, ctx.cursed, junction_at) {
            continue; // a frozen corner is now provably unsealable -- dead branch
        }
        if !sink.push(&pm, &next, new_id) {
            continue; // sink cannot record this tile -- skip the branch
        }
        let d = bury(&next, threshold, frozen, completed, ctx, sink, junction_at);
        if d > best {
            best = d;
        }
        if best >= bound && !ctx.enumerate {
            return bound; // winning path retained in sink (no pop on success)
        }
        sink.pop();
    }
    best
}

/// Capture the `PatchMatch` recipe of a sample `target`-corona gap-free
/// surrounding of `tile_id` -- the cheap witness that the (true) Heesch number
/// is at least `target`. Returns the build (first glue included), or `None` if
/// no `target`-corona surrounding is found within `budget` (e.g. `target`
/// exceeds the real Heesch number). `target == 0` is the empty build (Heesch 0
/// needs no surrounding).
///
/// Runs the shared [`bury`] search (edge-burial then wedge-seal, concave-first)
/// with a [`PathSink`] and `bound == target`: it records the path and stops on the
/// first success -- a witness search, not an exhaustion, so it needs no prune.
pub(crate) fn corona_witness<T: IsRing>(
    tileset: &Arc<TileSet<T>>,
    tile_id: usize,
    target: usize,
    budget: usize,
) -> Option<Vec<PatchMatch>> {
    if target == 0 {
        return Some(Vec::new());
    }
    let seed = EPatch::single_tile(tileset.clone(), tile_id);
    let empty = HashSet::default();
    // One shared node budget across all first-glue candidates.
    let mut ctx = BurySearch::new(target, budget, &empty, false);
    for first in seed.get_all_matches() {
        let Some(gp) = seed.with_tile(&first) else {
            continue;
        };
        let frozen = frozen_coords(&gp, 1);
        let mut path = vec![first];
        // Same search as the Heesch number (edge-burial + wedge-seal), but stop on
        // the FIRST `target`-corona surrounding and keep its recipe: bound ==
        // target, a PathSink, no prune (this is a witness, not an exhaustion).
        let reached = {
            let mut sink = PathSink { path: &mut path };
            bury(&gp, 1, &frozen, 0, &mut ctx, &mut sink, &|p, i| {
                p.junction_type_at(i)
            }) >= target
        };
        if reached {
            return Some(path);
        }
        if ctx.spent >= budget {
            break;
        }
    }
    None
}

/// Collects the build recipe of EVERY corona that closes at the target depth
/// `k` during an enumeration ([`enumerate_coronas`]). Like [`BestPathSink`] it
/// mirrors the live descent via push/pop; `mark(k)` snapshots the current path.
/// A corona reachable by more than one glue order is snapshotted more than
/// once -- the caller dedups by canonical patch shape. Stops snapshotting at
/// `cap` (the search still unwinds; `enumerate_coronas` breaks between seeds).
struct CollectSink {
    k: usize,
    cap: usize,
    current: Vec<PatchMatch>,
    all: Vec<Vec<PatchMatch>>,
}
impl CollectSink {
    fn new(k: usize, cap: usize) -> Self {
        Self {
            k,
            cap,
            current: Vec::new(),
            all: Vec::new(),
        }
    }
    fn restart(&mut self, first: &PatchMatch) {
        self.current.clear();
        self.current.push(*first);
    }
}
impl<T: IsRing, P: Patch<T>> TileSink<T, P> for CollectSink {
    fn push(&mut self, pm: &PatchMatch, _: &P, _: usize) -> bool {
        self.current.push(*pm);
        true
    }
    fn pop(&mut self) {
        self.current.pop();
    }
    fn mark(&mut self, depth: usize, _patch: &P) {
        if depth == self.k && self.all.len() < self.cap {
            self.all.push(self.current.clone());
        }
    }
}

/// Canonical key of the corona a `build` recipe produces: the lex-min rotation
/// of its full patch boundary word (single-chirality, so rotation-canonical
/// suffices). Collapses coronas that are congruent up to rotation of the whole
/// patch to one representative. `None` if the recipe does not replay.
fn corona_key<T: IsRing>(base: &Rat<T>, build: &[PatchMatch]) -> Option<Vec<i8>> {
    if build.is_empty() {
        return Some(Vec::new());
    }
    let gp = grow::replay_recipe(base, build, |_, _| true)?;
    Some(crate::stringmatch::canonical_rotation(gp.to_rat().seq()))
}

/// Enumerate the build recipes of ALL distinct `k`-coronas of `tile_id`: every
/// gap-free way to surround it with `k` complete rings. `edge_only` selects
/// EDGE coronas (rings whose edges are all buried) vs TRUE coronas (edges
/// buried AND every wedge sealed) -- the same distinction `bury` draws.
///
/// Reuses the `bury` search in enumeration mode (no `best >= bound`
/// short-circuit, so every sibling placement is explored) with `bound == k`
/// and empty prune set (nothing sound is skipped), collecting each depth-`k`
/// closure and deduplicating by canonical patch boundary. Bounded by `budget`
/// nodes and `cap` distinct coronas to contain the combinatorial blow-up
/// (edge coronas / larger `k` can be huge). Returns the deduped builds and a
/// `hit_limit` flag (the enumeration was cut short by the budget or the cap).
pub fn enumerate_coronas<T: IsRing>(
    tileset: &Arc<TileSet<T>>,
    tile_id: usize,
    k: usize,
    edge_only: bool,
    budget: usize,
    cap: usize,
) -> (Vec<Vec<PatchMatch>>, bool) {
    if k == 0 {
        return (vec![Vec::new()], false);
    }
    let seed = EPatch::single_tile(tileset.clone(), tile_id);
    let empty = HashSet::default();
    let mut ctx = BurySearch::new(k, budget, &empty, edge_only);
    ctx.enumerate = true;
    // Over-collect (cap*4) raw closures so dedup still yields up to `cap`
    // distinct coronas even when several glue orders hit the same one.
    let mut sink = CollectSink::new(k, cap.saturating_mul(4));
    for first in seed.get_all_matches() {
        if ctx.spent >= budget || sink.all.len() >= sink.cap {
            break;
        }
        let Some(gp) = seed.with_tile(&first) else {
            continue;
        };
        let frozen = frozen_coords(&gp, 1);
        sink.restart(&first);
        bury(&gp, 1, &frozen, 0, &mut ctx, &mut sink, &|p, i| {
            p.junction_type_at(i)
        });
    }
    let base = tileset.rat(tile_id);
    let mut seen: HashSet<Vec<i8>> = HashSet::default();
    let mut out: Vec<Vec<PatchMatch>> = Vec::new();
    for build in sink.all {
        if out.len() >= cap {
            break;
        }
        if let Some(key) = corona_key::<T>(base, &build)
            && seen.insert(key)
        {
            out.push(build);
        }
    }
    let hit_limit = ctx.budget_hit || seen.len() >= cap;
    (out, hit_limit)
}

/// Advance the corona bookkeeping while the frozen patch (instances `< threshold`)
/// is fully surrounded: no exposed frozen edge AND no open frozen wedge means the
/// current corona closed, so bump `completed` and re-freeze everything placed so
/// far. Used by the recipe replayer [`count_coronas`] (the same freeze rule the
/// [`bury`] search advances one ring at a time).
/// A (true) corona is closed when the frozen patch (instances `< threshold`) is
/// fully surrounded: every frozen edge buried (`exposed == 0`) AND every frozen
/// wedge sealed (`frozen_open == 0`). The single completion rule shared by the
/// replay verifier [`advance_closed_coronas`] and the [`bury`] search -- whose
/// non-`edge_only` completion is this same predicate, but computed
/// componentwise (as `exp` / `m`) because those two terms also drive its
/// pruning, so it cannot afford to recompute them through this boolean.
fn corona_closed<T: IsRing, P: Patch<T>>(gp: &P, threshold: usize, frozen: &HashSet<T>) -> bool {
    exposed(gp, threshold) == 0 && frozen_open(gp, frozen) == 0
}

fn advance_closed_coronas<T: IsRing, P: Patch<T>>(
    gp: &P,
    threshold: &mut usize,
    frozen: &mut HashSet<T>,
    completed: &mut usize,
) {
    while corona_closed(gp, *threshold, frozen) {
        *completed += 1;
        *threshold = gp.next_tile_id();
        *frozen = frozen_coords(gp, *threshold);
    }
}

/// Count the complete gap-free coronas a patch built by replaying a
/// [`corona_witness`] recipe surrounds tile 0 with, by replaying the same
/// corona-completion bookkeeping: a corona closes when the frozen patch
/// (instances `< threshold`) is fully surrounded, after which the next corona
/// freezes everything placed so far. Used by `HeeschCert::verify_lower_bound`.
pub(crate) fn count_coronas<T: IsRing>(base: &Rat<T>, build: &[PatchMatch]) -> usize {
    if build.is_empty() {
        return 0;
    }
    let mut threshold = 1usize;
    let mut frozen: HashSet<T> = HashSet::default();
    let mut completed = 0usize;
    let mut initialized = false;
    // Replay the recipe and advance the corona bookkeeping after every glue (the
    // frozen set is seeded from the two-tile patch on the first observation).
    // A truncated replay (add_tile fails) just stops accumulating -- `completed`
    // then holds the coronas closed before the break, exactly as before.
    grow::replay_recipe(base, build, |gp, _new_id| {
        if !initialized {
            frozen = frozen_coords(gp, threshold);
            initialized = true;
        }
        advance_closed_coronas(gp, &mut threshold, &mut frozen, &mut completed);
        true
    });
    completed
}

/// One Heesch search up to `bound` coronas with a node `budget`, forward-checking
/// dead branches against the supplied `cursed` (non-closable) junction types (empty
/// = no prune). The public [`heesch_number`] decides when to build that set.
fn heesch_search<T: IsRing>(
    tileset: &Arc<TileSet<T>>,
    tile_id: usize,
    bound: usize,
    budget: usize,
    cursed: &HashSet<OpenJunctionType>,
    edge_only: bool,
) -> (Heesch, Vec<PatchMatch>) {
    if bound == 0 {
        return (Heesch::AtLeast(0), Vec::new());
    }
    let seed = EPatch::single_tile(tileset.clone(), tile_id);
    let candidates: Vec<_> = seed.get_all_matches();
    let mut ctx = BurySearch::new(bound, budget, cursed, edge_only);
    let mut best = 0usize;
    // Bank the deepest corona witness AS the exhaustion runs (see BestPathSink),
    // so this one search yields both the number and its build.
    let mut sink = BestPathSink::new();
    for pm in &candidates {
        if ctx.spent >= budget {
            ctx.budget_hit = true;
            break;
        }
        ctx.spent += 1;
        let Some(gp) = seed.with_tile(pm) else {
            continue;
        };
        // After the first glue: central tile = instance 0, frozen = {0}. Snapshot
        // the central tile's corner coords; corona 1 surrounds them.
        let frozen = frozen_coords(&gp, 1);
        sink.restart(pm);
        let d = bury(&gp, 1, &frozen, 0, &mut ctx, &mut sink, &|p, i| {
            p.junction_type_at(i)
        });
        if d > best {
            best = d;
        }
        if best >= bound {
            return (Heesch::AtLeast(bound), std::mem::take(&mut sink.best));
        }
    }
    let result = if ctx.budget_hit {
        Heesch::Unknown(best)
    } else {
        Heesch::Finite(best)
    };
    // Diagnostic (HEESCH_SPENT=1): report the node count a resolution actually
    // cost, to calibrate the deep budget to the true worst case rather than a
    // round guess. Off by default (per-call, so it must not fire in normal runs).
    if crate::classify::trace::heesch_spent() {
        eprintln!(
            "HEESCH_SPENT bound={bound} budget={budget} spent={} -> {result:?}",
            ctx.spent
        );
    }
    (result, std::mem::take(&mut sink.best))
}

/// Node budget for the cheap pruneless probe before escalating to the
/// cursed-vertex prune (bounds >= 2).
const ESCALATE_NODES: usize = 20_000;

/// The Heesch number of tile `tile_id` in `tileset`, up to `bound` coronas.
///
/// The cursed-junction forward-check needs an ~O(tile) junction-type catalog, far
/// too dear to build for every tile in a classification. So build it LAZILY: run the
/// cheap pruneless search first, and only if it does not resolve within the
/// probe ceiling -- a genuinely hard exhaustion -- build the cursed set and
/// re-run with the prune. The bulk (easy rejects exhaust, candidates
/// short-circuit) never pays the catalog build; only the hard tail does.
/// Verdicts are identical to an always-pruned search; only the catalog work is
/// deferred. Bound 1 never escalates (its search is short).
pub fn heesch_number<T: IsRing>(
    tileset: Arc<TileSet<T>>,
    tile_id: usize,
    bound: usize,
    budget: usize,
) -> Heesch {
    heesch_number_witnessed(tileset, tile_id, bound, budget).0
}

/// Like [`heesch_number`], but also returns the DEEPEST corona witness recipe
/// captured during the SAME search -- the `build` a [`crate::classify::cert::HeeschCert`]
/// records, with no separate re-derivation (the old two-search
/// number-then-`corona_witness` split). The witness reaches the returned number
/// of coronas (`heesch` for `Finite`/`Unknown`, `bound` for `AtLeast`); it is
/// empty exactly when that number is 0. Probe/escalate is identical to
/// [`heesch_number`]; the witness comes from whichever run RESOLVES.
pub fn heesch_number_witnessed<T: IsRing>(
    tileset: Arc<TileSet<T>>,
    tile_id: usize,
    bound: usize,
    budget: usize,
) -> (Heesch, Vec<PatchMatch>) {
    let empty = HashSet::default();
    // Bound-1 searches are short; the ~O(tile) catalog rarely pays off.
    if bound < 2 {
        return heesch_search(&tileset, tile_id, bound, budget, &empty, false);
    }
    // Cheap pruneless probe first; only a genuinely hard exhaustion (still
    // Unknown at the probe ceiling) pays for the cursed-junction catalog and
    // re-runs with the prune. The prune is SOUND now that junction types are
    // faithful (`cursed_junction_types` / the inner_petals fix), so verdicts are
    // identical to the pruneless search -- only the deep-reject tail is faster.
    let probe = heesch_search(
        &tileset,
        tile_id,
        bound,
        budget.min(ESCALATE_NODES),
        &empty,
        false,
    );
    if !matches!(probe.0, Heesch::Unknown(_)) {
        return probe;
    }
    let cursed = cursed_junction_types(&tileset);
    heesch_search(&tileset, tile_id, bound, budget, &cursed, false)
}

/// Run the Heesch search with a CALLER-SUPPLIED cursed-vertex set (the
/// forward-check prune). Lets a caller that has already paid for
/// [`cursed_junction_types`] reuse it, and lets probes measure the prune's effect
/// at any bound. `empty` cursed = pruneless. (Probe-only for now.)
#[cfg(all(test, feature = "cli"))]
pub(crate) fn heesch_search_cursed<T: IsRing>(
    tileset: &Arc<TileSet<T>>,
    tile_id: usize,
    bound: usize,
    budget: usize,
    cursed: &HashSet<OpenJunctionType>,
) -> Heesch {
    heesch_search(tileset, tile_id, bound, budget, cursed, false).0
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cyclotomic::ZZ12;
    use crate::geom::rat::Rat;
    use crate::geom::tiles;

    /// Test-default node budget; the pipeline's real budgets live in
    /// cascade.rs (H2_BUDGET / H3_BUDGET) and classify_tiles.rs (deep_budget /
    /// res_budget).
    const HEESCH_BUDGET: usize = 200_000;

    fn ts_of(rat: Rat<ZZ12>) -> Arc<TileSet<ZZ12>> {
        TileSet::single(rat)
    }

    /// enumerate_coronas: every returned build must be a genuine k-corona
    /// (count_coronas == k), the set is deduped (no two share a canonical
    /// boundary), and a Heesch-2 tile has >=1 true 1- and 2-corona while a
    /// non-tiler has none beyond its Heesch number. Reports the counts.
    #[test]
    #[ignore = "corona enumeration counts + validity (~seconds-minutes)"]
    fn enumerate_coronas_valid_and_deduped() {
        // idx 153373378, a proven Heesch-2 n=15 tile.
        let seq: &[i8] = &[-4, 0, 2, 2, 2, 2, -2, 0, 2, 0, 2, 4, -2, 0, 4];
        let ts = ts_of(Rat::<ZZ12>::from_slice_trusted(seq));
        let base = ts.rat(0);
        for (k, edge) in [(1, false), (2, false), (1, true), (2, true)] {
            let (builds, capped) = enumerate_coronas(&ts, 0, k, edge, 5_000_000, 500);
            let kind = if edge { "edge" } else { "true" };
            eprintln!(
                "{kind} {k}-coronas: {} distinct{}",
                builds.len(),
                if capped { " (CAPPED)" } else { "" }
            );
            assert!(
                !builds.is_empty(),
                "{kind} {k}-corona set empty for a Heesch-2 tile"
            );
            // every build is a genuine k-corona (true mode); edge mode only
            // guarantees the edges are buried, so count_coronas >= ... skip that
            // check for edge and just assert non-degenerate.
            let mut keys = std::collections::HashSet::new();
            for b in &builds {
                assert!(!b.is_empty(), "empty corona build");
                if !edge {
                    assert_eq!(count_coronas(base, b), k, "true {k}-corona has wrong depth");
                }
                assert!(
                    keys.insert(corona_key::<ZZ12>(base, b)),
                    "duplicate corona survived dedup"
                );
            }
        }
    }

    /// First-corona case (bound = 1): tilers surround, the dodecagon does not.
    #[test]
    fn first_corona_separates_tilers_from_dodecagon() {
        for (name, rat) in [
            (
                "triangle",
                Rat::from_snake_trusted(&tiles::triangle::<ZZ12>()),
            ),
            ("square", Rat::from_snake_trusted(&tiles::square::<ZZ12>())),
            (
                "hexagon",
                Rat::from_snake_trusted(&tiles::hexagon::<ZZ12>()),
            ),
        ] {
            let v = heesch_number(ts_of(rat), 0, 1, HEESCH_BUDGET);
            eprintln!("{name}: {v:?}");
            assert_eq!(v, Heesch::AtLeast(1), "{name} must surround");
        }
        let dodec = heesch_number(
            ts_of(Rat::from_snake_trusted(&tiles::dodecagon::<ZZ12>())),
            0,
            1,
            HEESCH_BUDGET,
        );
        eprintln!("dodecagon: {dodec:?}");
        assert_eq!(dodec, Heesch::Finite(0), "dodecagon cannot be surrounded");
    }

    /// True-Heesch regression at the default SCREENING bound (2): the bound the
    /// filter actually runs, where each tile resolves cheaply into one of three
    /// buckets with no budget-`Unknown`.
    ///
    /// (a) Proven-PERIODIC tiles must NOT be rejected -- a tiler surrounds
    ///     forever, so it reaches the bound (`AtLeast(2)`); a `Finite` here would
    ///     mean the wedge-sealing search missed a real sealing (unsound). The
    ///     critical no-false-reject check.
    /// (b) Cannot-tile tiles (edge-Heesch finite) resolve to either `Finite(k)`
    ///     with k < 2 -- REJECTED outright -- or `AtLeast(2)` -- a CANDIDATE that
    ///     reaches corona 2 and needs a deeper pass. Both are cheap: a tile with
    ///     true Heesch < 2 exhausts the (shallow) corona-2 search; one with true
    ///     Heesch >= 2 short-circuits the instant corona 2 closes. So bound 2
    ///     never produces `Unknown` (asserted) -- that is the screening win, and
    ///     the reason we screen low by default (deep exhaustion is for the tail).
    ///     true <= edge throughout.
    #[cfg(feature = "cli")]
    #[test]
    #[ignore = "regression: true-Heesch screening at bound 2 (the filter default)"]
    fn true_heesch_n10_regression() {
        const BOUND: usize = 2;
        const BUDGET: usize = 20_000_000; // bound-2 search is shallow; generous == no Unknown
        let ts = |s: &[i8]| ts_of(Rat::<ZZ12>::from_slice_trusted(s));

        // (a) proven periodic -> must not be Finite (reaches the bound).
        let tri = Rat::from_snake_trusted(&tiles::triangle::<ZZ12>());
        let periodic: [&[i8]; 4] = [
            tri.seq(),                          // triangle (Conway)
            &[-4, 3, 4, 1, 3, 5],               // isohedral p3/p4/p6
            &[-2, -1, 2, 5, -2, 1, 2, 1, 2, 4], // the unknown (3-domain)
            &[-4, 3, 4, 0, 4, -3, 5, 3],        // tile0 (8-domain)
        ];
        for seq in periodic {
            let t = std::time::Instant::now();
            let h = heesch_number(ts(seq), 0, BOUND, BUDGET);
            eprintln!("periodic {seq:?}: {h:?}  [{:?}]", t.elapsed());
            assert!(
                !h.cannot_tile(),
                "{seq:?} tiles; must not be Finite, got {h:?}"
            );
            assert!(
                !matches!(h, Heesch::Unknown(_)),
                "{seq:?}: bound-2 screen should not be Unknown, got {h:?}"
            );
        }

        // (b) cannot-tile tiles -> REJECTED (Finite, k < 2) or CANDIDATE
        // (AtLeast(2)); never Unknown; never a value above the edge bound.
        let finite: [(&[i8], usize); 5] = [
            (&[-2, 1, 4, -1, 4, -1, 2, -1, 5, 1], 3),
            (&[-3, 2, 4, -2, 5, -2, 3, -2, 5, 2], 3),
            (&[-1, 0, -1, 4, 1, 2, 1, 0, 1, 5], 3),
            (&[-3, 2, -3, 4, 3, 0, 3, -2, 3, 5], 3),
            (&[-2, 1, -2, 4, 2, 1, 2, -1, 2, 5], 4), // the suspect
        ];
        let (mut rejected, mut candidates) = (0usize, 0usize);
        for (seq, edge) in finite {
            let t = std::time::Instant::now();
            let h = heesch_number(ts(seq), 0, BOUND, BUDGET);
            let el = t.elapsed();
            match h {
                Heesch::Finite(k) => {
                    assert!(
                        k < BOUND && k <= edge,
                        "{seq:?}: Finite({k}) out of range (edge {edge})"
                    );
                    eprintln!("finite {seq:?}: REJECTED at Heesch {k} (edge {edge})  [{el:?}]");
                    rejected += 1;
                }
                Heesch::AtLeast(b) => {
                    assert_eq!(b, BOUND, "{seq:?}: AtLeast({b}) but bound is {BOUND}");
                    eprintln!(
                        "finite {seq:?}: CANDIDATE (reaches corona {b}, edge {edge})  [{el:?}]"
                    );
                    candidates += 1;
                }
                Heesch::Unknown(k) => {
                    panic!(
                        "{seq:?}: Unknown({k}) at bound {BOUND} after {el:?} -- screen should exhaust or short-circuit"
                    );
                }
            }
        }
        eprintln!(
            "bound-{BOUND} screen: {rejected} rejected outright, {candidates} candidates for a deeper pass"
        );
        assert_eq!(rejected + candidates, 5);
    }

    /// The dodecagon is Heesch 0 at any bound (still cannot be surrounded).
    #[test]
    fn dodecagon_heesch_zero_at_higher_bound() {
        let v = heesch_number(
            ts_of(Rat::from_snake_trusted(&tiles::dodecagon::<ZZ12>())),
            0,
            3,
            HEESCH_BUDGET,
        );
        eprintln!("dodecagon bound 3: {v:?}");
        assert_eq!(v, Heesch::Finite(0));
    }

    /// Regression for the inner_petals faithfulness fix: with the cursed-vertex
    /// prune ON, the n=12 tiler 700511 must NOT be rejected. Before the fix the
    /// lossy `inner` aliased its closable corona-2 junction (angle -2) onto a
    /// dead 30deg notch type (angle -5), giving a false `Finite(1)`. The pruned
    /// search must agree with the pruneless one: `AtLeast(2)`.
    #[cfg(feature = "cli")]
    #[test]
    #[ignore = "regression: faithful cursed prune must not false-reject n=12 tiler 700511 (bound-2, ~30s)"]
    fn cursed_prune_sound_on_700511() {
        let ts = ts_of(Rat::<ZZ12>::from_slice_trusted(&[
            -1, 0, 1, 1, 1, 4, -1, 1, -1, 2, 1, 4,
        ]));
        let cursed = cursed_junction_types(&ts);
        let pruned = heesch_search_cursed(&ts, 0, 2, 20_000_000, &cursed);
        let pruneless = heesch_number(ts.clone(), 0, 2, 20_000_000);
        assert_eq!(pruneless, Heesch::AtLeast(2), "pruneless: 700511 tiles");
        assert_eq!(
            pruned,
            Heesch::AtLeast(2),
            "faithful prune must NOT reject the tiler 700511"
        );
    }

    /// Tilers reach the bound (Heesch >= 2): a second corona exists.
    #[test]
    #[ignore = "exploratory: second corona (heavier)"]
    fn tilers_reach_second_corona() {
        for (name, rat) in [
            (
                "triangle",
                Rat::from_snake_trusted(&tiles::triangle::<ZZ12>()),
            ),
            (
                "hexagon",
                Rat::from_snake_trusted(&tiles::hexagon::<ZZ12>()),
            ),
        ] {
            let v = heesch_number(ts_of(rat), 0, 2, HEESCH_BUDGET);
            eprintln!("{name} bound 2: {v:?}");
            assert!(!v.cannot_tile(), "{name} tiles, must not be rejected");
        }
    }

    /// MEASUREMENT harness (not a correctness test): serial wall-time of the
    /// bound-2 Heesch exhaustion on the five known finite n=10 tiles -- the
    /// hot-loop benchmark for changes to bury / the frozen-set machinery.
    /// Serial on purpose (an A/B timing must not fight thread contention).
    /// Run: `cargo test --release bench_heesch_bound2 -- --ignored --nocapture`.
    #[test]
    #[ignore = "measurement: serial bound-2 exhaustion wall time on hard n=10 tiles"]
    fn bench_heesch_bound2_hard_tiles() {
        let tiles: [&[i8]; 5] = [
            &[-2, 1, 4, -1, 4, -1, 2, -1, 5, 1],
            &[-3, 2, 4, -2, 5, -2, 3, -2, 5, 2],
            &[-1, 0, -1, 4, 1, 2, 1, 0, 1, 5],
            &[-3, 2, -3, 4, 3, 0, 3, -2, 3, 5],
            &[-2, 1, -2, 4, 2, 1, 2, -1, 2, 5],
        ];
        for rep in 0..3 {
            let t0 = std::time::Instant::now();
            for seq in tiles {
                let t = std::time::Instant::now();
                let h = heesch_number(
                    ts_of(Rat::<ZZ12>::from_slice_trusted(seq)),
                    0,
                    2,
                    20_000_000,
                );
                eprintln!("  rep {rep} {seq:?}: {h:?} in {:?}", t.elapsed());
            }
            eprintln!("rep {rep} TOTAL: {:?}", t0.elapsed());
        }
    }

    /// Parallel screening + dump: a work-stealing pool runs the Heesch filter
    /// over every free ZZ12 rat up to perimeter `HEESCH_N` (default 10),
    /// computing the Heesch number up to `HEESCH_BOUND` coronas (default 3)
    /// with per-tile node budget `HEESCH_BUDGET` (default 1e6). Each tile's
    /// result is dumped (flushed per line, so a timeout keeps partials) to
    /// `$TMPDIR/heesch_zz12_n{N}_b{BOUND}.tsv` as `CODE\t[seq]`, where CODE is
    /// `F{k}` (proven Heesch k -- F0/F1/F2... the finite, cannot-tile finds),
    /// `A{bound}` (reached the bound, candidate), or `U{k}` (budget hit).
    /// Run: `HEESCH_BUDGET=... cargo test --release --features cli
    /// screen_zz12_heesch_dump -- --ignored --nocapture`.
    #[cfg(feature = "cli")]
    #[test]
    #[ignore = "screening run + dump: parallel Heesch over ZZ12 free rats"]
    fn screen_zz12_heesch_dump() {
        use crate::enumerate::enumerate_dispatch;
        use crate::util::parallel::parallel_drain;
        use std::io::Write;
        use std::sync::Mutex;
        use std::time::Instant;

        let envn = |k: &str, d: usize| {
            std::env::var(k)
                .ok()
                .and_then(|s| s.parse().ok())
                .unwrap_or(d)
        };
        let n_max = envn("HEESCH_N", 10);
        let bound = envn("HEESCH_BOUND", 3);
        let budget = envn("HEESCH_BUDGET", 1_000_000);

        let seqs = enumerate_dispatch::<ZZ12>(n_max, 1, 1, true, false, false).0;
        let n = seqs.len();
        let workers = crate::util::available_workers();
        let out = std::env::temp_dir().join(format!("heesch_zz12_n{n_max}_b{bound}.tsv"));
        eprintln!(
            "Heesch bound {bound} budget {budget} on {n} ZZ12 rats (n<={n_max}), {workers} workers -> {}",
            out.display()
        );

        let file = Mutex::new(std::io::BufWriter::new(
            std::fs::File::create(&out).unwrap(),
        ));
        let t = Instant::now();
        // per-worker tally: [F0, F1, F(>=2), A(bound), Unknown]
        let s = parallel_drain(
            n,
            workers,
            || [0usize; 5],
            |tally, i| {
                let ts = ts_of(Rat::<ZZ12>::from_slice_trusted(&seqs[i]));
                let code = match heesch_number(ts, 0, bound, budget) {
                    Heesch::Finite(0) => {
                        tally[0] += 1;
                        "F0".to_string()
                    }
                    Heesch::Finite(1) => {
                        tally[1] += 1;
                        "F1".to_string()
                    }
                    Heesch::Finite(k) => {
                        tally[2] += 1;
                        format!("F{k}")
                    }
                    Heesch::AtLeast(b) => {
                        tally[3] += 1;
                        format!("A{b}")
                    }
                    Heesch::Unknown(k) => {
                        tally[4] += 1;
                        format!("U{k}")
                    }
                };
                let mut f = file.lock().unwrap();
                let _ = writeln!(f, "{code}\t{:?}", seqs[i]);
                let _ = f.flush();
            },
            |mut a, b| {
                for j in 0..5 {
                    a[j] += b[j];
                }
                a
            },
        );
        eprintln!(
            "done in {:?}: F0={} F1={} F(>=2,high-Heesch)={} A(>={bound})={} Unknown={}  dump={}",
            t.elapsed(),
            s[0],
            s[1],
            s[2],
            s[3],
            s[4],
            out.display()
        );
    }
}