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
//! `rat_enum`: enumerate every simple polygon on a cyclotomic-ring
//! lattice with boundary length up to `n`. Output is controlled by
//! `--mode` -- see the `Mode` enum for the full menu.
//!
//! # Scaling to large `n`
//!
//! The in-memory modes (`--mode bench`, `--mode render`, `--mode
//! dafsa`, `--mode dafsa-blocks`) hold the entire result set as a
//! `HashSet<Vec<i8>>` of canonical (or free, i.e. dihedral-reduced) angle
//! sequences while the DFS runs. The *raw* payload is tiny (~`n`
//! bytes per polygon), but several effects multiply peak RSS by
//! ~50-100x:
//!
//! 1. **HashSet bucket overhead.** Per-entry control byte + cached
//!    hash + `Vec<i8>` header (24 B) + the malloc-rounded heap slab
//!    for the angles. ~80 bytes per polygon at typical loads.
//! 2. **Hashbrown doubling resize.** Mid-resize, both old and new
//!    bucket arrays are live: ~3x transient blowup per set.
//! 3. **Per-thread duplication.** Each parallel worker keeps a
//!    private HashSet for the whole DFS; final merge fans them in.
//! 4. **Final-merge double-buffer.** Worker locals sit in their
//!    `JoinHandle`s while the main set grows by `extend`; peak
//!    adds another ~2x.
//! 5. **Glibc arena retention.** Per-thread arenas don't release
//!    pages back to the OS once the high-water mark is reached.
//!
//! Empirically: ZZ12 free n=13 (4.08M polygons, ~50 MB raw)
//! peaks at **~5.5 GB** in a 16-thread `--mode bench`. n=14 (~30M
//! polygons) is out of reach for any single in-memory run on a
//! commodity workstation.
//!
//! # Recommendation: the streaming pipeline (`--mode stream` then
//! `--mode merge`)
//!
//! Workers stream closures to per-thread, bounded sort-buffer run
//! files instead of accumulating in HashSets; a separate merge
//! pass k-way dedupes the runs into a single sorted `unique.bin`
//! plus a `certificate.json` with the BLAKE3 hash. Memory is
//! bounded by `n_threads * buffer_size` (~16 MB/worker default),
//! regardless of the final rat count. Single host, single
//! invocation, no orchestrator:
//!
//! ```sh
//! ./target/release/rat_enum --ring 12 -n 14 --free \
//!     --mode stream -o out/ --threads 16
//! ./target/release/rat_enum --ring 12 -n 14 --free \
//!     --mode merge  -o out/
//! ./target/release/rat_enum --ring 12 -n 14 --free \
//!     --mode build  -o out/        # 4 MiB blocks by default
//! # out/dafsa/ now holds the blocked RatDafsa, readable by
//! # LazyRatDafsa / LazyRatDafsaAsync. out/certificate.json
//! # carries the BLAKE3 of unique.bin so the build is auditable.
//! ```
//!
//! Stage 3 (`--mode build`) reads `unique.bin` and streams each
//! record straight through `RatDafsa::from_sorted_unique_rats`
//! into a DAFSA builder, so peak RSS scales with the compressed
//! automaton (~12-32 bytes per state) rather than with the input
//! set (~80 bytes per HashSet entry).
//!
//! # Alternative: multi-host distribution (`--mode list-seeds`)
//!
//! Still relevant when you want to fan one enumeration out across
//! multiple machines (each runs `--seed <prefix> --threads 1` on
//! its share of the seed list). Per-process memory stays bounded
//! by that process's share -- the same multipliers above apply,
//! just to a smaller subset. For a single host though, prefer the
//! streaming pipeline: tighter memory bound, no result-set
//! concatenation step needed.
//!
//! `--seed <prefix> --threads N>1` exists for environments where
//! the orchestrator hands you one big slot at a time, but it has
//! the same per-process memory profile as `--mode bench --threads
//! N` -- it does NOT recover the single-threaded-per-process
//! savings.

use std::fs::File;
use std::io::BufWriter;
use std::sync::Mutex;
use std::time::Instant;

use clap::{Parser, ValueEnum};

use tilezz::dataset::{DEFAULT_TARGET_BLOCK_BYTES, RatDafsa};
use tilezz::enumerate::dfs::STREAM_RAT_LINES;
use tilezz::enumerate::output::{print_stats, rats_gif, run_rat_enum_polylines};
use tilezz::enumerate::prune::{
    install_closure_table_prune, install_modular_prune, install_shadow_prune,
};
use tilezz::enumerate::run_rat_enum_seqs;
use tilezz::enumerate::seed::{dispatch_collect_seed_prefixes, dispatch_enumerate_from_seed};

use tilezz::vis::plotutils::P64;

static VERBOSE: Mutex<bool> = Mutex::new(false);

// --------

#[derive(Copy, Clone, Debug, ValueEnum)]
enum Mode {
    /// Enumerate and render output (GIF)
    Render,
    /// Enumerate only and report elapsed time
    Bench,
    /// Walk the DFS down to `split_depth` (default 3) and print alive
    /// prefixes one per line as "SEED a,b,c", plus any polygon that
    /// closed before reaching that depth as "RAT [...]". Use with
    /// `--seed` to dispatch per-prefix jobs externally and merge.
    ListSeeds,
    /// Enumerate, then write a gzipped `RatDafsa` to the path given
    /// by `-o`. The on-disk format is `tilezz-rat-dafsa`; assigned
    /// external indices follow `(length asc, lex asc)` order. The
    /// length-prefix encoding used internally is described in
    /// `RatDafsa::JSON_SCHEMA_DOC`.
    Dafsa,
    /// Enumerate, then write a blocked (lazy-loadable) `RatDafsa`
    /// asset directory at the path given by `-o`. Produces
    /// `block_index.json` + `blocks/<sha256>.bin` gzipped files
    /// readable by [`tilezz::dataset::LazyRatDafsa`] (or an
    /// async equivalent). Pair with `--target-block-bytes` if the
    /// default is too coarse or too fine for your set size.
    DafsaBlocks,
    /// Stage 1 of the streaming pipeline. Runs the parallel DFS but
    /// writes each worker's closures to per-thread sort-buffer runs
    /// under `-o <dir>/runs/run_tNN_rMM.bin`, instead of accumulating
    /// in an in-memory HashSet. Memory is bounded by the per-thread
    /// buffer (~16 MB/worker default), so very large enumerations
    /// (e.g. ZZ12 n=15+) fit on a commodity workstation. Pair with
    /// `--mode merge` to fold the runs into a single sorted
    /// `unique.bin` + `certificate.json`, then `--mode build` to
    /// produce the blocked `RatDafsa` asset under `<-o dir>/dafsa/`
    /// without materialising the full set in memory.
    Stream,
    /// Stage 2 of the streaming pipeline. K-way merges `<-o
    /// dir>/runs/*.bin` (produced by `--mode stream`) into
    /// `<-o dir>/unique.bin` (deduped, sorted) and writes
    /// `<-o dir>/certificate.json` with the BLAKE3 hash + headline
    /// counts. Doesn't re-run the DFS -- just folds existing run
    /// files. Requires the same `--ring`, `-n`, `--step`,
    /// `--free` flags as the producing `--mode stream` call (they
    /// are recorded in the certificate verbatim).
    Merge,
    /// Stage 3 of the streaming pipeline. Reads `<-o dir>/unique.bin`
    /// (produced by `--mode merge`), streams the records through
    /// `RatDafsa::from_sorted_unique_rats`, and writes the blocked
    /// asset to `<-o dir>/dafsa/` via `RatDafsa::write_blocks`. Pair
    /// with `--target-block-bytes`. Does not run the DFS or
    /// re-merge; it's the streaming-friendly equivalent of `--mode
    /// dafsa-blocks` for inputs too large to fit in memory as a
    /// `Vec<Vec<i8>>`.
    Build,
    /// Re-host an EXISTING dataset to a new host (metadata only, no
    /// recompute). Surgically patches just the host-coordinate fields
    /// (`identifier`, `url`, `distribution.contentUrl`, `sameAs`) in
    /// `<-o dir>/ro-crate-metadata.json` to the `--base-url` / `--doi`
    /// given, leaving the blocks, their recorded sha256s, the
    /// provenance (commit / build time / reproduce recipe), and
    /// `variableMeasured` byte-for-byte unchanged. Use when mirroring a
    /// dataset to Zenodo or otherwise switching where it is served;
    /// pass neither flag to revert to the location-independent form.
    Rehost,
}

#[derive(Parser, Debug)]
#[command(
    version = tilezz::VERSION,
    about = "Enumerate simple cyclotomic matchstick polygons (rats) up to a given perimeter",
    long_about = "\
Enumerate every simple polygon (closed self-avoiding boundary) of\n\
unit-length edges on a cyclotomic ring `ZZn`, with perimeter up to `-n`.\n\
\n\
Output is selected via `--mode` (default: render):\n\
  * render        enumerate and render the polygons as a GIF (`-o file.gif`)\n\
  * bench         enumerate, time, report counts (no -o needed)\n\
  * dafsa         enumerate and write a gzipped DAFSA (`-o file.bin.gz`)\n\
  * dafsa-blocks  same, but as a directory of lazy-loadable blocks\n\
  * stream        stage 1 of the streaming pipeline: write per-thread runs\n\
                  to `<-o dir>/runs/run_tNN_rMM.bin` (bounded memory)\n\
  * merge         stage 2 of the streaming pipeline: k-way merge runs into\n\
                  `<-o dir>/unique.bin` + `certificate.json`\n\
  * build         stage 3 of the streaming pipeline: stream `unique.bin`\n\
                  through a DAFSA builder and write blocks to `<-o dir>/dafsa/`\n\
  * list-seeds    walk DFS to `--split-depth` and print SEED + RAT lines\n\
                  (for multi-host orchestration; see `--seed`)\n\
  * rehost        patch an existing dataset's RO-Crate host fields to a\n\
                  new `--base-url` / `--doi` (no recompute; see -o)\n\
\n\
Performance opts (combine for maximum speedup):\n\
  --reachability-prune          reachability prune, finite + archimedean places; up to 376x\n\
  --closure-table-prune  exact lattice closure-table prune; another 2-5x on top\n\
  --threads N          parallel DFS; near-linear in streaming modes,\n\
                       sub-linear in HashSet modes (set-merge overhead)\n\
  --free               free (= full dihedral reduction) output:\n\
                       one rep per chiral pair (lex-min over rotations and\n\
                       reflections); also accelerates DFS via\n\
                       complement-reflection prune\n\
\n\
For memory at large n: prefer the streaming pipeline (`--mode stream`\n\
then `--mode merge`) over `--mode bench --threads N`. See the file-level\n\
docstring in src/bin/rat_enum.rs for the full memory accounting.\n"
)]
struct Cli {
    /// Cyclotomic ring index n in `ZZn`. Supported:
    /// 4, 6, 8, 10, 12, 16, 20, 24, 32, 60. Required by every
    /// enumerating mode; ignored by `--mode rehost` (metadata-only).
    #[arg(short = 'r', long)]
    ring: Option<u8>,

    /// Maximum boundary perimeter to enumerate up to (inclusive).
    /// Memory and time scale exponentially in `n`; expect each
    /// `+1` to multiply runtime by `~3-10` depending on ring.
    /// Required by every enumerating mode; ignored by `--mode rehost`.
    #[arg(short = 'n', long)]
    max_steps: Option<usize>,

    /// Output mode. See the top-level `--help` for the menu.
    #[arg(long, value_enum, default_value_t = Mode::Render)]
    mode: Mode,

    /// Output filename. Meaning depends on `--mode`:
    ///   * render        path/to/file.gif
    ///   * dafsa         path/to/file.bin.gz
    ///   * dafsa-blocks  path/to/output_dir/ (will be created)
    ///   * stream        path/to/output_dir/ (will be created; runs go in `<dir>/runs/`)
    ///   * merge         path/to/output_dir/ (same one used by `--mode stream`)
    ///   * build         path/to/output_dir/ (same; blocks go in `<dir>/dafsa/`)
    #[arg(short = 'o', long)]
    filename: Option<String>,

    /// Print extra progress / diagnostic chatter.
    #[arg(short, long)]
    verbose: bool,

    /// In Bench mode, write a flamegraph SVG to this path (requires
    /// the `debug` cargo feature).
    #[arg(long)]
    profile: Option<String>,

    /// Use the domino-automaton geometry backend
    /// (`rat_enum::boundary::DominoBoundary`) instead of the `Snake` DFS:
    /// identical tree and results via the same generic `rat_enum_step`,
    /// but self-avoidance is a precomputed table lookup rather than an
    /// exact-arithmetic `intersect`. Orthogonal to `--mode` -- honoured by
    /// every enumerating mode: the in-memory ones (bench, render, dafsa,
    /// dafsa-blocks) run single-threaded; `--mode stream` runs the domino
    /// backend in its parallel workers (they share one prebuilt cell
    /// alphabet). A no-op for modes that don't enumerate.
    #[arg(long)]
    domino: bool,

    /// In Bench mode, print a per-boundary-length breakdown of total /
    /// achiral / rotational-symmetry histogram after enumeration.
    #[arg(long)]
    stats: bool,

    /// Number of worker threads for the DFS.
    ///
    /// `1` (default) runs the original single-threaded path
    /// unchanged. `0` resolves to all available parallelism. Any other
    /// positive value is used as-is, capped at all available.
    #[arg(long, default_value_t = 1)]
    threads: usize,

    /// Restrict the DFS to directions that are multiples of `step`.
    ///
    /// `1` (default) walks every direction in `(-hturn+1)..hturn`.
    /// `step = 2` on ZZ20 walks only even-indexed directions, which
    /// enumerates exactly the ZZ10-equivalent polygons (b=9 vs 19).
    /// Similarly `step = 2` on ZZ24 -> ZZ12 subset, `step = 3` on
    /// ZZ24 -> ZZ8 subset, etc.
    #[arg(long, default_value_t = 1)]
    step: i8,

    /// Free (= full dihedral symmetry reduction) enumeration: outputs
    /// one representative per chiral pair (lex-min over rotations
    /// AND reflections). Faster than the default rotation-canonical
    /// DFS because complement-reflection pruning halves the search
    /// space at the root.
    #[arg(long)]
    free: bool,

    /// After every successful `Snake::add`, replay the entire current
    /// angle prefix in a fresh `Snake::new()` and assert that fresh
    /// snake accepts the same prefix and reaches the same
    /// `is_closed` state. Panics on any disagreement -- traps cases
    /// where the stateful incremental check (post-pop grid state)
    /// admits prefixes that a from-scratch check would reject.
    /// Roughly O(n) extra work per step; expect ~2x slowdown.
    #[arg(long)]
    paranoid: bool,

    /// Enable the reachability prune (finite + archimedean places).
    /// FINITE half: for each modulus `m in {2..=16}` whose state space
    /// `m^phi` fits the cell budget, precomputes the cumulative
    /// reachable mod-m displacement set and rejects any candidate
    /// direction whose post-extension displacement can't reach 0 mod m
    /// in any number of remaining steps (one packed hash lookup per
    /// modulus; `--reachability-moduli` to A/B test). ARCHIMEDEAN half
    /// (shadow-radius): the same `within_radius` reachability bound in
    /// the non-physical conjugate embeddings -- `O(phi)`, no precompute,
    /// and the dominant half on high-`phi` rings (e.g. ZZ32/60) where
    /// the modular budget collapses to `m=2`.
    #[arg(long)]
    reachability_prune: bool,

    /// Comma-separated list of moduli to use with `--reachability-prune`
    /// (default: 2..=16, filtered by ring's state-space budget).
    /// Useful for A/B testing: e.g. `--reachability-moduli 2,3,4,6`
    /// reproduces the original hardcoded set.
    #[arg(long, value_delimiter = ',', num_args = 1..)]
    reachability_moduli: Option<Vec<i64>>,

    /// Enable the closure-table prune: pre-enumerate every simple
    /// open snake up to length L (= `--closure-table-depth`) and
    /// store their (endpoint, facing) keys. During DFS, when the
    /// remaining-after-this-direction count is <= L, the candidate
    /// is pruned iff its required suffix's closure key isn't in
    /// the precomputed set. Strictly stronger than any modular
    /// projection (uses exact lattice + facing info). More memory
    /// and pre-pass cost; per-node cost is one ring mul + one
    /// hash lookup.
    #[arg(long)]
    closure_table_prune: bool,

    /// Suffix-length cap for `--closure-table-prune`. Memory/pre-pass
    /// cost scales as |S_L| ~ c^L (c ~ 5-10 for typical rings);
    /// the prune only fires when `remaining_after <= L`. L=4 was
    /// empirically optimal across ZZ8/12/16 at n=10..15: larger L
    /// finds more skips but the table-build cost dominates the
    /// per-node savings.
    #[arg(long, default_value_t = 4)]
    closure_table_depth: usize,

    /// Print a live progress heartbeat to stderr every N seconds during
    /// `--mode stream` (0 = off). Each line reports seeds dispatched/
    /// retired, closures and branch-attempts per second, the in-flight
    /// recursion-depth spread, and scratch (`runs/`) growth. A per-seed
    /// cost distribution (the load-balance / skew picture) is printed at
    /// the end regardless of this flag.
    #[arg(long, default_value_t = 0)]
    heartbeat: u64,

    /// Target uncompressed bytes per block file when writing the
    /// `--mode dafsa-blocks` asset. The writer closes a block once its
    /// serialised size crosses this threshold (the final block may be
    /// smaller). Default 4 MiB (4194304): fewer blocks means a lazy
    /// lookup crosses fewer of them, so HTTP-served assets pay fewer
    /// sequential block fetches (measured ZZ4 n32: worst-case
    /// blocks/lookup 12 at 1 MiB -> 7 at 4 MiB) at ~the same gzipped
    /// on-disk size; going larger would bloat each fetch and strain
    /// low-bandwidth clients. Reduce (e.g. 8192) for tiny example
    /// assets so a small set still fans out across multiple blocks.
    #[arg(long, default_value_t = DEFAULT_TARGET_BLOCK_BYTES)]
    target_block_bytes: u32,

    /// Skip emission of `ro-crate-metadata.json` and the `schemas/`
    /// directory when writing a `--mode dafsa-blocks` asset. Default
    /// is to write a self-describing RO-Crate 1.2 bundle alongside
    /// the manifest and block files; this flag is the escape hatch
    /// for callers that want only the bare wire format (e.g. an
    /// internal test fixture).
    #[arg(long)]
    no_rocrate: bool,

    /// Optional OEIS A-number this enumeration realises (e.g.
    /// `A316192` for ZZ12 free dihedral). Surfaced into the
    /// `ro-crate-metadata.json` as a `subjectOf` contextual entity
    /// so an archivist can pivot from the asset to the OEIS
    /// sequence. Honoured by the asset-writing modes (`--mode
    /// dafsa-blocks` and the streaming pipeline's `--mode build`).
    #[arg(long)]
    oeis_a_number: Option<String>,

    /// Public base URL where this dataset directory will be hosted
    /// (e.g. the raw.githubusercontent.com or Pages URL); used to set
    /// the RO-Crate distribution.contentUrl and identifier on deployed
    /// assets. Omit for local/test builds (relative URL). In `--mode
    /// rehost` this is the NEW host the dataset is being moved to.
    #[arg(long)]
    base_url: Option<String>,

    /// Minted DOI for this dataset (e.g. `10.5281/zenodo.123` from a
    /// Zenodo deposit). When set, the RO-Crate identifier becomes a DOI
    /// PropertyValue and a resolvable `https://doi.org/<doi>` sameAs is
    /// added. Honoured by the asset-writing modes and by `--mode
    /// rehost`. Omit when the dataset has no DOI.
    #[arg(long)]
    doi: Option<String>,

    /// Resume the DFS from a specific seed prefix (comma-separated
    /// angles like `-5,3,-4`). When set, the DFS skips seed
    /// collection and resumes from this prefix; output is the same
    /// RAT lines as Bench mode. Honours `--threads`. Used together
    /// with `--mode list-seeds` to dispatch per-prefix jobs
    /// externally.
    #[arg(long, value_delimiter = ',', allow_hyphen_values = true, num_args = 1)]
    seed: Option<Vec<i8>>,

    /// DFS splitting depth for `--mode list-seeds` and for the
    /// parallel (`--threads > 1`) seed-collection step. Defaults to
    /// 3 in list-seeds mode (~50-300 seeds for typical n), or to
    /// the auto-picked value otherwise.
    #[arg(long)]
    split_depth: Option<usize>,
}

/// Resolve the `--threads` CLI value to an actual worker count.
/// `0` -> all available; otherwise cap at all available.
fn resolve_n_threads(requested: usize) -> usize {
    let max = tilezz::util::available_workers();
    if requested == 0 {
        max
    } else {
        requested.min(max)
    }
}

fn main() {
    let cli = Cli::parse();
    if cli.verbose {
        let mut verbose = VERBOSE.lock().unwrap();
        *verbose = true;
    }

    let n_threads = resolve_n_threads(cli.threads);

    // `--mode rehost`: pure metadata patch on an existing dataset, no
    // DFS and no ring / -n needed. Rewrites only the host-coordinate
    // fields in the dataset's ro-crate-metadata.json (identifier / url /
    // distribution / sameAs) to the new --base-url / --doi, leaving
    // blocks, sha256s, and provenance untouched. Handled first, before
    // anything reads --ring / --max-steps, so re-hosting a dataset does
    // not require restating its enumeration parameters.
    if matches!(cli.mode, Mode::Rehost) {
        let Some(dir) = cli.filename.as_deref() else {
            eprintln!("--mode rehost requires -o <existing dataset directory>");
            std::process::exit(2);
        };
        let dir = std::path::Path::new(dir);
        match tilezz::dataset::rehost_ro_crate(dir, cli.base_url.as_deref(), cli.doi.as_deref()) {
            Ok(()) => {
                let where_to = match (cli.base_url.as_deref(), cli.doi.as_deref()) {
                    (Some(b), Some(d)) => format!("base_url={b} doi={d}"),
                    (Some(b), None) => format!("base_url={b}"),
                    (None, Some(d)) => format!("doi={d}"),
                    (None, None) => "location-independent (relative) form".to_string(),
                };
                eprintln!(
                    "rehost: patched {}/ro-crate-metadata.json to {where_to}",
                    dir.display()
                );
            }
            Err(e) => {
                eprintln!("--mode rehost failed: {e}");
                std::process::exit(2);
            }
        }
        return;
    }

    // Every remaining mode enumerates, so --ring and --max-steps are
    // required from here on. Resolve them once into locals; the rest of
    // main uses these instead of the Option-typed CLI fields.
    let Some(ring) = cli.ring else {
        eprintln!("--ring is required for every mode except --mode rehost");
        std::process::exit(2);
    };
    let Some(max_steps) = cli.max_steps else {
        eprintln!("-n / --max-steps is required for every mode except --mode rehost");
        std::process::exit(2);
    };

    if cli.reachability_prune {
        // The reachability prune has two complementary halves, both under
        // this one flag: the modular tables (finite places, mod m) and the
        // shadow-radius check (the non-physical archimedean places --
        // extending the always-on physical `within_radius` to all of them).
        // They are the same "can the remaining budget cancel the head"
        // test at different places of the field, so they share a flag.
        install_modular_prune(ring, max_steps, cli.reachability_moduli.as_deref());
        install_shadow_prune(ring);
    }
    if cli.closure_table_prune {
        install_closure_table_prune(ring, cli.closure_table_depth);
    }
    // `--mode list-seeds`: walk the DFS down to split_depth, print
    // alive prefixes as `SEED a,b,c` lines and any already-closed
    // polygons as `RAT [...]` lines, then exit. The split_depth
    // defaults to 3 (typically ~50-300 seeds at usable n).
    if matches!(cli.mode, Mode::ListSeeds) {
        let split_depth = cli.split_depth.unwrap_or(3);
        let (closed, seeds) =
            dispatch_collect_seed_prefixes(ring, max_steps, cli.step, split_depth, cli.free);
        for prefix in &seeds {
            let s = prefix
                .iter()
                .map(|a| a.to_string())
                .collect::<Vec<_>>()
                .join(",");
            println!("SEED {s}");
        }
        // Polygons that closed before reaching split_depth (typically
        // perimeter-3 only, e.g. the triangle at ZZ12). These would
        // be missed if the orchestrator only ran the SEED jobs.
        for seq in &closed {
            println!("RAT {seq:?}");
        }
        eprintln!(
            "list-seeds: {} alive prefixes at depth {}, {} polygons closed before split",
            seeds.len(),
            split_depth,
            closed.len(),
        );
        return;
    }

    // `--seed <prefix>`: skip seed collection, resume DFS from the
    // given prefix, print RAT lines. With `--threads 1` (default and
    // recommended), this is one work unit; the orchestrator runs
    // multiple `--seed` jobs as separate processes to use more cores.
    // With `--threads N>1`, the seed's subtree is itself sub-split
    // for in-process parallelism -- useful when an orchestrator
    // gives one big process at a time, but per-process memory is
    // ~N x higher because this path still uses the HashSet-backed
    // `enumerate_from_seed` (i.e. it's bench-shaped, not stream-
    // shaped). For memory-bounded large-n enumeration, prefer
    // `--mode stream` instead, where multi-threading within one
    // process and multi-process orchestration have ~the same
    // memory profile (no per-thread result accumulation to
    // multiply).
    if let Some(seed) = cli.seed.as_deref() {
        let t0 = Instant::now();
        let rats = dispatch_enumerate_from_seed(
            ring,
            max_steps,
            cli.step,
            seed,
            n_threads,
            cli.free,
            cli.paranoid,
        );
        let dt = t0.elapsed();
        for seq in &rats {
            println!("RAT {seq:?}");
        }
        eprintln!("seed {:?}: {} unique rats in {dt:?}", seed, rats.len());
        return;
    }

    match cli.mode {
        Mode::ListSeeds => unreachable!("handled above"),
        Mode::Rehost => unreachable!("handled above"),
        Mode::Build => {
            let Some(out_dir) = cli.filename.as_deref() else {
                eprintln!("--mode build requires -o <output directory>");
                std::process::exit(2);
            };
            let out_dir = std::path::Path::new(out_dir);
            let unique_path = out_dir.join(tilezz::enumerate::stream::UNIQUE_FILENAME);
            if !unique_path.exists() {
                eprintln!(
                    "--mode build: {} not found; run `--mode merge` first",
                    unique_path.display()
                );
                std::process::exit(2);
            }

            let t0 = Instant::now();
            // Stream records straight into the streaming DAFSA
            // builder. Peak RSS scales with the in-progress
            // automaton, not with the input set.
            let records = tilezz::enumerate::stream::read_unique_records(&unique_path)
                .expect("open unique.bin")
                .map(|r| r.expect("read unique record"));
            let dafsa = RatDafsa::from_sorted_unique_rats(records);
            let t_build = t0.elapsed();
            eprintln!(
                "build: streamed {} rats into RatDafsa in {:?}",
                dafsa.len(),
                t_build
            );

            let blocks_dir = out_dir.join("dafsa");
            std::fs::create_dir_all(&blocks_dir).expect("create dafsa/");
            let t1 = Instant::now();
            dafsa
                .write_blocks(&blocks_dir, cli.target_block_bytes)
                .expect("write_blocks");

            // Same self-describing bundle as Mode::DafsaBlocks, but the
            // reproduction recipe records the streaming pipeline's
            // three-stage shape instead of a single --mode dafsa-blocks
            // invocation.
            if !cli.no_rocrate {
                use tilezz::dataset::{
                    AssetParams, ProducedVia, SequenceCounts, write_archival_extras, write_ro_crate,
                };
                let params = AssetParams {
                    ring,
                    max_steps,
                    step: cli.step,
                    free: cli.free,
                    target_block_bytes: cli.target_block_bytes,
                    n_sequences: dafsa.len() as u64,
                    oeis_a_number: cli.oeis_a_number.as_deref(),
                    produced_via: ProducedVia::StreamingPipeline,
                };
                let counts = SequenceCounts::from_rats(dafsa.iter());
                write_archival_extras(&blocks_dir, &params).expect("write archival extras");
                write_ro_crate(
                    &blocks_dir,
                    &params,
                    &counts,
                    cli.base_url.as_deref(),
                    cli.doi.as_deref(),
                )
                .expect("write ro-crate-metadata.json");
            }

            fn dir_size_recursive(p: &std::path::Path) -> u64 {
                let mut total = 0u64;
                if let Ok(rd) = std::fs::read_dir(p) {
                    for entry in rd.flatten() {
                        let path = entry.path();
                        if path.is_dir() {
                            total += dir_size_recursive(&path);
                        } else if let Ok(m) = entry.metadata() {
                            total += m.len();
                        }
                    }
                }
                total
            }
            let total_bytes = dir_size_recursive(&blocks_dir);
            eprintln!(
                "build: wrote {} ({} bytes) in {:?}",
                blocks_dir.display(),
                total_bytes,
                t1.elapsed()
            );
        }
        Mode::Merge => {
            let Some(out_dir) = cli.filename.as_deref() else {
                eprintln!("--mode merge requires -o <output directory>");
                std::process::exit(2);
            };
            let t0 = Instant::now();
            let cert = tilezz::enumerate::stream::merge_runs(
                std::path::Path::new(out_dir),
                ring,
                max_steps,
                cli.step,
                cli.free,
            )
            .expect("merge_runs");
            let dt = t0.elapsed();
            println!(
                "merge: ring={} step={} max_steps={} -> {} unique rats in {:?}",
                ring, cli.step, max_steps, cert.unique_records, dt
            );
        }
        Mode::Stream => {
            let Some(out_dir) = cli.filename.as_deref() else {
                eprintln!("--mode stream requires -o <output directory>");
                std::process::exit(2);
            };
            // Stage 1 is artifact-producing; don't double up by also
            // dumping RAT lines on stdout.
            STREAM_RAT_LINES.store(false, std::sync::atomic::Ordering::Relaxed);

            let t0 = Instant::now();
            let stats = tilezz::enumerate::stream::stream_enum_dispatch(
                ring,
                max_steps,
                cli.step,
                n_threads,
                cli.free,
                cli.paranoid,
                cli.domino,
                std::path::Path::new(out_dir),
                cli.heartbeat,
            )
            .expect("stream_enum_dispatch");
            let dt = t0.elapsed();
            println!(
                "stream: ring={} step={} max_steps={} -> wrote runs to {} in {:?}",
                ring, cli.step, max_steps, out_dir, dt
            );
            println!("{stats}");
        }
        Mode::Dafsa => {
            let Some(filename) = cli.filename.as_deref() else {
                eprintln!("--mode dafsa requires -o <output path>");
                std::process::exit(2);
            };

            // The DFS streams each newly-found rat to stdout by
            // default (for `--seed` / `--mode render`); in dafsa mode
            // the artifact is the binary file at `-o`, so silence the
            // streaming lines before enumerating.
            STREAM_RAT_LINES.store(false, std::sync::atomic::Ordering::Relaxed);

            let t0 = Instant::now();
            let (rats, _stats) = run_rat_enum_seqs(
                ring,
                max_steps,
                cli.step,
                n_threads,
                cli.free,
                cli.paranoid,
                cli.domino,
            );
            eprintln!("enumerated {} rats in {:?}", rats.len(), t0.elapsed());

            // `RatDafsa::from_rats` handles the (length, lex) sort,
            // dedup, and length-prefix encoding internally; the
            // resulting external index of each rat is its position in
            // the (length, lex)-ordered sequence.
            let t1 = Instant::now();
            let dafsa = RatDafsa::from_rats(rats.iter().map(|r| r.as_slice()));
            eprintln!(
                "built RatDafsa ({} entries) in {:?}",
                dafsa.len(),
                t1.elapsed()
            );

            let t2 = Instant::now();
            let file = File::create(filename).expect("create output file");
            dafsa
                .write_json_gz(BufWriter::new(file))
                .expect("write gzipped RatDafsa");
            let bytes = std::fs::metadata(filename).map(|m| m.len()).unwrap_or(0);
            eprintln!("wrote {filename} ({bytes} bytes) in {:?}", t2.elapsed());

            if cli.stats {
                print_stats(&rats);
            }
        }
        Mode::DafsaBlocks => {
            let Some(dir) = cli.filename.as_deref() else {
                eprintln!("--mode dafsa-blocks requires -o <output directory>");
                std::process::exit(2);
            };

            STREAM_RAT_LINES.store(false, std::sync::atomic::Ordering::Relaxed);

            let t0 = Instant::now();
            let (rats, _stats) = run_rat_enum_seqs(
                ring,
                max_steps,
                cli.step,
                n_threads,
                cli.free,
                cli.paranoid,
                cli.domino,
            );
            eprintln!("enumerated {} rats in {:?}", rats.len(), t0.elapsed());

            let t1 = Instant::now();
            let dafsa = RatDafsa::from_rats(rats.iter().map(|r| r.as_slice()));
            eprintln!(
                "built RatDafsa ({} entries) in {:?}",
                dafsa.len(),
                t1.elapsed()
            );

            let t2 = Instant::now();
            let path = std::path::Path::new(dir);
            std::fs::create_dir_all(path).expect("create output dir");
            dafsa
                .write_blocks(path, cli.target_block_bytes)
                .expect("write blocked RatDafsa");

            // Self-describing RO-Crate bundle: schemas/ + tools/decode.py
            // + REPRODUCE.md + ro-crate-metadata.json. Skipped under
            // --no-rocrate (e.g. internal test fixtures that want only
            // the bare wire format).
            if !cli.no_rocrate {
                use tilezz::dataset::{
                    AssetParams, ProducedVia, SequenceCounts, write_archival_extras, write_ro_crate,
                };
                let params = AssetParams {
                    ring,
                    max_steps,
                    step: cli.step,
                    free: cli.free,
                    target_block_bytes: cli.target_block_bytes,
                    n_sequences: dafsa.len() as u64,
                    oeis_a_number: cli.oeis_a_number.as_deref(),
                    produced_via: ProducedVia::InMemory,
                };
                let counts = SequenceCounts::from_rats(dafsa.iter());
                write_archival_extras(path, &params).expect("write archival extras");
                write_ro_crate(
                    path,
                    &params,
                    &counts,
                    cli.base_url.as_deref(),
                    cli.doi.as_deref(),
                )
                .expect("write ro-crate-metadata.json");
            }

            // Walk the directory tree so the total includes blocks/
            // and schemas/ subdir contents, not just top-level files.
            fn dir_size(p: &std::path::Path) -> u64 {
                let mut total = 0u64;
                if let Ok(rd) = std::fs::read_dir(p) {
                    for entry in rd.flatten() {
                        let path = entry.path();
                        if path.is_dir() {
                            total += dir_size(&path);
                        } else if let Ok(m) = entry.metadata() {
                            total += m.len();
                        }
                    }
                }
                total
            }
            let total_bytes = dir_size(path);
            let extras = if cli.no_rocrate {
                ""
            } else {
                " + schemas + ro-crate-metadata"
            };
            eprintln!(
                "wrote {dir}/ ({total_bytes} bytes across manifest + blocks{extras}) in {:?}",
                t2.elapsed()
            );

            if cli.stats {
                print_stats(&rats);
            }
        }
        Mode::Bench => {
            // Don't stream RAT lines: this mode times the DFS, and the
            // per-rat printing would land inside the timed region.
            STREAM_RAT_LINES.store(false, std::sync::atomic::Ordering::Relaxed);
            let profile = tilezz::util::profile::ProfileGuard::start(cli.profile.as_deref());

            let t0 = Instant::now();
            let (rats, stats) = run_rat_enum_seqs(
                ring,
                max_steps,
                cli.step,
                n_threads,
                cli.free,
                cli.paranoid,
                cli.domino,
            );
            let dt = t0.elapsed();

            // Use the result so it can't be trivially optimized away.
            let total_boundary_len: usize = rats.iter().map(|s| s.len()).sum();

            println!(
                "benchmark: backend={} ring={} step={} max_steps={} -> {} unique rats (total boundary len={}) in {:?}",
                if cli.domino { "automaton" } else { "snake" },
                ring,
                cli.step,
                max_steps,
                rats.len(),
                total_boundary_len,
                dt
            );

            println!("{stats}");

            profile.finish();

            if cli.stats {
                print_stats(&rats);
            }
        }
        Mode::Render => {
            let rats: Vec<Vec<P64>> = run_rat_enum_polylines(
                ring,
                max_steps,
                cli.step,
                n_threads,
                cli.free,
                cli.paranoid,
                cli.domino,
            );

            let Some(filename) = cli.filename else {
                return;
            };

            let gif_bytes = rats_gif(&rats, 500, 500);
            std::fs::write(&filename, gif_bytes).expect("write GIF");
            println!("wrote {filename}");
        }
    }
}