-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathall.txt
More file actions
2437 lines (1717 loc) · 88 KB
/
Copy pathall.txt
File metadata and controls
2437 lines (1717 loc) · 88 KB
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
<!-- Copyright (c) Microsoft Corporation. Licensed under the MIT license. -->
# Pragmatic Rust Guidelines
This file contains all guidelines concatenated for easy reference.
---
# AI Guidelines
## Design with AI use in Mind (M-DESIGN-FOR-AI) { #M-DESIGN-FOR-AI }
<why>To maximize the utility you get from letting agents work in your code base.</why>
<version>0.1</version>
As a general rule, making APIs easier to use for humans also makes them easier to use by AI.
If you follow the guidelines in this book, you should be in good shape.
Rust's strong type system is a boon for agents, as their lack of genuine understanding can often be
counterbalanced by comprehensive compiler checks, which Rust provides in abundance.
With that said, there are a few guidelines which are particularly important to help make AI coding in Rust more effective:
* **Create Idiomatic Rust API Patterns**. The more your APIs, whether public or internal, look and feel like the majority of
Rust code in the world, the better it is for AI. Follow the [Rust API Guidelines](https://rust-lang.github.io/api-guidelines/checklist.html)
along with the guidelines from [Library / UX](../libs/ux).
* **Provide Thorough Docs**. Agents love good detailed docs. Include docs for all of your modules and public items in your crate.
Assume the reader has a solid, but not expert, level of understanding of Rust, and that the reader understands the standard library.
Follow
[C-CRATE-DOC](https://rust-lang.github.io/api-guidelines/checklist.html#c-crate-doc),
[C-FAILURE](https://rust-lang.github.io/api-guidelines/checklist.html#c-failure),
[C-LINK](https://rust-lang.github.io/api-guidelines/checklist.html#c-link), and
[M-MODULE-DOCS](../docs/#M-MODULE-DOCS)
[M-CANONICAL-DOCS](../docs/#M-CANONICAL-DOCS).
* **Provide Thorough Examples**. Your documentation should have directly usable examples, the repository should include more elaborate ones.
Follow
[C-EXAMPLE](https://rust-lang.github.io/api-guidelines/checklist.html#c-example)
[C-QUESTION-MARK](https://rust-lang.github.io/api-guidelines/checklist.html#c-question-mark).
* **Use Strong Types**. Avoid [primitive obsession](https://refactoring.guru/smells/primitive-obsession) by using strong types with strict well-documented semantics.
Follow
[C-NEWTYPE](https://rust-lang.github.io/api-guidelines/checklist.html#c-newtype).
* **Make Your APIs Testable**. Design APIs which allow your customers to test their use of your API in unit tests. This might involve introducing some mocks, fakes,
or cargo features. AI agents need to be able to iterate quickly to prove that the code they are writing that calls your API is working
correctly.
* **Ensure Test Coverage**. Your own code should have good test coverage over observable behavior.
This enables agents to work in a mostly hands-off mode when refactoring.
---
# Application Guidelines
## Applications may use Anyhow or Derivatives (M-APP-ERROR) { #M-APP-ERROR }
<why>To simplify application-level error handling.</why>
<version>0.1</version>
> Note, this guideline is primarily a relaxation and clarification of [M-ERRORS-CANONICAL-STRUCTS].
Applications, and crates in your own repository exclusively used from your application, may use [anyhow](https://github.com/dtolnay/anyhow),
[eyre](https://github.com/eyre-rs/eyre) or similar application-level error crates instead of implementing their own types.
For example, in your application crates you may just re-export and use eyre's common `Result` type, which should be able to automatically
handle all third party library errors, in particular the ones following
[M-ERRORS-CANONICAL-STRUCTS].
```rust,ignore
use eyre::Result;
fn start_application() -> Result<()> {
start_server()?;
Ok(())
}
```
Once you selected your application error crate you should switch all application-level errors to that type, and you should not mix multiple
application-level error types.
Libraries (crates used by more than one crate) should always follow [M-ERRORS-CANONICAL-STRUCTS] instead.
[M-ERRORS-CANONICAL-STRUCTS]: ../libs/ux/#M-ERRORS-CANONICAL-STRUCTS
## Use Mimalloc for Apps (M-MIMALLOC-APPS) { #M-MIMALLOC-APPS }
<why>To get significant performance for free.</why>
<version>0.1</version>
Applications should set [mimalloc](https://crates.io/crates/mimalloc) as their global allocator. This usually results in notable performance
increases along allocating hot paths; we have seen up to 25% benchmark improvements.
Changing the allocator only takes a few lines of code. Add mimalloc to your `Cargo.toml` like so:
```toml
[dependencies]
mimalloc = { version = "0.1" } # Or later version if available
```
Then use it from your `main.rs`:
```rust,ignore
use mimalloc::MiMalloc;
#[global_allocator]
static GLOBAL: MiMalloc = MiMalloc;
```
---
# Documentation
## Documentation Has Canonical Sections (M-CANONICAL-DOCS) { #M-CANONICAL-DOCS }
<why>To follow established and expected Rust best practices.</why>
<version>1.0</version>
Public library items must contain the canonical doc sections. The summary sentence must always be present. Extended documentation and examples
are strongly encouraged. The other sections must be present when applicable.
```rust
/// Summary sentence < 15 words.
///
/// Extended documentation in free form.
///
/// # Examples
/// One or more examples that show API usage like so.
///
/// # Errors
/// If fn returns `Result`, list known error conditions
///
/// # Panics
/// If fn may panic, list when this may happen
///
/// # Safety
/// If fn is `unsafe` or may otherwise cause UB, this section must list
/// all conditions a caller must uphold.
///
/// # Abort
/// If fn may abort the process, list when this may happen.
pub fn foo() {}
```
In contrast to other languages, you should not create a table of parameters. Instead parameter use is explained in plain text. In other words, do not
```rust,ignore
/// Copies a file.
///
/// # Parameters
/// - src: The source.
/// - dst: The destination.
fn copy(src: File, dst: File) {}
```
but instead:
```rust,ignore
/// Copies a file from `src` to `dst`.
fn copy(src: File, dst: File) {}
```
### Related Reading
- Function docs include error, panic, and safety considerations ([C-FAILURE](https://rust-lang.github.io/api-guidelines/documentation.html#c-failure))
## Mark `pub use` Items with `#[doc(inline)]` (M-DOC-INLINE) { #M-DOC-INLINE }
<why>To make re-exported items 'fit in' with their non re-exported siblings.</why>
<version>1.0</version>
When publicly re-exporting crate items via `pub use foo::Foo` or `pub use foo::*`, they show up in an opaque re-export block. In most cases, this is not
helpful to the reader:

Instead, you should annotate them with `#[doc(inline)]` at the `use` site, for them to be inlined organically:
```rust,edition2021,ignore
# pub(crate) mod foo { pub struct Foo; }
#[doc(inline)]
pub use foo::*;
// or
#[doc(inline)]
pub use foo::Foo;
```

This does not apply to `std` or 3rd party types; these should always be re-exported without inlining to make it clear they are external.
> ### <alert></alert> Still avoid glob exports
>
> The `#[doc(inline)]` trick above does not change [M-NO-GLOB-REEXPORTS]; you generally should not re-export items via wildcards.
[M-NO-GLOB-REEXPORTS]: ../libs/resilience/#M-NO-GLOB-REEXPORTS
## First Sentence is One Line; Approx. 15 Words (M-FIRST-DOC-SENTENCE) { #M-FIRST-DOC-SENTENCE }
<why>To make API docs easily skimmable.</why>
<version>1.0</version>
When you document your item, the first sentence becomes the "summary sentence" that is extracted and shown in the module summary:
```rust
/// This is the summary sentence, shown in the module summary.
///
/// This is other documentation. It is only shown in that item's detail view.
/// Sentences here can be as long as you like and it won't cause any issues.
fn some_item() { }
```
Since Rust API documentation is rendered with a fixed max width, there is a naturally preferred sentence length you should not
exceed to keep things tidy on most screens.
If you keep things in a line, your docs will become easily skimmable. Compare, for example, the standard library:

Otherwise, you might end up with _widows_ and a generally unpleasant reading flow:

As a rule of thumb, the first sentence should not exceed **15 words**.
## Has Comprehensive Module Documentation (M-MODULE-DOCS) { #M-MODULE-DOCS }
<why>To allow for better API docs navigation.</why>
<version>1.1</version>
Any public library module must have `//!` module documentation, and the first sentence must follow [M-DOC-FIRST-SENTENCE].
```rust,edition2021,ignore
pub mod ffi {
//! Contains FFI abstractions.
pub struct String {};
}
```
The rest of the module documentation should be comprehensive, i.e., cover the most relevant technical aspects of the contained items, including
- what the module contains
- when it should be used, possibly when not
- examples
- subsystem specifications (e.g., `std::fmt` [also describes its formatting language](https://doc.rust-lang.org/stable/std/fmt/index.html#formatting-parameters))
- observable side effects, including what guarantees are made about these, if any
- relevant implementation details, e.g., the used system APIs
Great examples include:
- [`std::fmt`](https://doc.rust-lang.org/stable/std/fmt/index.html)
- [`std::pin`](https://doc.rust-lang.org/stable/std/pin/index.html)
- [`std::option`](https://doc.rust-lang.org/stable/std/option/index.html)
This does not mean every module should contain all of these items. But if there is something to say about the interaction of the contained types,
their module documentation is the right place.
[M-DOC-FIRST-SENTENCE]: ./#M-DOC-FIRST-SENTENCE
---
# FFI Guidelines
## Isolate DLL State Between FFI Libraries (M-ISOLATE-DLL-STATE) { #M-ISOLATE-DLL-STATE }
<why>To prevent data corruption and undefined behavior.</why>
<version>0.1</version>
When loading multiple Rust-based dynamic libraries (DLLs) within one application, you may only share 'portable' state between these libraries.
Likewise, when authoring such libraries, you must only accept or provide 'portable' data from foreign DLLs.
Portable here means data that is safe and consistent to process regardless of its origin. By definition, this is a subset of FFI-safe types.
A type is portable if it is `#[repr(C)]` (or similarly well-defined), and _all_ of the following:
- It must not have any interaction with any `static` or thread local.
- It must not have any interaction with any `TypeId`.
- It must not contain any value, pointer or reference to any non-portable data (it is valid to point into portable data within non-portable data, such as
sharing a reference to an ASCII string held in a `Box`).
_Interaction_ means any computational relationship, and therefore also relates to how the type is used. Sending a `u128` between DLLs is OK, using it to
exchange a transmuted `TypeId` isn't.
The underlying issue stems from the Rust compiler treating each DLL as an entirely new compilation artifact, akin to a standalone application. This means each DLL:
- has its own set of `static` and thread-local variables,
- the type layout of any `#[repr(Rust)]` type (the default) can differ between compilations,
- has its own set of unique type IDs, differing from any other DLL.
Notably, this affects:
- ⚠️ any allocated instance, e.g., `String`, `Vec<u8>`, `Box<Foo>`, ...
- ⚠️ any library relying on other statics, e.g., `tokio`, `log`,
- ⚠️ any struct not `#[repr(C)]`,
- ⚠️ any data structure relying on consistent `TypeId`.
In practice, transferring any of the above between libraries leads to data loss, state corruption, and usually undefined behavior.
Take particular note that this may also apply to types and methods that are invisible at the FFI boundary:
```rust,ignore
/// A method in DLL1 that wants to use a common service from DLL2
#[ffi_function]
fn use_common_service(common: &CommonService) {
// This has at least two issues:
// - `CommonService`, or ANY type nested deep within might have
// a different type layout in DLL2, leading to immediate
// undefined behavior (UB) ⚠️
// - `do_work()` here looks like it will be invoked in DLL2, but
// the code executed will actually come from DLL1. This means that
// `do_work()` invoked here will see a data structure coming from
// DLL2, but will use statics from DLL1 ⚠️
common.do_work();
}
```
---
# Library Guidelines
---
# Performance Guidelines
## Identify, Profile, Optimize the Hot Path Early (M-HOTPATH) { #M-HOTPATH }
<why>To end up with high performance code.</why>
<version>0.1</version>
You should, early in the development process, identify if your crate is performance or COGS relevant. If it is:
- identify hot paths and create benchmarks around them,
- regularly run a profiler collecting CPU and allocation insights,
- document or communicate the most performance sensitive areas.
For benchmarks we recommend [criterion](https://crates.io/crates/criterion) or [divan](https://crates.io/crates/divan).
If possible, benchmarks should not only measure elapsed wall time, but also used CPU time over all threads (this unfortunately
requires manual work and is not supported out of the box by the common benchmark utils).
Profiling Rust on Windows works out of the box with [Intel VTune](https://www.intel.com/content/www/us/en/developer/tools/oneapi/vtune-profiler.html)
and [Superluminal](https://superluminal.eu/). However, to gain meaningful CPU insights you should enable debug symbols for benchmarks in your `Cargo.toml`:
```toml
[profile.bench]
debug = 1
```
Documenting the most performance sensitive areas helps other contributors take better decision. This can be as simple as
sharing screenshots of your latest profiling hot spots.
### Further Reading
- [Performance Tips](https://cheats.rs/#performance-tips)
> ### <tip></tip> How much faster?
>
> Some of the most common 'language related' issues we have seen include:
>
> - frequent re-allocations, esp. cloned, growing or `format!` assembled strings,
> - short lived allocations over bump allocations or similar,
> - memory copy overhead that comes from cloning Strings and collections,
> - repeated re-hashing of equal data structures
> - the use of Rust's default hasher where collision resistance wasn't an issue
>
> Anecdotally, we have seen ~15% benchmark gains on hot paths where only some of these `String` problems were
> addressed, and it appears that up to 50% could be achieved in highly optimized versions.
## Optimize for Throughput, Avoid Empty Cycles (M-THROUGHPUT) { #M-THROUGHPUT }
<why>To ensure COGS savings at scale.</why>
<version>0.1</version>
You should optimize your library for throughput, and one of your key metrics should be _items per CPU cycle_.
This does not mean to neglect latency—after all you can scale for throughput, but not for latency. However,
in most cases you should not pay for latency with _empty cycles_ that come with single-item processing, contended locks and frequent task switching.
Ideally, you should
- partition reasonable chunks of work ahead of time,
- let individual threads and tasks deal with their slice of work independently,
- sleep or yield when no work is present,
- design your own APIs for batched operations,
- perform work via batched APIs where available,
- yield within long individual items, or between chunks of batches (see [M-YIELD-POINTS]),
- exploit CPU caches, temporal and spatial locality.
You should not:
- hot spin to receive individual items faster,
- perform work on individual items if batching is possible,
- do work stealing or similar to balance individual items.
Shared state should only be used if the cost of sharing is less than the cost of re-computation.
[M-YIELD-POINTS]: ./#M-YIELD-POINTS
## Long-Running Tasks Should Have Yield Points. (M-YIELD-POINTS) { #M-YIELD-POINTS }
<why>To ensure you don't starve other tasks of CPU time.</why>
<version>0.2</version>
If you perform long running computations, they should contain `yield_now().await` points.
Your future might be executed in a runtime that cannot work around blocking or long-running tasks. Even then, such tasks are
considered bad design and cause runtime overhead. If your complex task performs I/O regularly it will simply utilize these await points to preempt itself:
```rust, ignore
async fn process_items(items: &[items]) {
// Keep processing items, the runtime will preempt you automatically.
for i in items {
read_item(i).await;
}
}
```
If your task performs long-running CPU operations without intermixed I/O, it should instead cooperatively yield at regular intervals, to not starve concurrent operations:
```rust, ignore
async fn process_items(zip_file: File) {
let items = zip_file.read().async;
for i in items {
decompress(i);
yield_now().await;
}
}
```
If the number and duration of your individual operations are unpredictable you should use APIs such as `has_budget_remaining()` and
related APIs to query your hosting runtime.
> ### <tip></tip> Yield how often?
>
> In a thread-per-core model the overhead of task switching must be balanced against the systemic effects of starving unrelated tasks.
>
> Under the assumption that runtime task switching takes 100's of ns, in addition to the overhead of lost CPU caches,
> continuous execution in between should be long enough that the switching cost becomes negligible (<1%).
>
> Thus, performing 10 - 100μs of CPU-bound work between yield points would be a good starting point.
---
# Safety Guidelines
## Unsafe Implies Undefined Behavior (M-UNSAFE-IMPLIES-UB) { #M-UNSAFE-IMPLIES-UB }
<why>To ensure semantic consistency and prevent warning fatigue.</why>
<version>1.0</version>
The marker `unsafe` may only be applied to functions and traits if misuse implies the risk of undefined behavior (UB).
It must not be used to mark functions that are dangerous to call for other reasons.
```rust
// Valid use of unsafe
unsafe fn print_string(x: *const String) { }
// Invalid use of unsafe
unsafe fn delete_database() { }
```
## Unsafe Needs Reason, Should be Avoided (M-UNSAFE) { #M-UNSAFE }
<why>To prevent undefined behavior, attack surface, and similar 'happy little accidents'.</why>
<version>0.2</version>
You must have a valid reason to use `unsafe`. The only valid reasons are
1) novel abstractions, e.g., a new smart pointer or allocator,
1) performance, e.g., attempting to call `.get_unchecked()`,
1) FFI and platform calls, e.g., calling into C or the kernel, ...
Unsafe code lowers the guardrails used by the compiler, transferring some of the compiler's responsibilities
to the programmer. Correctness of the resulting code relies primarily on catching all mistakes in code review,
which is error-prone. Mistakes in unsafe code may introduce high-severity security vulnerabilities.
You must not use ad-hoc `unsafe` to
- shorten a performant and safe Rust program, e.g., 'simplify' enum casts via `transmute`,
- bypass `Send` and similar bounds, e.g., by doing `unsafe impl Send ...`,
- bypass lifetime requirements via `transmute` and similar.
Ad-hoc here means `unsafe` embedded in otherwise unrelated code. It is of course permissible to create properly designed, sound abstractions doing these things.
In any case, `unsafe` must follow the guidelines outlined below.
### Novel Abstractions
- [ ] Verify there is no established alternative. If there is, prefer that.
- [ ] Your abstraction must be minimal and testable.
- [ ] It must be hardened and tested against ["adversarial code"](https://cheats.rs/#adversarial-code), esp.
- If they accept closures they must become invalid (e.g., poisoned) if the closure panics
- They must assume any safe trait is misbehaving, esp. `Deref`, `Clone` and `Drop`.
- [ ] Any use of `unsafe` must be accompanied by plain-text reasoning outlining its safety
- [ ] It must pass [Miri](https://github.com/rust-lang/miri), including adversarial test cases
- [ ] It must follow all other [unsafe code guidelines](https://rust-lang.github.io/unsafe-code-guidelines/)
### Performance
- [ ] Using `unsafe` for performance reasons should only be done after benchmarking
- [ ] Any use of `unsafe` must be accompanied by plain-text reasoning outlining its safety. This applies to both
calling `unsafe` methods, as well as providing `_unchecked` ones.
- [ ] The code in question must pass [Miri](https://github.com/rust-lang/miri)
- [ ] You must follow the [unsafe code guidelines](https://rust-lang.github.io/unsafe-code-guidelines/)
### FFI
- [ ] We recommend you use an established interop library to avoid `unsafe` constructs
- [ ] You must follow the [unsafe code guidelines](https://rust-lang.github.io/unsafe-code-guidelines/)
- [ ] You must document your generated bindings to make it clear which call patterns are permissible
### Further Reading
- [Nomicon](https://doc.rust-lang.org/nightly/nomicon/)
- [Unsafe Code Guidelines](https://rust-lang.github.io/unsafe-code-guidelines/)
- [Miri](https://github.com/rust-lang/miri)
- ["Adversarial code"](https://cheats.rs/#adversarial-code)
## All Code Must be Sound (M-UNSOUND) { #M-UNSOUND }
<why>To prevent unexpected runtime behavior, leading to potential bugs and incompatibilities.</why>
<version>1.0</version>
Unsound code is seemingly _safe_ code that may produce undefined behavior when called from other safe code, or on its own accord.
> ### <tip></tip> Meaning of 'Safe'
>
> The terms _safe_ and `unsafe` are technical terms in Rust.
>
> A function is _safe_, if its signature does not mark it `unsafe`. That said, _safe_ functions can still be dangerous
> (e.g., `delete_database()`), and `unsafe` ones are, when properly used, usually quite benign (e.g.,`vec.get_unchecked()`).
>
> A function is therefore _unsound_ if it appears _safe_ (i.e., it is not marked `unsafe`), but if _any_ of its calling
> modes would cause undefined behavior. This is to be interpreted in the strictest sense. Even if causing undefined
> behavior is only a 'remote, theoretical possibility' requiring 'weird code', the function is unsound.
>
> Also see [Unsafe, Unsound, Undefined](https://cheats.rs/#unsafe-unsound-undefined).
```rust
// "Safely" converts types
fn unsound_ref<T>(x: &T) -> &u128 {
unsafe { std::mem::transmute(x) }
}
// "Clever trick" to work around missing `Send` bounds.
struct AlwaysSend<T>(T);
unsafe impl<T> Send for AlwaysSend<T> {}
unsafe impl<T> Sync for AlwaysSend<T> {}
```
Unsound abstractions are never permissible. If you cannot safely encapsulate something, you must expose `unsafe` functions instead, and document proper behavior.
<div class="warning">
No Exceptions
While you may break most guidelines if you have a good enough reason, there are no exceptions in this case: unsound code is never acceptable.
</div>
> ### <tip></tip> It's the Module Boundaries
>
> Note that soundness boundaries equal module boundaries! It is perfectly fine, in an otherwise safe abstraction,
> to have safe functions that rely on behavior guaranteed elsewhere **in the same module**.
>
> ```rust
> struct MyDevice(*const u8);
>
> impl MyDevice {
> fn new() -> Self {
> // Properly initializes instance ...
> # todo!()
> }
>
> fn get(&self) -> u8 {
> // It is perfectly fine to rely on `self.0` being valid, despite this
> // function in-and-by itself being unable to validate that.
> unsafe { *self.0 }
> }
> }
>
> ```
---
# Universal Guidelines
## Names are Free of Weasel Words (M-CONCISE-NAMES) { #M-CONCISE-NAMES }
<why>To improve readability.</why>
<version>1.0</version>
Symbol names, especially types and traits names, should be free of weasel words that do not meaningfully
add information. Common offenders include `Service`, `Manager`, and `Factory`. For example:
While your library may very well contain or communicate with a booking service—or even hold an `HttpClient`
instance named `booking_service`—one should rarely encounter a `BookingService` _type_ in code.
An item handling many bookings can just be called `Bookings`. If it does anything more specific, then that quality
should be appended instead. It submits these items elsewhere? Calling it `BookingDispatcher` would be more helpful.
The same is true for `Manager`s. Every code manages _something_, so that moniker is rarely useful. With rare
exceptions, life cycle issues should likewise not be made the subject of some manager. Items are created in whatever
way they are needed, their disposal is governed by `Drop`, and only `Drop`.
Regarding factories, at least the term should be avoided. While the concept `FooFactory` has its use, its canonical
Rust name is `Builder` (compare [M-INIT-BUILDER](../libs/ux/#M-INIT-BUILDER)). A builder that can produce items repeatedly is still a builder.
In addition, accepting factories (builders) as parameters is an unidiomatic import of OO concepts into Rust. If
repeatable instantiation is required, functions should ask for an `impl Fn() -> Foo` over a `FooBuilder` or
similar. In contrast, standalone builders have their use, but primarily to reduce parametric permutation complexity
around optional values (again, [M-INIT-BUILDER](../libs/ux/#M-INIT-BUILDER)).
## Magic Values are Documented (M-DOCUMENTED-MAGIC) { #M-DOCUMENTED-MAGIC }
<why>To ensure maintainability and prevent misunderstandings when refactoring.</why>
<version>1.0</version>
Hardcoded _magic_ values in production code must be accompanied by a comment. The comment should outline:
- why this value was chosen,
- non-obvious side effects if that value is changed,
- external systems that interact with this constant.
You should prefer named constants over inline values.
```rust, ignore
// Bad: it's relatively obvious that this waits for a day, but not why
wait_timeout(60 * 60 * 24).await // Wait at most a day
// Better
wait_timeout(60 * 60 * 24).await // Large enough value to ensure the server
// can finish. Setting this too low might
// make us abort a valid request. Based on
// `api.foo.com` timeout policies.
// Best
/// How long we wait for the server.
///
/// Large enough value to ensure the server
/// can finish. Setting this too low might
/// make us abort a valid request. Based on
/// `api.foo.com` timeout policies.
const UPSTREAM_SERVER_TIMEOUT: Duration = Duration::from_secs(60 * 60 * 24);
```
## Lint Overrides Should Use `#[expect]` (M-LINT-OVERRIDE-EXPECT) { #M-LINT-OVERRIDE-EXPECT }
<why>To prevent the accumulation of outdated lints.</why>
<version>1.0</version>
When overriding project-global lints inside a submodule or item, you should do so via `#[expect]`, not `#[allow]`.
Expected lints emit a warning if the marked warning was not encountered, thus preventing the accumulation of stale lints.
That said, `#[allow]` lints are still useful when applied to generated code, and can appear in macros.
Overrides should be accompanied by a `reason`:
```rust,edition2021
#[expect(clippy::unused_async, reason = "API fixed, will use I/O later")]
pub async fn ping_server() {
// Stubbed out for now
}
```
## Use Structured Logging with Message Templates (M-LOG-STRUCTURED) { #M-LOG-STRUCTURED }
<why>To minimize the cost of logging and to improve filtering capabilities.</why>
<version>0.1</version>
Logging should use structured events with named properties and message templates following
the [message templates](https://messagetemplates.org/) specification.
> **Note:** Examples use the [`tracing`](https://docs.rs/tracing/) crate's `event!` macro,
but these principles apply to any logging API that supports structured logging (e.g., `log`,
`slog`, custom telemetry systems).
### Avoid String Formatting
String formatting allocates memory at runtime. Message templates defer formatting until viewing time.
We recommend that message template includes all named properties for easier inspection at viewing time.
```rust,ignore
// Bad: String formatting causes allocations
tracing::info!("file opened: {}", path);
tracing::info!(format!("file opened: {}", path));
// Good: Message templates with named properties
event!(
name: "file.open.success",
Level::INFO,
file.path = path.display(),
"file opened: {{file.path}}",
);
```
> **Note**: Use the `{{property}}` syntax in message templates which preserves the literal text
> while escaping Rust's format syntax. String formatting is deferred until logs are viewed.
### Name Your Events
Use hierarchical dot-notation: `<component>.<operation>.<state>`
```rust,ignore
// Bad: Unnamed events
event!(
Level::INFO,
file.path = file_path,
"file {{file.path}} processed succesfully",
);
// Good: Named events
event!(
name: "file.processing.success", // event identifier
Level::INFO,
file.path = file_path,
"file {{file.path}} processed succesfully",
);
```
Named events enable grouping and filtering across log entries.
### Follow OpenTelemetry Semantic Conventions
Use [OTel semantic conventions](https://opentelemetry.io/docs/specs/semconv/) for common attributes if needed.
This enables standardization and interoperability.
```rust,ignore
event!(
name: "file.write.success",
Level::INFO,
file.path = path.display(), // Standard OTel name
file.size = bytes_written, // Standard OTel name
file.directory = dir_path, // Standard OTel name
file.extension = extension, // Standard OTel name
file.operation = "write", // Custom name
"{{file.operation}} {{file.size}} bytes to {{file.path}} in {{file.directory}} extension={{file.extension}}",
);
```
Common conventions:
- HTTP: `http.request.method`, `http.response.status_code`, `url.scheme`, `url.path`, `server.address`
- File: `file.path`, `file.directory`, `file.name`, `file.extension`, `file.size`
- Database: `db.system.name`, `db.namespace`, `db.operation.name`, `db.query.text`
- Errors: `error.type`, `error.message`, `exception.type`, `exception.stacktrace`
### Redact Sensitive Data
Do not log plain sensitive data as this might lead to privacy and security incidents.
```rust,ignore
// Bad: Logs potentially sensitive data
event!(
name: "file.operation.started",
Level::INFO,
user.email = user.email, // Sensitive data
file.name = "license.txt",
"reading file {{file.name}} for user {{user.email}}",
);
// Good: Redact sensitive parts
event!(
name: "file.operation.started",
Level::INFO,
user.email.redacted = redact_email(user.email),
file.name = "license.txt",
"reading file {{file.name}} for user {{user.email.redacted}}",
);
```
Sensitive data includes email addresses, file paths revealing user identity, filenames containing secrets or tokens,
file contents with PII, temporary file paths with session IDs and more. Consider using the [`data_privacy`](https://crates.io/crates/data_privacy) crate for consistent redaction.
### Further Reading
- [Message Templates Specification](https://messagetemplates.org/)
- [OpenTelemetry Semantic Conventions](https://opentelemetry.io/docs/specs/semconv/)
- [OWASP Logging Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html)
## Panic Means 'Stop the Program' (M-PANIC-IS-STOP) { #M-PANIC-IS-STOP }
<why>To ensure soundness and predictability.</why>
<version>1.0</version>
Panics are not exceptions. Instead, they suggest immediate program termination.
Although your code must be [panic-safe](https://doc.rust-lang.org/nomicon/exception-safety.html) (i.e., a survived panic may not lead to
inconsistent state), invoking a panic means _this program should stop now_. It is not valid to:
- use panics to communicate (errors) upstream,
- use panics to handle self-inflicted error conditions,
- assume panics will be caught, even by your own code.
For example, if the application calling you is compiled with a `Cargo.toml` containing
```toml
[profile.release]
panic = "abort"
```
then any invocation of panic will cause an otherwise functioning program to needlessly abort. Valid reasons to panic are:
- when encountering a programming error, e.g., `x.expect("must never happen")`,
- anything invoked from const contexts, e.g., `const { foo.unwrap() }`,
- when user requested, e.g., providing an `unwrap()` method yourself,
- when encountering a poison, e.g., by calling `unwrap()` on a lock result (a poisoned lock signals another thread has panicked already).
Any of those are directly or indirectly linked to programming errors.
## Detected Programming Bugs are Panics, Not Errors (M-PANIC-ON-BUG) { #M-PANIC-ON-BUG }
<why>To avoid impossible error handling code and ensure runtime consistency.</why>
<version>1.0</version>
As an extension of [M-PANIC-IS-STOP] above, when an unrecoverable programming error has been
detected, libraries and applications must panic, i.e., request program termination.
In these cases, no `Error` type should be introduced or returned, as any such error could not be acted upon at runtime.
Contract violations, i.e., the breaking of invariants either within a library or by a caller, are programming errors and must therefore panic.
However, what constitutes a violation is situational. APIs are not expected to go out of their way to detect them, as such
checks can be impossible or expensive. Encountering `must_be_even == 3` during an already existing check clearly warrants
a panic, while a function `parse(&str)` clearly must return a `Result`. If in doubt, we recommend you take inspiration from the standard library.
```rust, ignore
// Generally, a function with bad parameters must either
// - Ignore a parameter and/or return the wrong result
// - Signal an issue via Result or similar
// - Panic
// If in this `divide_by` we see that y == 0, panicking is
// the correct approach.
fn divide_by(x: u32, y: u32) -> u32 { ... }
// However, it can also be permissible to omit such checks
// and return an unspecified (but not an undefined) result.
fn divide_by_fast(x: u32, y: u32) -> u32 { ... }
// Here, passing an invalid URI is not a contract violation.
// Since parsing is inherently fallible, a Result must be returned.
fn parse_uri(s: &str) -> Result<Uri, ParseError> { };
```
> ### <tip></tip> Make it 'Correct by Construction'
>
> While panicking on a detected programming error is the 'least bad option', your panic might still ruin someone's day.
> For any user input or calling sequence that would otherwise panic, you should also explore if you can use the type
> system to avoid panicking code paths altogether.
[M-PANIC-IS-STOP]: ../universal/#M-PANIC-IS-STOP
## Public Types are Debug (M-PUBLIC-DEBUG) { #M-PUBLIC-DEBUG }
<why>To simplify debugging and prevent leaking sensitive data.</why>
<version>1.0</version>
All public types exposed by a crate should implement `Debug`. Most types can do so via `#[derive(Debug)]`:
```rust
#[derive(Debug)]
struct Endpoint(String);
```
Types designed to hold sensitive data should also implement `Debug`, but do so via a custom implementation.
This implementation must employ unit tests to ensure sensitive data isn't actually leaked, and will not be in the future.
```rust
use std::fmt::{Debug, Formatter};
struct UserSecret(String);
impl Debug for UserSecret {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "UserSecret(...)")
}
}
#[test]
fn test() {
let key = "552d3454-d0d5-445d-ab9f-ef2ae3a8896a";
let secret = UserSecret(key.to_string());
let rendered = format!("{:?}", secret);
assert!(rendered.contains("UserSecret"));
assert!(!rendered.contains(key));
}
```
## Public Types Meant to be Read are Display (M-PUBLIC-DISPLAY) { #M-PUBLIC-DISPLAY }
<why>To improve usability.</why>
<version>1.0</version>
If your type is expected to be read by upstream consumers, be it developers or end users, it should implement `Display`. This in particular includes:
- Error types, which are mandated by `std::error::Error` to implement `Display`
- Wrappers around string-like data
Implementations of `Display` should follow Rust customs; this includes rendering newlines and escape sequences.
The handling of sensitive data outlined in [M-PUBLIC-DEBUG] applies analogously.
[M-PUBLIC-DEBUG]: ./#M-PUBLIC-DEBUG
## Prefer Regular over Associated Functions (M-REGULAR-FN) { #M-REGULAR-FN }
<why>To improve readability.</why>
<version>1.0</version>
Associated functions should primarily be used for instance creation, not general purpose computation.
In contrast to some OO languages, regular functions are first-class citizens in Rust and need no module or _class_ to host them. Functionality that
does not clearly belong to a receiver should therefore not reside in a type's `impl` block:
```rust, ignore
struct Database {}
impl Database {
// Ok, associated function creates an instance
fn new() -> Self {}
// Ok, regular method with `&self` as receiver
fn query(&self) {}
// Not ok, this function is not directly related to `Database`,
// it should therefore not live under `Database` as an associated
// function.
fn check_parameters(p: &str) {}
}
// As a regular function this is fine
fn check_parameters(p: &str) {}
```
Regular functions are more idiomatic, and reduce unnecessary noise on the caller side. Associated trait functions are perfectly idiomatic though: