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
//! Logical memory profiling for OMMX types.
//!
//! The public entry point is [`crate::Instance::logical_memory_profile`],
//! which returns a [`MemoryProfile`] that can be rendered as a folded-stack
//! string via its [`std::fmt::Display`] impl and consumed programmatically
//! through [`MemoryProfile::entries`] / [`MemoryProfile::total_bytes`].
//!
//! # Design philosophy
//!
//! - **Only leaf nodes emit byte counts.** Intermediate nodes delegate to
//! their children; aggregation is the collector's job. This eliminates
//! the inclusive/exclusive-bytes distinction and makes double-counting
//! structurally impossible.
//! - **Visitor pattern.** Each type's only responsibility is to describe
//! its logical structure to a visitor; output formats (folded stack,
//! totals, ...) live in visitor implementations.
//! - **Flexible granularity.** Each type decides how deep to decompose
//! itself — a struct may report every field, or collapse itself to one
//! leaf (e.g. ID wrappers that are just `size_of::<T>()`).
//!
//! # Internal use only
//!
//! The [`LogicalMemoryProfile`] trait, [`Path`]/`PathGuard` helpers and
//! related free functions are `pub(crate)`: they are implementation details
//! used within the `ommx` crate and are not part of the public API.
//! External consumers should interact with [`MemoryProfile`] via the
//! method on [`crate::Instance`].
//!
//! # Implementation notes
//!
//! These conventions are enforced by `#[derive(LogicalMemoryProfile)]`
//! (from the `ommx-derive` crate) and by the declarative
//! `impl_logical_memory_profile!` macro. Hand-written impls for
//! generic / enum / foreign types should follow them too.
//!
//! - **Naming: `Type.field`.** Each field's frame is
//! `"TypeName.field_name"`. Flamegraph frames then show both the
//! owning type and the field name, which makes the hierarchy
//! easy to read at a glance.
//!
//! - **Never write `size_of::<Self>()` at a struct leaf.** That would
//! double-count: the struct's stack slot already includes every field
//! by layout. Delegate to each field instead. Padding between fields
//! is the only thing missed — an acceptable trade-off.
//!
//! - **Stack vs heap.** Primitives and POD structs (`Bound`, `Kind`, ...)
//! emit a single leaf of `size_of::<T>()`. Collections emit a
//! `Type[stack]` leaf for their header (`size_of::<Vec<T>>()` etc.)
//! and then delegate to their elements; unused capacity is deliberately
//! ignored. `String` emits `size_of::<String>() + len()` (heap
//! bytes actually present).
//!
//! - **Aggregation.** Multiple visits to the same path accumulate in
//! [`MemoryProfile`]. So profiling a `BTreeMap<Id, T>` with 1000
//! entries produces one line per unique path, not 1000 duplicates.
//!
//! # Caveats
//!
//! This is a logical-structure estimation, not exact heap profiling.
//! Allocator overhead, internal fragmentation, and padding between
//! fields are not tracked. Unused `Vec` / `HashMap` capacity is
//! deliberately ignored — only bytes holding live data are counted.
//! For precise heap accounting use a dedicated profiler (jemalloc,
//! valgrind, heaptrack); this tool is for understanding proportions
//! and flamegraph visualization.
pub use Path;
use BTreeMap;
use fmt;
/// Types that provide logical memory profiling.
///
/// Implementations should enumerate their "logical memory leaves" by calling
/// `visitor.visit_leaf()` for each leaf node, while intermediate nodes should
/// delegate to their children.
///
/// The trait is declared `pub` so it can appear in the bound of `pub`
/// types within this crate (e.g. `ConstraintMetadataStore<ID>` requires
/// `ID: LogicalMemoryProfile`) without triggering the `private_bounds`
/// lint, and so `#[derive(LogicalMemoryProfile)]` can be used at every
/// struct that participates in profiling — the derive prevents
/// "added a new field, forgot to update the impl" drift that hand-
/// written impls invite. The enclosing module
/// (`crate::logical_memory`) is `pub(crate)`, so downstream crates
/// cannot reach the trait directly. The user-facing memory-profile
/// entry points are [`crate::Instance::logical_memory_profile`] and
/// [`crate::MemoryProfile`].
/// Visitor for logical memory leaf nodes.
/// Logical memory profile of a value.
///
/// This is the output type of [`crate::Instance::logical_memory_profile`].
/// Internally it is a flat map from logical path (e.g.
/// `["Instance", "objective", ...]`) to the number of bytes attributed to
/// that leaf.
///
/// # Caveats
///
/// Reported bytes are a logical-structure estimation, not exact heap
/// profiling: allocator overhead, padding, and unused collection capacity
/// are deliberately ignored. See the module docs for details. Use for
/// proportions and flamegraph visualization, not for total-allocation
/// accounting.
///
/// # Flamegraph workflow
///
/// The [`std::fmt::Display`] impl produces the folded-stack format read
/// by `flamegraph.pl` and `inferno`:
///
/// ```bash
/// # in a Rust program / test / example
/// std::fs::write("profile.txt", instance.logical_memory_profile().to_string())?;
///
/// # then, in the shell:
/// flamegraph.pl profile.txt > memory.svg
/// # or with inferno:
/// inferno-flamegraph < profile.txt > memory.svg
/// ```
///
/// External tools:
/// - `flamegraph.pl`: <https://github.com/brendangregg/FlameGraph>
/// - `inferno` (Rust): <https://github.com/jonhoo/inferno>
/// Renders the profile as folded stack format: each leaf on its own line as
/// `"frame1;frame2;...;frameN bytes"`, lines sorted for deterministic output.