framealloc 0.6.0

Intent-aware, thread-smart memory allocation for Rust game engines
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
# `framealloc`


**Deterministic, frame-based memory allocation for Rust game engines.**

`framealloc` is an engine-shaped memory allocation crate designed for **predictable performance**, **explicit lifetimes**, and **out-of-the-box scaling from single-threaded to multi-threaded workloads**.

It is **not** a general-purpose replacement for Rust's global allocator.
It is a **purpose-built tool** for game engines, renderers, simulations, and real-time systems.

---

## Why `framealloc`?


Most game engine memory:

* Is short-lived
* Has a clear lifetime (per-frame, per-system, per-task)
* Is performance-sensitive
* Should *never* hit the system allocator in hot paths

Yet most Rust code still relies on:

* `Vec`, `Box`, and `Arc` everywhere
* Implicit heap allocations
* Allocators optimized for average-case workloads

`framealloc` makes **memory intent explicit** and **cheap**.

---

## Core Concepts


### 1. Frame-based allocation


The primary allocator is a **frame arena**:

* Fast bump allocation
* No per-allocation free
* Reset once per frame

```rust
use framealloc::{SmartAlloc, AllocConfig};

let alloc = SmartAlloc::new(AllocConfig::default());

alloc.begin_frame();

let tmp = alloc.frame_alloc::<ScratchData>();
let verts = alloc.frame_alloc::<[Vertex; 4096]>();

// All frame allocations are invalid after end_frame
alloc.end_frame();
```

This model:

* Eliminates fragmentation
* Guarantees O(1) allocation
* Matches how engines actually work

---

### 2. Thread-local fast paths


Every thread automatically gets:

* Its own frame arena
* Its own small-object pools
* Zero locks on hot paths

This is always enabled — even in single-threaded programs.

```text
Single-threaded: 1 TLS allocator
Multi-threaded:  N TLS allocators
Same API. Same behavior.
```

No mode switching. No configuration required.

---

### 3. Automatic single → multi-thread scaling


`framealloc` scales automatically when used across threads:

* **Single-threaded usage:**
  * No mutex contention
  * No atomic overhead in hot paths

* **Multi-threaded usage:**
  * Thread-local allocation remains lock-free
  * Shared state is only touched during refills

The user never toggles a "threaded mode".

```rust
use framealloc::SmartAlloc;
use std::sync::Arc;

let alloc = Arc::new(SmartAlloc::with_defaults());

std::thread::spawn({
    let alloc = alloc.clone();
    move || {
        alloc.begin_frame();
        let x = alloc.frame_alloc::<Foo>();
        alloc.end_frame();
    }
});
```

This works out of the box.

---

### 4. Allocation by intent


Allocations are categorized by **intent**, not just size:

| Intent | Method | Behavior |
|--------|--------|----------|
| `Frame` | `frame_alloc::<T>()` | Bump allocation, reset every frame |
| `Pool` | `pool_alloc::<T>()` | Thread-local pooled allocation |
| `Heap` | `heap_alloc::<T>()` | System allocator (large objects) |

This allows:

* Better locality
* Predictable behavior
* Meaningful diagnostics

---

### 5. Designed for game engines (and Bevy)


`framealloc` integrates cleanly with **Bevy**:

```rust
use bevy::prelude::*;
use framealloc::bevy::SmartAllocPlugin;

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_plugins(SmartAllocPlugin::default())
        .run();
}
```

This automatically:

* Inserts the allocator as a Bevy resource
* Resets frame arenas at frame boundaries
* Works across Bevy's parallel systems

Inside a system:

```rust
fn my_system(alloc: Res<framealloc::bevy::AllocResource>) {
    let tmp = alloc.frame_alloc::<TempData>();
    // Use tmp...
}
```

No lifetimes exposed. No unsafe in user code. No boilerplate.

---

## What `framealloc` is **not**


To set expectations clearly:

❌ Not a global allocator replacement  
❌ Not a garbage collector  
❌ Not a drop-in replacement for `Vec`  
❌ Not optimized for long-lived arbitrary object graphs  

If you need:

* General heap allocation → use the standard allocator
* Reference-counted sharing → use `Arc`
* Data structures with unknown lifetimes → use `Vec` / `Box`

Use `framealloc` where **lifetime and performance are known**.

---

## Architecture Overview


```text
SmartAlloc (Arc)
 ├── GlobalState (shared)
 │    ├── SystemHeap (mutex-protected, large allocations)
 │    ├── SlabRegistry (mutex-protected page pools)
 │    ├── BudgetManager (optional limits)
 │    └── GlobalStats (atomics)
 │
 └── ThreadLocalState (TLS, per thread)
      ├── FrameArena (bump allocator, no sync)
      ├── LocalPools (small-object free lists, no sync)
      ├── DeferredFreeQueue (lock-free cross-thread frees)
      └── ThreadStats (local counters)
```

**Key rule:**

> Allocation always tries thread-local memory first.

Global synchronization only occurs during:

* Slab refills (rare, batched)
* Large allocations (>4KB default)
* Cross-thread frees (deferred, amortized)

---

## Performance Characteristics


| Operation | Cost | Synchronization |
|-----------|------|-----------------|
| Frame allocation | O(1) | None |
| Frame reset | O(1) | None |
| Pool allocation | O(1) | None (local hit) |
| Pool refill | O(1) amortized | Mutex (rare) |
| Pool free | O(1) | None |
| Cross-thread free | O(1) | Lock-free queue |
| Large alloc/free | O(1) | Mutex |

This design favors:

* Predictability over throughput
* Cache locality
* Stable frame times

---

## Safety Model


* All unsafe code is isolated inside `allocators/` module
* Public API is fully safe Rust
* Frame memory is invalidated explicitly at `end_frame()`
* Debug builds poison freed memory with `0xCD` pattern
* Optional allocation backtraces for leak detection

---

## Feature Flags


```toml
[features]
default = []

# Use parking_lot for faster mutexes

parking_lot = ["dep:parking_lot"]

# Bevy integration

bevy = ["dep:bevy_ecs", "dep:bevy_app"]

# Debug features: memory poisoning, allocation backtraces

debug = ["dep:backtrace"]
```

---

## Advanced Features


### Memory Budgets (Per-Tag Limits)


Track and limit memory usage by subsystem:

```rust
use framealloc::{SmartAlloc, AllocConfig, AllocationTag, BudgetManager};

let config = AllocConfig::default().with_budgets(true);
let alloc = SmartAlloc::new(config);

// Register budgets for subsystems
let rendering_tag = AllocationTag::new("rendering");
// Budget manager is accessed through global state
```

Budget events can trigger callbacks for monitoring:
- `SoftLimitExceeded` - Warning threshold crossed
- `HardLimitExceeded` - Allocation may fail
- `NewPeak` - High water mark updated

### Streaming Allocator


For large assets loaded incrementally (textures, meshes, audio):

```rust
use framealloc::{StreamingAllocator, StreamPriority};

let streaming = StreamingAllocator::new(64 * 1024 * 1024); // 64MB budget

// Reserve space for an asset
let id = streaming.reserve(1024 * 1024, StreamPriority::Normal).unwrap();

// Load data incrementally
let ptr = streaming.begin_load(id).unwrap();
// ... write data to ptr ...
streaming.report_progress(id, bytes_loaded);
streaming.finish_load(id);

// Access the data
let data = streaming.access(id).unwrap();

// Automatic eviction under memory pressure (LRU + priority)
```

### Diagnostics UI Hooks


For integration with imgui, egui, or custom debug UIs:

```rust
use framealloc::diagnostics::{DiagnosticsHooks, DiagnosticsEvent};

let mut hooks = DiagnosticsHooks::new();

// Register event listeners
hooks.add_listener(|event| {
    match event {
        DiagnosticsEvent::FrameBegin { frame_number } => { /* ... */ }
        DiagnosticsEvent::MemoryPressure { current, limit } => { /* ... */ }
        _ => {}
    }
});

// Get graph data for visualization
let graph_data = hooks.get_memory_graph_data(100);
```

Snapshot history provides time-series data for memory graphs.

### Handle-Based Allocation


Stable handles that survive memory relocation:

```rust
use framealloc::{HandleAllocator, Handle};

let allocator = HandleAllocator::new();

// Allocate and get a handle (not a raw pointer)
let handle: Handle<MyData> = allocator.alloc().unwrap();

// Resolve handle to pointer when needed
let ptr = allocator.resolve_mut(handle).unwrap();
unsafe { *ptr = MyData::new(); }

// Pin to prevent relocation during critical sections
allocator.pin(handle);
// ... use raw pointer safely ...
allocator.unpin(handle);

// Defragment memory (relocates unpinned allocations)
let relocations = allocator.defragment();

// Handle remains valid after relocation
let ptr = allocator.resolve(handle).unwrap();
```

### Allocation Groups


Free multiple allocations at once:

```rust
use framealloc::SmartAlloc;

let alloc = SmartAlloc::with_defaults();
let groups = alloc.groups();

// Create a group for level assets
let level_group = groups.create_group("level_1_assets");

// Allocate into the group
groups.alloc_val(level_group, texture_data);
groups.alloc_val(level_group, mesh_data);
groups.alloc_val(level_group, audio_data);

// Free everything at once when unloading level
groups.free_group(level_group);
```

### Safe Wrapper Types


RAII wrappers for automatic memory management:

```rust
use framealloc::SmartAlloc;

let alloc = SmartAlloc::with_defaults();

// FrameBox - valid until end_frame()
alloc.begin_frame();
let data = alloc.frame_box(MyStruct::new()).unwrap();
println!("{}", data.field); // Deref works
alloc.end_frame();

// PoolBox - auto-freed on drop
{
    let boxed = alloc.pool_box(123u64).unwrap();
    // Use boxed...
} // Freed here

// HeapBox - auto-freed on drop
{
    let large = alloc.heap_box([0u8; 8192]).unwrap();
    // Use large...
} // Freed here
```

### Profiler Integration


Hooks for Tracy, Optick, or custom profilers:

```rust
use framealloc::diagnostics::{ProfilerHooks, MemoryEvent};

let mut hooks = ProfilerHooks::new();

hooks.set_callback(|event| {
    match event {
        MemoryEvent::Alloc { ptr, size, tag } => {
            // Report to profiler
        }
        MemoryEvent::Free { ptr } => {
            // Report to profiler
        }
        _ => {}
    }
});
```

---

## v0.2.0 Features


### Frame Phases


Divide frames into named phases for profiling and diagnostics:

```rust
alloc.begin_frame();

alloc.begin_phase("physics");
let contacts = alloc.frame_alloc::<[Contact; 256]>();
// All allocations tracked under "physics"
alloc.end_phase();

alloc.begin_phase("render");
let verts = alloc.frame_alloc::<[Vertex; 4096]>();
alloc.end_phase();

alloc.end_frame();
```

**Features:**
- Zero overhead when not using phases
- Nested phase support
- Per-phase allocation statistics
- Integrates with diagnostics and profiler hooks

**Use with RAII guard:**
```rust
{
    let _phase = alloc.phase_scope("ai");
    // allocations here are in "ai" phase
} // phase ends automatically
```

### Frame Checkpoints


Save and rollback speculative allocations:

```rust
alloc.begin_frame();

let checkpoint = alloc.frame_checkpoint();

// Speculative allocations
let result = try_complex_operation();

if result.is_err() {
    alloc.rollback_to(checkpoint); // Undo all allocations
}

alloc.end_frame();
```

**Speculative blocks:**
```rust
let result = alloc.speculative(|| {
    let data = alloc.frame_alloc::<LargeData>();
    if validate(data).is_err() {
        return Err("validation failed");
    }
    Ok(process(data))
});
// Automatically rolled back on Err
```

**Use cases:**
- Pathfinding with dead-end rollback
- Physics with speculative contacts
- UI layout with try/fail patterns

### Frame Collections


Bounded, frame-local collections:

```rust
// FrameVec - fixed capacity vector
let mut entities = alloc.frame_vec::<Entity>(128);
entities.push(entity1);
entities.push(entity2);

for entity in entities.iter() {
    process(entity);
}
// Freed at end_frame()
```

```rust
// FrameMap - fixed capacity hash map
let mut lookup = alloc.frame_map::<EntityId, Transform>(64);
lookup.insert(id, transform);

if let Some(t) = lookup.get(&id) {
    use_transform(t);
}
```

**Properties:**
- Cannot grow beyond initial capacity
- Cannot escape the frame (lifetime-bound)
- Full iterator support
- Familiar API (push, pop, get, iter)

### Tagged Allocations


First-class allocation attribution:

```rust
alloc.with_tag("ai", |alloc| {
    let scratch = alloc.frame_alloc::<AIScratch>();
    // Allocation attributed to "ai" tag
    
    alloc.with_tag("pathfinding", |alloc| {
        let nodes = alloc.frame_alloc::<[Node; 256]>();
        // Nested: attributed to "ai::pathfinding"
    });
});

// Check current tag
println!("Tag: {:?}", alloc.current_tag());
println!("Path: {}", alloc.tag_path()); // "ai::pathfinding"
```

**Benefits:**
- Automatic budget attribution
- Better profiling granularity
- Clearer diagnostics

### Scratch Pools


Cross-frame reusable memory:

```rust
// Get or create a named pool
let pool = alloc.scratch_pool("pathfinding");

// Allocate (persists across frames)
let nodes = pool.alloc::<[PathNode; 1024]>();

// Use across multiple frames...

// Reset when done (e.g., level unload)
pool.reset();
```

**Registry access:**
```rust
let scratch = alloc.scratch();

// Get stats for all pools
for stat in scratch.stats() {
    println!("{}: {} / {} bytes", stat.name, stat.allocated, stat.capacity);
}

// Reset all pools
scratch.reset_all();
```

**Use cases:**
- Pathfinding node storage
- Level-specific allocations
- Subsystem scratch memory that outlives frames

---

## v0.3.0: Frame Retention & Promotion


### Overview


Frame allocations normally vanish at `end_frame()`. The retention system lets allocations optionally "escape" to other allocators.

**Key principle:** This is NOT garbage collection. It's explicit, deterministic post-frame ownership transfer.

### Retention Policies


```rust
pub enum RetentionPolicy {
    Discard,                      // Default - freed at frame end
    PromoteToPool,                // Copy to pool allocator
    PromoteToHeap,                // Copy to heap allocator  
    PromoteToScratch(&'static str), // Copy to named scratch pool
}
```

### Basic Usage


```rust
// Allocate with retention policy
let mut data = alloc.frame_retained::<NavMesh>(RetentionPolicy::PromoteToPool);
data.calculate_paths();

// At frame end, get promoted allocations
let result = alloc.end_frame_with_promotions();

for item in result.promoted {
    match item {
        PromotedAllocation::Pool { ptr, size, .. } => {
            // Data now lives in pool allocator
        }
        PromotedAllocation::Heap { ptr, size, .. } => {
            // Data now lives on heap
        }
        PromotedAllocation::Failed { reason, meta } => {
            // Promotion failed (budget exceeded, etc.)
            eprintln!("Failed to promote {}: {}", meta.type_name, reason);
        }
        _ => {}
    }
}
```

### Importance Levels (Semantic Sugar)


For more intuitive usage:

```rust
pub enum Importance {
    Ephemeral,   // → Discard
    Reusable,    // → PromoteToPool
    Persistent,  // → PromoteToHeap
    Scratch(n),  // → PromoteToScratch(n)
}

// Usage
let path = alloc.frame_with_importance::<Path>(Importance::Reusable);
let config = alloc.frame_with_importance::<Config>(Importance::Persistent);
```

### Frame Summary Diagnostics


Get detailed statistics about what happened at frame end:

```rust
let result = alloc.end_frame_with_promotions();
let summary = result.summary;

println!("Frame Summary:");
println!("  Discarded: {} bytes ({} allocs)", 
    summary.discarded_bytes, summary.discarded_count);
println!("  Promoted to pool: {} bytes ({} allocs)", 
    summary.promoted_pool_bytes, summary.promoted_pool_count);
println!("  Promoted to heap: {} bytes ({} allocs)", 
    summary.promoted_heap_bytes, summary.promoted_heap_count);
println!("  Failed: {} allocs", summary.failed_count);

// Breakdown by failure reason
let failures = &summary.failures_by_reason;
if failures.budget_exceeded > 0 {
    println!("    Budget exceeded: {}", failures.budget_exceeded);
}
if failures.scratch_pool_full > 0 {
    println!("    Scratch pool full: {}", failures.scratch_pool_full);
}
```

### Integration with Tags


Retained allocations preserve their tag attribution:

```rust
alloc.with_tag("ai", |alloc| {
    let data = alloc.frame_retained::<AIState>(RetentionPolicy::PromoteToPool);
    // When promoted, data retains "ai" tag for budgeting
});
```

### Design Principles


| Principle | Implementation |
|-----------|----------------|
| **Explicit** | Must opt-in per allocation |
| **Deterministic** | All decisions at `end_frame()` |
| **Bounded** | Subject to budgets and limits |
| **No Magic** | No heuristics or auto-promotion |

### When to Use Retention


| Scenario | Recommendation |
|----------|----------------|
| Pathfinding result might be reused | `Reusable` / `PromoteToPool` |
| Computed data proved useful | `Reusable` / `PromoteToPool` |
| Config loaded during frame | `Persistent` / `PromoteToHeap` |
| Subsystem scratch that persists | `Scratch("name")` |
| Truly temporary data | `Ephemeral` / `Discard` (default) |

### API Reference


```rust
// Allocate with retention
fn frame_retained<T>(&self, policy: RetentionPolicy) -> FrameRetained<'_, T>

// Allocate with importance (sugar)
fn frame_with_importance<T>(&self, importance: Importance) -> FrameRetained<'_, T>

// End frame and process promotions
fn end_frame_with_promotions(&self) -> PromotionResult

// End frame and get summary only
fn end_frame_with_summary(&self) -> FrameSummary

// Get pending retained count
fn retained_count(&self) -> usize

// Clear retained without processing
fn clear_retained(&self)
```

---

## v0.6.0: Explicit Thread Coordination & Frame Observability


### Design Philosophy


v0.6.0 makes the existing cross-thread behavior **explicit** and **controllable** while staying true to framealloc's core principles:

| Principle | How v0.6.0 Honors It |
|-----------|---------------------|
| **Deterministic** | Bounded queues, explicit barriers, predictable costs |
| **Frame-based** | All features center on frame lifecycle |
| **Explicit** | TransferHandle, budget policies, manual processing |
| **Predictable** | No hidden costs, configurable overhead |
| **Scales ST→MT** | Zero cost when features unused |

### TransferHandle: Explicit Cross-Thread Transfers


Previously, cross-thread allocations were handled silently via the deferred free queue. v0.6.0 adds explicit declaration of transfer intent:

```rust
use framealloc::{SmartAlloc, TransferHandle};

// Allocate with declared transfer intent
let handle: TransferHandle<PhysicsResult> = alloc.frame_box_for_transfer(result);

// Send to worker thread - transfer is explicit
worker_channel.send(handle);

// On worker thread: explicitly accept ownership
let data = handle.receive();
```

**Key properties:**
- Transfer intent is visible in the type system
- Ownership transfer is explicit, not implicit
- Dropped handles without receiving trigger warnings (debug mode)

### FrameBarrier: Deterministic Multi-Thread Sync


Coordinate frame boundaries across threads without races:

```rust
use framealloc::FrameBarrier;
use std::sync::Arc;

// Create barrier for main + 2 workers
let barrier = FrameBarrier::new(3);

// Each thread signals when frame work complete
barrier.signal_frame_complete();

// Coordinator waits for all, then resets
barrier.wait_all();
alloc.end_frame();
barrier.reset();
```

**Builder pattern:**
```rust
let barrier = FrameBarrierBuilder::new()
    .with_thread("main")
    .with_thread("physics")
    .with_thread("rendering")
    .build();
```

### Per-Thread Frame Budgets


Explicit per-thread memory limits with deterministic exceeded behavior:

```rust
use framealloc::{ThreadBudgetConfig, BudgetExceededPolicy};

// Configure per-thread limits
let config = ThreadBudgetConfig {
    frame_budget: 8 * 1024 * 1024,  // 8 MB
    frame_exceeded_policy: BudgetExceededPolicy::Fail,
    warning_threshold: 80,  // Warn at 80%
    ..Default::default()
};

alloc.set_thread_budget_config(thread_id, config);

// Check before large allocation
if alloc.frame_remaining() < large_size {
    // Handle gracefully
}
```

**Policies:**
| Policy | Behavior |
|--------|----------|
| `Fail` | Return null/error |
| `Warn` | Log warning, allow |
| `Allow` | Silent allow |
| `Promote` | Attempt promotion to larger allocator |

### Deferred Processing Control


Control when and how cross-thread frees are processed:

```rust
use framealloc::{DeferredConfig, DeferredProcessing, QueueFullPolicy};

// Bounded queue with explicit capacity
let config = DeferredConfig::bounded(1024)
    .full_policy(QueueFullPolicy::ProcessImmediately);

// Incremental processing (amortized cost per alloc)
let config = DeferredConfig::incremental(16);

// Full manual control
alloc.set_deferred_processing(DeferredProcessing::Explicit);
alloc.process_deferred_frees(64);  // Process up to 64
```

**Queue policies:**
| Policy | Behavior |
|--------|----------|
| `ProcessImmediately` | Block and drain |
| `DropOldest` | Lossy but non-blocking |
| `Fail` | Caller handles |
| `Grow` | Unbounded (legacy) |

### Frame Lifecycle Events


Opt-in observability with zero overhead when disabled:

```rust
use framealloc::{FrameEvent, LifecycleManager};

alloc.enable_lifecycle_tracking();

alloc.on_frame_event(|event| match event {
    FrameEvent::FrameBegin { thread_id, frame_number, .. } => {
        println!("Frame {} started on {:?}", frame_number, thread_id);
    }
    FrameEvent::CrossThreadFreeQueued { from, to, size } => {
        println!("Cross-thread: {:?} -> {:?}, {} bytes", from, to, size);
    }
    FrameEvent::FrameEnd { duration_us, peak_memory, .. } => {
        println!("Frame took {}μs, peak {} bytes", duration_us, peak_memory);
    }
    _ => {}
});

// Get per-thread statistics
let stats = alloc.thread_frame_stats(thread_id);
println!("Frames: {}, Peak: {} bytes", stats.frames_completed, stats.peak_memory);
```

### New Diagnostic Codes (FA2xx)


| Code | Severity | Description |
|------|----------|-------------|
| FA201 | Error | Cross-thread frame access without explicit transfer |
| FA202 | Warning | Thread not in FrameBarrier but shares frame boundary |
| FA203 | Hint | Thread allocates without budget configured |
| FA204 | Warning | Pattern may overflow deferred queue |
| FA205 | Error | `end_frame()` called without barrier synchronization |

### Performance Characteristics


When disabled (default): **Zero overhead**

When enabled:
| Feature | Overhead |
|---------|----------|
| TransferHandle | ~10ns per transfer |
| FrameBarrier | ~50ns per signal |
| Budget tracking | ~5ns per allocation |
| Lifecycle events | ~100ns per event (callback overhead) |

---

## v0.5.1: Unified Versioning & cargo-fa Enhancements


### Version Note


Starting with v0.5.1, `framealloc` and `cargo-fa` share version numbers to simplify tracking. This version bump reflects:

1. **Tooling parity** — The `cargo-fa` static analyzer is now a mature companion tool
2. **Documentation overhaul** — README professionally reformatted, documentation updated
3. **Ecosystem alignment** — Library and tool versions now stay in sync

**No runtime code changes** were made to the core allocator in this release. The frame arena, pools, and all allocation APIs remain identical to v0.4.0.

### cargo-fa v0.5.1 Features


Extended output formats for CI integration:
- `--format junit` — JUnit XML for test reporters
- `--format checkstyle` — Checkstyle XML for Jenkins

New filtering options:
- `--deny <CODE>` — Treat specific diagnostic as error
- `--allow <CODE>` — Suppress specific diagnostic
- `--exclude <PATTERN>` — Skip paths matching glob
- `--fail-fast` — Stop on first error

New subcommands:
- `cargo fa explain FA601` — Detailed explanation with examples
- `cargo fa show src/file.rs` — Single-file analysis
- `cargo fa list` — List all diagnostic codes
- `cargo fa init` — Generate `.fa.toml` configuration

Optimized `--all` check ordering runs fast checks first for better fail-fast behavior.

---

## v0.5.0: Static Analysis with cargo-fa


The `cargo-fa` tool provides build-time detection of memory intent violations. See the [cargo-fa README](cargo-fa/README.md) for full documentation.

---

## v0.4.0: Memory Behavior Filter


### Overview


The behavior filter detects "bad memory" — allocations that **violate their declared intent**. This is NOT about unsafe memory; it's about catching patterns like:

- Frame allocations that behave like long-lived data
- Pool allocations used as scratch (freed same frame)
- Excessive promotion churn
- Heap allocations in hot paths

### Enabling the Filter


```rust
// Enable tracking (disabled by default, zero overhead when off)
alloc.enable_behavior_filter();

// Run your game loop
for _ in 0..1000 {
    alloc.begin_frame();
    
    alloc.with_tag("physics", |alloc| {
        let scratch = alloc.frame_alloc::<PhysicsScratch>();
        // ...
    });
    
    alloc.end_frame();
}

// Analyze behavior
let report = alloc.behavior_report();
println!("{}", report.summary());

for issue in &report.issues {
    eprintln!("{}", issue);
}
```

### Diagnostic Codes


| Code | Severity | Meaning |
|------|----------|---------|
| FA501 | Warning | Frame allocation survives too long (avg lifetime > threshold) |
| FA502 | Warning | High frame survival rate (>50% survive beyond frame) |
| FA510 | Hint | Pool allocation used as scratch (>80% freed same frame) |
| FA520 | Warning | Promotion churn (>0.5 promotions/frame) |
| FA530 | Warning | Heap allocation in hot path (frequent heap allocs) |

### Example Output


```
[FA501] warning: frame allocation behaves like long-lived data
  tag: ai::pathfinding
  observed: avg lifetime: 128.0 frames
  threshold: expected < 60 frames
  suggestion: Consider using pool_alloc() or scratch_pool()

[FA520] warning: Excessive promotion churn detected
  tag: rendering::meshes
  observed: 0.75 promotions/frame
  threshold: expected < 0.50/frame
  suggestion: Consider allocating directly in the target allocator
```

### Configurable Thresholds


```rust
// Default thresholds
let default = BehaviorThresholds::default();

// Strict thresholds for CI/testing
let strict = BehaviorThresholds::strict();

// Relaxed thresholds for development
let relaxed = BehaviorThresholds::relaxed();

// Custom thresholds
let custom = BehaviorThresholds {
    frame_survival_frames: 120,        // Frames before warning
    frame_survival_rate: 0.3,          // 30% survival rate
    pool_same_frame_free_rate: 0.9,    // 90% freed same frame
    promotion_churn_rate: 0.3,         // 0.3 promotions/frame
    heap_in_hot_path_count: 50,        // 50 heap allocs
    min_samples: 20,                   // Min allocs before analysis
};
```

### Per-Tag Tracking


Statistics are tracked **per-tag**, not per-allocation. This keeps memory overhead at O(tags) instead of O(allocations):

```rust
// Each unique (tag, alloc_kind) pair gets its own stats
pub struct TagBehaviorStats {
    pub tag: &'static str,
    pub kind: AllocKind,
    pub total_allocs: u64,
    pub survived_frame_count: u64,
    pub promotion_count: u64,
    pub same_frame_frees: u64,
    // ...
}
```

### CI Integration


```bash
# Enable strict mode in CI

FRAMEALLOC_STRICT=warning cargo test

# Or programmatically

alloc.enable_behavior_filter();
// ... run tests ...
let report = alloc.behavior_report();
if report.has_warnings() {
    std::process::exit(1);
}
```

### Design Principles


| Principle | Implementation |
|-----------|----------------|
| **Opt-in** | Disabled by default, no overhead |
| **Per-tag** | O(tags) memory, not O(allocations) |
| **Actionable** | Every issue includes a suggestion |
| **Not a cop** | Advises, doesn't block |
| **Deterministic** | Same inputs → same outputs |

---

## Diagnostics System


`framealloc` provides **allocator-specific diagnostics** at build time, compile time, and runtime.
It does not replace Rust compiler warnings — it explains *engine-level* mistakes.

### Diagnostic Codes Reference


All diagnostics use codes for easy searching and documentation:

| Code | Category | Meaning |
|------|----------|---------|
| **FA001** | Frame | Frame allocation used outside active frame |
| **FA002** | Frame | Frame memory reference escaped scope |
| **FA003** | Frame | Frame arena exhausted |
| **FA101** | Bevy | SmartAllocPlugin not registered |
| **FA102** | Bevy | Frame hooks not executed this frame |
| **FA201** | Thread | Invalid cross-thread memory free |
| **FA202** | Thread | Thread-local state accessed before init |
| **FA301** | Budget | Global memory budget exceeded |
| **FA302** | Budget | Tag-specific budget exceeded |
| **FA401** | Handle | Invalid or freed handle accessed |
| **FA402** | Stream | Streaming allocator budget exhausted |
| **FA901** | Internal | Internal allocator error (report bug) |

### Runtime Diagnostics


Diagnostics are emitted to stderr in debug builds:

```rust
use framealloc::{fa_diagnostic, fa_emit, DiagnosticKind};

// Emit a custom diagnostic
fa_diagnostic!(
    Error,
    code = "FA001",
    message = "frame allocation used outside an active frame",
    note = "this allocation was requested after end_frame()",
    help = "call alloc.begin_frame() before allocating"
);

// Emit a predefined diagnostic
fa_emit!(FA001);

// Emit with context (captures thread, frame number, etc.)
fa_emit_ctx!(FA001);
```

**Sample output:**

```
[framealloc][FA001] error: frame allocation used outside an active frame
  note: this allocation was requested when no frame was active
  help: call alloc.begin_frame() before allocating, or use pool_alloc()/heap_alloc()
```

### Compile-Time Diagnostics


For errors detectable at compile time:

```rust
// Hard compiler error with formatted message
fa_compile_error!(
    code = "FA101",
    message = "Bevy support enabled but plugin not registered",
    help = "add .add_plugins(SmartAllocPlugin) to your App"
);
```

### Strict Mode (CI Integration)


Configure diagnostics to panic instead of warn — useful for CI:

```rust
use framealloc::{set_strict_mode, StrictMode, StrictModeGuard};

// Panic on any error diagnostic
set_strict_mode(StrictMode::PanicOnError);

// Or use a guard for scoped strict mode
{
    let _guard = StrictModeGuard::panic_on_error();
    // Errors in this scope will panic
}
// Back to normal behavior
```

**Environment variable:**

```bash
# In CI

FRAMEALLOC_STRICT=error cargo test

# Options: warn, error, warning (panics on warnings too)

```

### Conditional Assertions


Assert conditions with automatic diagnostics:

```rust
use framealloc::fa_assert;

// Emits FA001 if condition is false
fa_assert!(frame_active, FA001);

// With context capture
fa_assert!(frame_active, FA001, ctx);
```

### Diagnostic Context


Diagnostics can capture runtime context:

```rust
use framealloc::diagnostics::{DiagContext, set_bevy_context};

// Mark that we're in a Bevy app
set_bevy_context(true);

// Capture current context
let ctx = DiagContext::capture();
println!("Frame: {}, Thread: {:?}", ctx.frame_number, ctx.thread_id);
```

Context includes:
- Whether Bevy integration is active
- Current frame number
- Whether a frame is active
- Thread ID and name
- Whether this is the main thread

---

## Build-Time Diagnostics


The `build.rs` script provides helpful messages during compilation:

### Feature Detection


```
[framealloc] ℹ️  Bevy integration enabled
[framealloc]    Remember to add SmartAllocPlugin to your Bevy App:
[framealloc]      app.add_plugins(framealloc::bevy::SmartAllocPlugin::default())
```

### Debug Mode Hints


```
[framealloc] ℹ️  Debug features enabled
[framealloc]    Debug mode provides:
[framealloc]      • Memory poisoning (freed memory filled with 0xCD)
[framealloc]      • Allocation backtraces (for leak detection)
[framealloc]      • Extended validation checks
```

### Release Build Recommendations


```
[framealloc] ℹ️  Building in release mode
[framealloc]    Tip: Consider enabling 'parking_lot' for better mutex performance
```

### Quick Reference (printed during build)


```
[framealloc] ────────────────────────────────────────
[framealloc] ℹ️  framealloc Quick Reference
[framealloc] ────────────────────────────────────────
[framealloc]    Frame allocation (fastest, reset per frame):
[framealloc]      alloc.begin_frame();
[framealloc]      let data = alloc.frame_box(value);
[framealloc]      alloc.end_frame();
```

---

## Complete Feature Flags


```toml
[features]
default = []

# Use parking_lot for faster mutexes

parking_lot = ["dep:parking_lot"]

# Bevy integration

bevy = ["dep:bevy_ecs", "dep:bevy_app"]

# Debug features: memory poisoning, allocation backtraces

debug = ["dep:backtrace"]

# Tracy profiler integration

tracy = ["dep:tracy-client"]

# Nightly: std::alloc::Allocator trait implementations

nightly = []

# Enhanced runtime diagnostics

diagnostics = []
```

---

## std::alloc::Allocator Trait (Nightly)


With the `nightly` feature, use framealloc with standard collections:

```rust
#![feature(allocator_api)]


use framealloc::{SmartAlloc, FrameAllocator};

let alloc = SmartAlloc::with_defaults();
alloc.begin_frame();

// Use with Vec
let frame_alloc = FrameAllocator::new();
let mut vec: Vec<u32, _> = Vec::new_in(frame_alloc);
vec.push(42);

alloc.end_frame();
```

**Enable with:**

```toml
framealloc = { version = "0.1", features = ["nightly"] }
```

```bash
rustup override set nightly
```

---

## Common Patterns


### Pattern 1: Game Loop


```rust
let alloc = SmartAlloc::with_defaults();

loop {
    alloc.begin_frame();
    
    // All frame allocations here
    let scratch = alloc.frame_box(ScratchData::new())?;
    process(&scratch);
    
    alloc.end_frame(); // All frame memory freed
}
```

### Pattern 2: Level Loading


```rust
let alloc = SmartAlloc::with_defaults();
let groups = alloc.groups();

// Load level
let level_group = groups.create_group("level_1");
for asset in level_assets {
    groups.alloc_val(level_group, load_asset(asset)?);
}

// ... play level ...

// Unload - free everything at once
groups.free_group(level_group);
```

### Pattern 3: Streaming Assets


```rust
let streaming = alloc.streaming();

// Reserve space before loading
let texture_id = streaming.reserve(texture_size, StreamPriority::High)?;

// Load asynchronously
let ptr = streaming.begin_load(texture_id)?;
load_texture_async(ptr, texture_id, |progress| {
    streaming.report_progress(texture_id, progress);
});
streaming.finish_load(texture_id);

// Access when ready
if let Some(data) = streaming.access(texture_id) {
    use_texture(data);
}
```

### Pattern 4: Safe Wrappers


```rust
let alloc = SmartAlloc::with_defaults();

// Prefer safe wrappers over raw pointers
let pool_data = alloc.pool_box(MyData::new())?;  // Auto-freed on drop
let heap_data = alloc.heap_box(LargeData::new())?;  // Auto-freed on drop

alloc.begin_frame();
let frame_data = alloc.frame_box(TempData::new())?;  // Valid until end_frame
// Use frame_data...
alloc.end_frame();
```

---

## Troubleshooting


### "Frame allocation used outside an active frame" (FA001)


**Problem:** You called `frame_alloc()` without `begin_frame()`.

**Fix:**
```rust
alloc.begin_frame();  // Add this
let data = alloc.frame_alloc::<T>();
// ...
alloc.end_frame();
```

**Or use persistent allocation:**
```rust
let data = alloc.pool_box(value);  // Lives until dropped
```

### "Bevy plugin missing" (FA101)


**Problem:** Bevy feature enabled but plugin not added.

**Fix:**
```rust
App::new()
    .add_plugins(SmartAllocPlugin::default())  // Add this
    .run();
```

### "Frame arena exhausted" (FA003)


**Problem:** Too many frame allocations for the arena size.

**Fix:**
```rust
let config = AllocConfig::default()
    .with_frame_arena_size(64 * 1024 * 1024);  // Increase to 64MB
let alloc = SmartAlloc::new(config);
```

### Memory appears corrupted


**Debug with poisoning:**
```toml
framealloc = { version = "0.1", features = ["debug"] }
```

Freed memory is filled with `0xCD`. If you see this pattern, you're using freed memory.

### Finding memory leaks


**Enable backtraces:**
```toml
framealloc = { version = "0.1", features = ["debug"] }
```

```rust
// In debug builds, leaked allocations are tracked
let stats = alloc.stats();
println!("Active allocations: {}", stats.allocation_count - stats.deallocation_count);
```

---

## When should I use `framealloc`?


You should consider `framealloc` if you are building:

* A game engine
* A renderer
* A physics or simulation engine
* A real-time or embedded system
* A performance-critical tool with frame-like execution

---

## Philosophy


> **Make memory lifetime explicit.**  
> **Make the fast path obvious.**  
> **Make the slow path predictable.**

`framealloc` exists to give Rust game developers the same level of control engine developers expect — without sacrificing safety or ergonomics.

---

## License


Licensed under either of:

* Apache License, Version 2.0
* MIT license

at your option.