delaunay 0.8.0

D-dimensional Delaunay triangulations and convex hulls in Rust, with exact predicates, deterministic degeneracy handling, explicit topology validation, and bistellar flips for finite point sets.
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
# Rust Development Guidelines Reference

Rust coding conventions for this repository.

Agents must follow these rules when modifying or adding Rust code.

---

## Contents

- [Core Principles]#core-principles
- [Safety]#safety
- [Dimension Generic Architecture]#dimension-generic-architecture
- [Numeric Conversions]#numeric-conversions
- [Borrowing and Ownership]#borrowing-and-ownership
- [Error Handling]#error-handling
- [Fluent Workflow APIs]#fluent-workflow-apis
- [Constructor Naming]#constructor-naming
- [Panic Policy]#panic-policy
- [Error Types]#error-types
  - [Orthogonal variants]#orthogonal-variants
  - [Struct‑with‑named‑fields throughout]#structwithnamedfields-throughout
  - [Preserve typed sources — no boxing, no `dyn Error`]#preserve-typed-sources--no-boxing-no-dyn-error
  - [Do not stringify; carry typed context instead]#do-not-stringify-carry-typed-context-instead
  - [Derive `Clone, Debug, Error, PartialEq, Eq`]#derive-clone-debug-error-partialeq-eq
- [Naming and Paths]#naming-and-paths
- [Imports]#imports
- [Module Layout]#module-layout
- [Prelude Design]#prelude-design
- [Documentation]#documentation
- [Integration Tests]#integration-tests
- [Testing Expectations]#testing-expectations
- [Performance]#performance
- [External Dependencies]#external-dependencies
- [Toolchain and Package Boundary]#toolchain-and-package-boundary
- [Formatting and Lints]#formatting-and-lints
- [API Stability]#api-stability
- [Logging and Diagnostics]#logging-and-diagnostics
- [Preferred Patch Style]#preferred-patch-style

---

## Core Principles

This project is a **scientific computational geometry library**.

Key goals:

- Correctness
- Predictable performance
- API stability
- Zero unsafe code
- Dimension-generic architecture

All design decisions should prioritize these goals.

---

## Safety

Unsafe Rust is forbidden.

The crate enforces:

```rust
#![forbid(unsafe_code)]
```

Agents must never introduce:

- `unsafe`
- `unsafe fn`
- `unsafe impl`
- `unsafe` blocks

---

## Dimension Generic Architecture

The library is generic over dimension using const generics:

```rust
const D: usize
```

Code must remain compatible with:

- 2D
- 3D
- 4D
- 5D

Avoid hard‑coding dimension assumptions unless they are explicitly isolated.

Prefer patterns like:

```rust
struct Point<const D: usize> {
    coords: [f64; D],
}
```

Algorithms should operate generically over `D` whenever practical.

---

## Numeric Conversions

Avoid unchecked numeric casts in geometry, topology, tests, and benchmarks when
precision or range can matter.

Prefer repository helpers from `crate::geometry::util`, for example:

- `safe_usize_to_scalar::<T>(value)`
- `safe_scalar_to_f64(value)`
- `safe_scalar_from_f64::<T>(value)`
- `safe_coords_to_f64(coords)`
- `safe_coords_from_f64::<T, D>(coords)`

Do not silence `clippy::cast_precision_loss` with `#[expect(...)]` simply
because the current values are small. Use a safe conversion helper and handle
or justify the `Result` at the call site. A lint expectation is appropriate only
when no safe conversion applies and the invariant is documented in the code.

Avoid fallback conversions such as `unwrap_or(f64::NAN)`,
`unwrap_or(f64::INFINITY)`, or silently clamping failed conversions. These hide
the numerical state that geometric predicates and validation layers need in
order to fail explicitly.

---

## Borrowing and Ownership

Prefer **borrowing APIs** whenever possible.

### Function arguments

Prefer:

```rust
fn foo(points: &[Point<D>])
```

Instead of:

```rust
fn foo(points: Vec<Point<D>>)
```

### Return values

Prefer borrowed results:

```rust
fn vertex(&self, key: VertexKey) -> Option<&Vertex<D>>
```

Avoid unnecessary allocations.

Public APIs should also avoid unnecessary cloning. Prefer returning references
or iterators over internal data instead of cloning structures.

Avoid patterns like:

```rust
fn vertices(&self) -> Vec<Vertex<D>> {
    self.vertices.clone()
}
```

Prefer borrowed views instead:

```rust
fn vertices(&self) -> &[Vertex<D>] {
    &self.vertices
}
```

Cloning large structures in public APIs can introduce hidden performance
costs and should only be done when ownership transfer is required.

Only return owned values (`Vec`, `String`, etc.) when necessary.

### Lifetime-bound views and query helpers

Use Rust lifetimes to encode same-owner freshness whenever an API consults a
data structure or derived view. If a function returns an iterator, view, or
borrowed result over canonical storage, its signature should tie that result to
the lifetime of the storage it reads instead of relying only on runtime checks.

Prefer:

```rust
fn incident_simplices<'tds>(
    &'tds self,
    index: &'tds IncidenceView<'tds>,
) -> impl Iterator<Item = SimplexKey> + 'tds
```

or, when the returned iterator only borrows a derived index whose internal data
borrows the owner:

```rust
fn indexed_edges<'idx, 'tds>(
    index: &'idx EdgeIndex<'tds>,
) -> impl Iterator<Item = EdgeKey> + 'idx
```

Prefer first-class borrowed views such as `IncidenceView<'tds>`,
`EdgeIndex<'tds>`, `SimplexNeighborIndex<'tds>`, and composite
`TriangulationAdjacency<'tds>` when a caller should build derived traversal
state once and query it many times. The view should own only the data it needs
and either borrow canonical relations for `'tds` or carry a lifetime tie to the
source snapshot for derived maps, so mutation through the same owner is
impossible while the view is alive.

Names should match ownership. A `*View` type or a method described as returning
views must borrow the canonical owner, or return values lifetime-bound to that
owner, so the view cannot outlive the data it observes. Detached, copyable
runtime references should be named `*Handle` or `*Key` instead, and APIs that
turn handles back into views must revalidate the handle against a live owner at
the conversion boundary. For example, `ConvexHull::try_facets(triangulation)`
returns borrowed `FacetView<'_>` values, while `ConvexHull::facet_handles()`
exposes the stored `FacetHandle`s explicitly.

Borrowed slices over canonical topology storage follow the same convention:
return `&[Key]` when the slice lives in the owner and the caller should not keep
it across mutation. For example, `Tds::simplex_vertices(simplex_key)` validates
the relation and lends the simplex's stored `&[VertexKey]`.

Algorithm implementations should use borrowed views for read-only observation,
classification, and validation phases. Mutation APIs that change canonical
topology should take `&mut Tds`/`&mut Triangulation` directly, or expose a guard
that holds that mutable borrow for the whole mutation or rollback window. This
ties existence and aliasing to the real owner: missing topology fails at view or
guard construction, and Rust prevents mutation while immutable views remain
live. Inside the mutable scope, collapse short-lived views into validated
`*Handle`/`*Key` commit identifiers before mutating; a live view must not span a
topology mutation.

For failure-atomic topology mutation windows, prefer scoped rollback guards over
loose `(snapshot, restore)` pairs. Use the TDS rollback primitives in
`core::tds::rollback` for free functions that already own a `&mut Tds`, and use
`TriangulationRollbackTransaction` from `core::rollback` for `Triangulation`
methods that need to call back into `self` during the rollback window. Both
compose through the same TDS snapshot primitive, restore on drop unless
committed explicitly, and use rollback-preserving clone semantics for retries.
Higher-level
`DelaunayTriangulation` operations must use the Delaunay-level rollback guard
when they also mutate insertion hints, spatial indexes, or repair bookkeeping;
the guard must restore or intentionally invalidate that auxiliary state
alongside the TDS. Do not wrap only the TDS when owner-coupled state can change.
Issue #364 completed the rollback-infrastructure audit; the separate
`remove_vertex` orientation-correctness work was resolved in #448.

Detached trial/scratch workspaces are a separate pattern: they may use
`clone_for_rollback`/`clone_from_for_rollback` directly when the canonical owner
is not mutated until the detached trial has validated and is swapped into place.
Examples include flip trial workspaces and copy-on-success cleanup operations.

Keep runtime identity or generation checks for detached handles, separately
supplied indexes, serialization boundaries, and tests that intentionally corrupt
metadata. Those checks complement lifetimes at API boundaries where Rust cannot
prove that two borrowed values came from the same owner.

---

## Error Handling

Public APIs must **not panic**.

Use explicit error propagation.

### Fallible public functions

Return `Result`:

```rust
pub fn insert_vertex(...) -> Result<VertexKey, InsertError>
```

### Lookup functions

Return `Option`:

```rust
pub fn vertex(&self, key: VertexKey) -> Option<&Vertex<D>>
```

### Infallible APIs

These should return values directly:

Infallible functions **must not return `Result`**.
If a function cannot fail under normal operation, it should return its value
directly rather than wrapping it in `Result`. Returning `Result` from
infallible APIs is considered unidiomatic and unnecessarily complicates
callers.

- `len()`
- `is_empty()`
- iterators
- accessors
- builder setters

Example:

```rust
pub fn len(&self) -> usize
```

Examples of infallible APIs include:

- accessors (`len`, `dimension`, `capacity`)
- iterators and views
- builder setters
- simple queries over internal state

If a function may fail due to invalid input or algorithmic conditions, it
should return `Result`. If the value may or may not exist (e.g. lookup by key),
return `Option`.

Do not introduce artificial error types simply to satisfy a `Result` return type.

### Builder pattern

Builder setters return `Self`.

Errors occur in `build()`.

Example:

```rust
builder
    .with_capacity(100)
    .with_seed(seed)
    .build()?;
```

---

## Fluent Workflow APIs

Fluent APIs are a reviewed design preference for public workflows, not a
repository-wide requirement. Prefer staged method chains when the operation
naturally proceeds through configuration, proposal, transaction, dry-run,
commit, execution, or report phases.

Good fluent APIs make the valid sequence obvious and keep fallibility visible:

```rust
let result = owner
    .propose_change(raw_request)?
    .attempt_on(&mut owner)?;
```

Use fluent stages when they preserve useful evidence, such as a builder that
stores validated options, a proposal that carries owner/generation provenance,
or a transaction guard that owns rollback state. Coordinate this with
parse-don't-validate design: once raw input has been parsed into a
proof-bearing value, later stages should consume or borrow that value rather
than reaccepting the raw input.

Keep mutation explicit at the terminal method. Prefer names such as `build`,
`attempt_on`, `apply_to`, `commit`, `execute`, or `finish` when that method is
the point where side effects happen. Public samples should not hide mutation in
closures such as `and_then`, `map`, `inspect`, or `for_each` when a named stage
would be clearer.

Do not force fluent style onto accessors, iterators, simple queries, passive
reports, primitive/expert APIs, standard trait implementations, or one-step
operations with no meaningful intermediate state. Keep non-fluent functions
when they provide real orthogonality, such as trait dispatch hooks or low-level
primitive operations; remove or hide them when they only duplicate the fluent
workflow and broaden public surface without adding capability.

---

## Constructor Naming

Constructor names must show where raw input is parsed into proof-bearing domain
types and where already-validated values are merely assembled.

Use fallible names for raw or invariant-bearing input:

- `try_new*` is the default smart-constructor family for raw values becoming a
  proof-bearing domain type.
- `try_from_*`, `TryFrom`, and clearly named `parse` methods are appropriate
  when the source shape matters, especially conversions from another
  representation, deserialized snapshot data, or textual/raw DTO input. Prefer
  these names over owned `from_str` constructors so fallibility remains visible
  in the repository's constructor taxonomy.
- `try_<variant>` is appropriate for fallible enum variant constructors, such as
  `DedupPolicy::try_epsilon`, when the variant name is the clearest API.
- `try_<builder_option>` is appropriate for fallible builder setters, such as
  `DelaunayTriangulationBuilder::try_toroidal`, when the builder remains an
  intermediate state and final construction still happens at `build`.
- All of these names parse caller input and reject invalid values before storage.
- Raw numeric coordinates, slotmap keys, facet indexes, dimensions, UUIDs,
  explicit connectivity, deserialized snapshots, and topology data are
  invariant-bearing input unless a narrower validated type already carries the
  proof.
- The canonical pattern is `Point::try_new`, `Vertex::try_new`, and
  `FacetHandle::try_new`: validate the raw values, then store only values whose
  invariants have been proved.

Use `from_validated*` only for infallible construction from proof-bearing input:

- `from_validated*` means validation evidence already exists at the call site.
- These functions should be private by default. Use `pub(crate)` only when a
  non-test sibling module needs the trusted path after proving the invariant.
  Do not expose `from_validated*` as public API.
- Keep trusted constructors scarce. Prefer one `from_validated*` constructor
  that accepts all already-proved state (for example optional payload data) over
  parallel variants such as `from_validated_*_with_data`.
- The pattern in `FacetHandle::try_new` followed by
  `FacetHandle::from_validated` is the preferred shape for internal helpers.

Intentional idiomatic exceptions are allowed when no raw invalidable state is
being parsed:

- Zero-state strategies and markers may use `new`, such as geometry kernels and
  simple topology-space marker values.
- Empty containers and empty triangulations may use `empty`, `new_empty`, or
  `with_empty_*` because no user geometry or topology is accepted.
- Builder creation may use `Builder::new` when validation is explicitly deferred
  to `build`; fallible builder setters must use descriptive `try_*` names, while
  infallible builder setters keep `with_*` or domain-specific names and return
  `Self`.
- Configuration and statistics types may derive or implement `Default` when the
  default value is valid and documented as a policy choice or accumulator state.
- `from_*` is acceptable for passive report/view extraction or infallible
  standard conversions that cannot fail for representable input. Trusted
  construction from proof-bearing input should use `from_validated*` internally.

Current migration targets for API-normalization work:

- Public Delaunay construction examples should teach
  `DelaunayTriangulationBuilder::new(&vertices).build()?` and its fluent
  option setters/terminal variants as the canonical default-kernel workflow,
  with `DelaunayTriangulation::builder(&vertices)` acceptable only as a terse
  builder alias in tests and benchmarks. Public examples must not discard a
  successfully constructed triangulation with an underscore-prefixed binding.
  End-to-end construction examples with no more specific follow-on operation
  should retain the result and finish with `dt.validate()?`; examples teaching
  another API should use the result for that operation instead of adding a
  redundant validation call mechanically. Do not add local helpers whose whole
  purpose is hiding `DelaunayTriangulation::builder(...).build()` or the
  equivalent `DelaunayTriangulationBuilder::new(...).build()` chain; such
  helpers mask API friction instead of testing the canonical fluent workflow.
  The legacy `DelaunayTriangulation::try_new*` and `try_with_*` wrappers are not
  public API and should not exist, even as hidden compatibility shims. Use the builder
  terminals (`build`, `build_with_statistics`, `build_with_kernel`, and
  `build_with_kernel_and_statistics`) at call sites so options, topology
  expectations, statistics, and kernels remain visible in domain order.
  Shared implementation hooks should stay crate-private, named as builder
  backends, and unreachable from downstream callers. Infallible empty constructors
  remain `empty` and `with_empty_*` because they accept no user geometry or topology.
- `DelaunayTriangulationBuilder::try_from_vertices_and_simplices*` validates
  explicit simplex specs before storing them in a private proof-bearing wrapper.
  Full TDS/topology/Delaunay validation still happens at `build`, where the
  assembled triangulation exists.
- `ConvexHull::try_from_triangulation` is the fallible hull-snapshot
  constructor. Reserve `from_*` for infallible conversions from proof-bearing
  input or passive view/report extraction.
- Broad public `from_*` helpers should be reviewed case by case. Keep them when
  they consume proof-bearing inputs and cannot fail; rename to `try_from_*` when
  they parse raw invalidable state.

Semgrep guardrails for constructor names should stay narrow and repo-specific.
They enforce that fallible constructor definitions do not use misleading `new`
or `from_*` names, and they protect established public parse boundaries such as
`DelaunayTriangulation` and `ConvexHull`. Do not make the rules require every
fallible boundary to be named `try_new*`; descriptive `try_*` names are allowed
for builder setters and enum variant constructors when they better describe the
operation.
Do not add `from_unchecked_*` constructors; use an explicit candidate type for
temporarily assembled state, then consume validation proof before converting to
the final domain type. Other infallible `from_*` names remain acceptable only
for total conversions, passive report/view extraction, or proof-bearing input.

### Vertex construction in public samples

Prefer `vertex!` for user-facing vertex construction examples. This includes
`README.md`, active workflow/design docs, crate-level examples, doctests,
integration-style examples under `examples/`, and benchmarks where vertex
construction is incidental setup. Integration tests should follow the same
default when they exercise a higher-level workflow such as Pachner moves,
flips, insertion, repair, or triangulation construction rather than vertex
construction itself.

Use the direct constructors only when they are the subject of the example:

- API docs for `Vertex::try_new`, `Vertex::try_new_with_data`, and related
  constructor semantics.
- Tests that specifically exercise constructor behavior, type inference, error
  propagation, coordinate parsing, UUID handling, or vertex-data storage.
- Explanatory text that compares `vertex!` with the constructor it expands to.
- Internal invariant tests where direct constructor calls make the tested
  boundary clearer than macro syntax.

The public sample default should look like:

```rust
let vertex = vertex![0.0, 1.0]?;
let labeled: Vertex<&str, 2> = vertex![0.0, 1.0; data = "boundary"]?;
```

Keep `Vertex::try_new` and `Vertex::try_new_with_data` visible in their own
rustdocs so users can still see the fallible smart constructors and the typed
errors that the macro preserves.

---

## Panic Policy

Panics should be avoided in library code.

User-facing Rust surfaces must also avoid panic-based examples. Do not use
unwrap or expect calls in committed examples, benchmarks, Markdown Rust blocks,
or doctests. These artifacts are copied by users and should model typed error
propagation with `?`, local `thiserror` enums, or crate error types. Reserve
unwrap and expect calls for unit tests and test-only fixtures, where a panic
clearly reports a broken test assumption.

Acceptable panic situations:

- internal invariants violated
- unreachable logic errors

Do not use `debug_assert!`, `debug_assert_eq!`, or `debug_assert_ne!` in
production source. Debug-only assertions disappear in release builds, so they
cannot protect library invariants or serve as parse-don't-validate boundaries.
Encode the invariant in a type, return a typed error, or cover the assumption
with tests instead.

Prefer returning:

- `Result`
- `Option`

instead of panicking.

---

## Error Types

Errors should be defined **within the module where they are used**.

Avoid large centralized error enums.

Example:

```rust
#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum InsertError {
    #[error("duplicate vertex")]
    DuplicateVertex,
}
```

The sub‑sections below spell out the conventions that keep error values
**debuggable, composable, and stable**. They apply to every new error enum
and to edits of existing ones.

### Orthogonal variants

Every variant represents a **distinct failure mode**. Two variants must not
overlap in meaning: if a caller can't decide which one to match on, the
taxonomy is wrong.

When the same underlying condition occurs in two different contexts
(e.g. primary failure vs. failure during fallback), model it with
**separate variants that each carry the full typed context**, not with a
single variant and a free‑form `context: String` field.

Good:

```rust
pub enum DelaunayizeError {
    TopologyRepairFailed {
        source: PlManifoldRepairError,
    },
    TopologyRepairFailedWithRebuild {
        source: PlManifoldRepairError,
        rebuild_error: DelaunayTriangulationConstructionError,
    },
    DelaunayRepairFailed {
        source: DelaunayRepairError,
    },
    DelaunayRepairFailedWithRebuild {
        source: DelaunayRepairError,
        rebuild_error: DelaunayTriangulationConstructionError,
    },
}
```

Each pair `Failed` / `FailedWithRebuild` is **orthogonal**: the caller
always knows whether a fallback was attempted, and if so which specific
rebuild error was produced.

### Struct‑with‑named‑fields throughout

Prefer **struct variants with named fields** over positional (tuple) variants,
even for single‑field carriers. Named fields:

- document the semantics of each payload at the declaration site,
- keep `Display` format strings readable (`{source}`, `{rebuild_error}`),
- let downstream code pattern‑match by field name without caring about
  positional order,
- remain additive: adding a new field is a compile‑error surface that
  forces callers to consider it.

Prefer:

```rust
#[error("Invalid facet index {index} for simplex with {facet_count} facets")]
InvalidFacetIndex {
    index: u8,
    facet_count: usize,
},
```

Avoid:

```rust
#[error("Invalid facet index {0} for simplex with {1} facets")]
InvalidFacetIndex(u8, usize),
```

### Preserve typed sources — no boxing, no `dyn Error`

Source and "secondary" errors must be stored **by value as typed enums**.
Do not erase them behind dynamic error objects, `anyhow::Error`, or
`message: String` fields. The whole point of the taxonomy is that consumers
can pattern-match the full structured error, while [`Error::source`] exposes
whichever field is annotated as the primary source.

- Use `#[source]` (and `#[from]` where the conversion is unambiguous) on
  the typed field so `thiserror` wires up the source chain.
- Use `Box<T>` only when the **typed** payload would make the enum
  unbalanced in size (e.g. `NonConvergent` carries a fat diagnostics
  struct); the inner type is still fully typed.
- Never replace a typed error with a `String` just because the enum lived
  in a different crate — that erases variant and source information.

```rust
// Good: typed rebuild error preserved by value; primary source chain intact.
TopologyRepairFailedWithRebuild {
    #[source]
    source: PlManifoldRepairError,
    rebuild_error: DelaunayTriangulationConstructionError,
},
```

```rust
// Bad: stringification erases the typed variant.
TopologyRepairFailedWithRebuild {
    source: PlManifoldRepairError,
    rebuild_message: String,
},
```

### Do not stringify; carry typed context instead

Free‑form `message: String` fields are only acceptable when the context is
genuinely unstructured prose (rare). In practice, **most** "context" is
structured — indices, counts, keys, UUIDs, other enums — and belongs in
named fields of a struct variant.

Prefer:

```rust
#[error("Ridge indices ({omit_a}, {omit_b}) out of bounds for simplex {simplex_key:?} with {vertex_count} vertices")]
InvalidRidgeIndex {
    simplex_key: SimplexKey,
    omit_a: u8,
    omit_b: u8,
    vertex_count: usize,
},
```

Avoid:

```rust
#[error("Ridge indices out of bounds: {message}")]
InvalidRidgeIndex {
    message: String,
},
```

Structured payloads support:

- test assertions via `assert_eq!` / `matches!` without string parsing,
- diagnostic tools that filter or aggregate by field,
- localization and richer `Display` implementations without rewriting
  call‑sites.

### Derive `Clone, Debug, Error, PartialEq, Eq`

All error enums should derive the standard set:

```rust
#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum FooError { ... }
```

- `Clone` — lets callers attach the error to multiple diagnostics paths
  and lets tests construct expected values once and compare them.
- `Debug` — required for `Error`.
- `thiserror::Error` — wires up `Display` and `source()`.
- `PartialEq, Eq` — deriveable whenever all payload types are `Eq`
  (integers, strings, UUIDs, keys, other `Eq` enums, `Arc<T>` /
  `Box<T>` where `T: Eq`). All error enums in this crate satisfy
  this today. Skip these only when a payload genuinely cannot be `Eq`
  (e.g. `f64`, `io::Error`, dynamically erased error objects) — none of
  which belong in error values anyway.
- `#[non_exhaustive]` — new variants must remain additive; downstream
  matches need a `_` arm.

Use `assert_eq!` for fixed‑shape variants in tests; prefer `matches!` for
"just check the variant" when the payload contains long free‑form strings
or nondeterministic samples.

---

## Naming and Paths

Function names should be concise but specific. Prefer short verbs and domain
terms over names that restate the module, type, or every implementation detail.

Prefer:

```rust
fn align_offsets(...)
fn validate_link(...)
fn rebuild_candidate(...)
```

Avoid:

```rust
fn align_periodic_vertex_offsets_for_source_simplex_to_target_simplex(...)
fn validate_manifold_link_consistency_for_all_ridges(...)
fn rebuild_delaunay_triangulation_candidate_after_repair_failure(...)
```

Use short, unqualified paths inside function bodies. If a function needs a type,
trait, constant, or helper from another module, import it at the top of the
module and refer to the item by its short name locally.

---

## Imports

Always import types at the top of the module rather than using fully‑qualified
paths inline. This keeps code readable and consistent.

Prefer:

```rust
use crate::core::tds::TdsError;

fn check(err: &TdsError) -> bool { ... }
```

Instead of:

```rust
fn check(err: &crate::core::tds::TdsError) -> bool { ... }
```

Group imports from the same module into a single `use` statement with braces:

```rust
use crate::core::tds::{
    SimplexKey, EntityKind, Tds, TdsError, VertexKey,
};
```

Do not add `use` statements inside function bodies just to shorten a path.
Move those imports to the top of the module. Local imports are acceptable only
when they are intentionally scoped for conditional compilation, tests, macro
expansion, or to avoid a documented name collision.

If a test module already has `use super::*;`, do not re‑import items that are
already brought into scope by the parent module's imports.

---

## Module Layout

Never use `mod.rs`.

Modules are declared from `src/lib.rs`.

Example:

```rust
pub mod core;
pub mod geometry;
pub mod algorithms;
```

Nested modules may use inline declaration:

```rust
pub mod core {
    pub mod triangulation;
    pub mod vertex;
}
```

---

## Prelude Design

Focused preludes should remain **small, orthogonal, and purpose-specific**.

A focused prelude should import only the items needed for a specific task.
Bundle only related, non-overlapping functionality in a focused prelude; do
not use one focused prelude as a compatibility bucket for adjacent workflows.
If a focused prelude has grown too broad or ambiguous, prefer fixing the
taxonomy over preserving backwards compatibility for unrelated re-exports.
Create a new focused prelude when a distinct workflow needs one.

Prefer focused preludes in doctests, integration tests, examples, and benchmarks
because they make intent visible at the import site.

Examples:

```text
delaunay::prelude
delaunay::prelude::triangulation
delaunay::prelude::construction
delaunay::prelude::pachner
delaunay::prelude::insertion
delaunay::prelude::deletion
delaunay::prelude::repair
delaunay::prelude::delaunayize
delaunay::prelude::validation
delaunay::prelude::query
delaunay::prelude::algorithms
delaunay::prelude::geometry
delaunay::prelude::generators
delaunay::prelude::diagnostics
delaunay::prelude::ordering
delaunay::prelude::collections
delaunay::prelude::tds
delaunay::prelude::topology::validation
delaunay::prelude::topology::spaces
```

Keep raw bistellar flip primitives out of preludes. Downstream examples should
use `delaunay::prelude::pachner` for local move workflows, the construction
prelude for `DelaunayTriangulation::insert_vertex`, and
`delaunay::prelude::deletion` when matching typed `delete_vertex` failures.
Import `delaunay::flips` directly only when testing, benchmarking, or
documenting the primitive flip layer itself.

The root `delaunay::prelude::*` is intentionally available as the
kitchen-sink prelude for new users, quick experiments, and exploratory tests.
Avoid using it in committed examples, benchmarks, and doctests when a focused
prelude communicates the workflow more clearly.

---

## Documentation

All public items must have documentation. Public functions must include a
doctest in their documentation.

Example:

```rust
/// Inserts a vertex into the triangulation.
///
/// Returns the key of the inserted vertex.
///
/// # Examples
///
/// ```rust
/// # use delaunay::prelude::construction::{DelaunayTriangulation};
/// # use delaunay::prelude::insertion::InsertionError;
/// # fn main() -> Result<(), InsertionError> {
/// let mut triangulation = DelaunayTriangulation::<_, _, _, 2>::default();
/// let key = triangulation.insert_vertex([0.0, 0.0])?;
/// assert!(triangulation.contains_vertex(key));
/// # Ok(())
/// # }
/// ```
pub fn insert_vertex(...)
```

### Private functions

Private functions must have a brief doc comment (`///`) explaining **why they
exist** — what problem they solve or what invariant they maintain. The *what*
is often clear from the signature; the *why* is not.

Prefer:

```rust
/// Aligns source-simplex periodic offsets into the target-simplex frame so
/// cross-simplex insphere predicates see consistent lifted coordinates.
fn align_periodic_offset<const D: usize>(...) -> Result<[i8; D], FlipError>
```

Use normal comments (`//`) for documentation inside function bodies or other
implementation-local notes:

```rust
fn align_periodic_offset<const D: usize>(...) -> Result<[i8; D], FlipError> {
    // Compare deltas in each coordinate so conflicting frame translations are
    // rejected before lifted coordinates are constructed.
    ...
}
```

A bare signature with no context forces readers to reverse-engineer
intent from the implementation.

After Rust changes, verify documentation builds:

```bash
just doc-check
```

or

```bash
cargo doc
```

---

## Integration Tests

Integration tests live in:

```text
tests/
```

Each integration test crate should include a crate‑level doc comment:

```rust
//! Integration tests for triangulation invariants.
```

This satisfies `clippy::missing_docs` in CI.

Fixed-bug regression integration tests belong in `tests/regressions.rs` unless
they need separate crate-level configuration, feature flags, or profile
isolation.

---

## Testing Expectations

Use focused tests while iterating on Rust changes, for example:

```bash
just test-unit
just test-doc
just test-integration
```

For final handoff validation, core Rust/Cargo changes require `just ci`.
Doctest-only, unit-test-only, integration-test-only, benchmark-only, and
example-only changes use the focused validators in
[`commands.md`](../commands.md).

Property tests are preferred for geometric invariants such as:

- Euler characteristic checks
- simplex adjacency invariants
- manifold consistency

---

## Performance

For performance-sensitive Rust changes, follow the benchmark-before-and-after
workflow in [`perf-tuning.md`](../perf-tuning.md). Add a representative benchmark
when none exists, and cover 2D through 5D for dimension-generic hot paths
whenever feasible.

Avoid unnecessary allocations.

Prefer:

- iterators
- slices
- stack arrays `[T; D]`
- fixed‑size containers

Avoid cloning large structures unless necessary.

Repair benchmarks sometimes need topology states that ordinary construction
must reject, such as codimension-1 facets incident to more than two simplices.
Keep those states behind `#[cfg(feature = "bench")]` fixture helpers and type
the fixture errors. Do not broaden normal public constructors or treat
`TopologyGuarantee::Pseudomanifold` as an invalid-topology bypass; it still
requires facet degree 1 or 2, boundary consistency, connectedness, isolated
vertex checks, and Euler validation when Level 3 runs.

---

## External Dependencies

Dependencies should be minimal.

Before adding a dependency, consider:

1. compile time impact
2. MSRV compatibility
3. maintenance status
4. dependency tree size

---

## Toolchain and Package Boundary

`Cargo.toml` owns the MSRV, and `rust-toolchain.toml` pins local and CI Rust to
that version. Keep the toolchain profile minimal and the default component set
limited to `clippy`, `rustfmt`, and `rust-src`; workflows or developers that
need cross targets or additional components should install them explicitly.

The explicit `Cargo.toml` package `include` list is the crates.io distribution
boundary. Keep it aligned with the public library, examples, benchmarks,
integration tests, active documentation, citation/release metadata, and assets
needed by docs.rs or published examples. Do not add CI-only tooling, Python
automation, or unrelated repository history to the crate artifact. Validate
changes to this boundary with:

```bash
just publish-check
```

---

## Formatting and Lints

Code must pass non-mutating checks:

```bash
just rust-core-check
```

Apply formatters and auto-fixes after reviewing check output:

```bash
just fix
```

CI treats warnings as errors.

### Lint Suppression

When suppressing a lint, use `#[expect(...)]` instead of `#[allow(...)]`.

`expect` causes a compiler warning if the lint is no longer triggered,
ensuring suppressions are removed when they become unnecessary.

Always include a `reason`:

```rust
#[expect(clippy::too_many_lines, reason = "test covers multiple cases")]
fn test_large_dataset_performance() { ... }
```

---

## API Stability

The crate is intended for external use, but it is still pre-1.0.0. Intentional
breaking changes to public types, functions, and modules are acceptable when
they improve correctness, invariants, orthogonality, or the constructor taxonomy
described above.

Do not preserve stale public APIs by adding deprecated compatibility aliases,
compatibility re-exports, or shim functions. Prefer a clean public surface with
clear migration guidance in docs and changelog material. For example,
`GlobalTopology::model` is crate-private behavior-model plumbing, and raw
toroidal input is parsed through public domain constructors such as
`ToroidalDomain::try_new` and `GlobalTopology::try_toroidal`; do not reintroduce
a public `ToroidalModel::try_new` alias.

---

## Logging and Diagnostics

Use `tracing` for committed diagnostics across production code, tests,
and benchmarks. This includes library/runtime code, non-trivial test
diagnostics, and debugging of numerical instability or topological
invariants. Prefer `tracing::debug!`, `tracing::trace!`, etc. over
ad-hoc printing.

This ensures all diagnostic output is:

- filterable via `RUST_LOG` / `tracing-subscriber`
- structured and machine-parseable
- suppressible in production builds

`eprintln!` is acceptable only for short-lived local debugging while
investigating an issue. Do not leave it in committed code when `tracing`
or a typed error path is more appropriate.

Debug hooks gated on environment variables should still use `tracing`:

```rust
#[cfg(debug_assertions)]
if std::env::var_os("DELAUNAY_DEBUG_FOO").is_some() {
    tracing::debug!("diagnostic message: {value}");
}
```

### Tests and Benchmarks

- Use `tracing` for non-trivial test diagnostics rather than
  `eprintln!`, especially when diagnosing geometric predicate behavior,
  invariant failures, or shrink/reproduction context.
- Never log inside hot benchmark loops or Criterion-measured closures.
  Emit diagnostics before or after the measured path so measurements stay
  meaningful.
- Gate non-essential test and benchmark diagnostics behind feature flags.
  In this repository, use `diagnostics` for test diagnostics and
  `bench-logging` for benchmark diagnostics:

```rust
#[cfg(feature = "diagnostics")]
tracing::debug!("test diagnostic");

#[cfg(feature = "bench-logging")]
tracing::debug!("benchmark diagnostic");
```

---

## Preferred Patch Style

When modifying Rust code:

- make **small focused changes**
- avoid large refactors
- maintain existing naming conventions
- preserve module boundaries