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
//! RAII guards for safe manual memory management.
//!
//! # PERF-002: Allocation Guard
//!
//! Provides panic-safe allocation patterns for code that must use
//! manual memory management (e.g., cache-aligned buffers).
//!
//! # Usage
//!
//! ```rust,ignore
//! use velesdb_core::alloc_guard::AllocGuard;
//! use std::alloc::Layout;
//!
//! let layout = Layout::from_size_align(1024, 64).unwrap();
//! let guard = AllocGuard::new(layout)?;
//!
//! // Use guard.as_ptr() for operations...
//! // If panic occurs, memory is automatically freed
//!
//! // Transfer ownership when done
//! let ptr = guard.into_raw();
//! ```
use ;
use NonNull;
use ;
/// Default ceiling for a single raw allocation, in bytes: **1 TiB**.
///
/// # Rationale (#899 + follow-up)
///
/// This is purely a *backstop against pathological / attacker-controlled /
/// overflow-class sizes*, **not** a workload limit. It must NEVER reject a
/// legitimate large index.
///
/// `ContiguousVectors` is a **single monolithic buffer holding ALL vectors of an
/// HNSW graph** — it is not sharded. The previous 16 GiB ceiling therefore
/// falsely rejected legitimate ingests: a collection only needs ~5.6M vectors at
/// 768D to exceed 16 GiB in one buffer, and the geometric doubling in
/// `ensure_capacity`/`resize` tripped even earlier (~2.8M @768D, when the next
/// doubling crosses 16 GiB). Worse, an index built+persisted under the old code
/// with > 16 GiB of vectors became **un-loadable** after upgrade.
///
/// 1 TiB is chosen because:
/// - It is far above any single in-RAM vector buffer a real deployment builds
/// (~358M vectors at 768D, ~715M at 384D), so legitimate workloads never trip
/// it; the OS allocator / OOM killer rejects genuinely-impossible sizes first.
/// - It still sits *vastly* below overflow-class requests: a wrapped `usize`
/// lands near `usize::MAX` (~16 EiB on 64-bit), four-plus orders of magnitude
/// above 1 TiB, so wrapped/absurd sizes are still cut off before they reach the
/// system allocator.
/// - The real overflow guard is the `checked_mul`/`checked_add` arithmetic in
/// [`ContiguousVectors::byte_size`](crate::perf_optimizations::ContiguousVectors)
/// and the insert/resize paths; this ceiling is a coarse secondary net.
///
/// Configurable at runtime via [`set_alloc_byte_limit`] if an operator
/// legitimately needs an even larger single allocation, or to harden it down.
///
/// On 32-bit / WASM targets `usize` tops out at ~4 GiB, so the 1 TiB literal
/// would overflow at compile time and the ceiling is meaningless anyway (the
/// allocator caps allocations well below it). There the backstop is disabled
/// (`usize::MAX`) and the OS allocator is the effective limit.
pub const DEFAULT_ALLOC_BYTE_LIMIT: usize = 1024 * 1024 * 1024 * 1024;
/// See the 64-bit variant above: disabled on 32-bit / WASM where 1 TiB would
/// overflow `usize` and the allocator is the effective ceiling.
pub const DEFAULT_ALLOC_BYTE_LIMIT: usize = usizeMAX;
/// Process-wide per-allocation byte ceiling, initialized to
/// [`DEFAULT_ALLOC_BYTE_LIMIT`]. See [`set_alloc_byte_limit`].
static ALLOC_BYTE_LIMIT: AtomicUsize = new;
/// Overrides the per-allocation byte ceiling enforced by [`AllocGuard`].
///
/// Use to raise the limit for genuinely huge single-buffer workloads, or lower
/// it to harden against pathological sizes. Affects all subsequent allocations
/// through [`AllocGuard::new`] / [`AllocGuard::new_zeroed`] and
/// [`check_alloc_bound`]. Passing `0` is treated as "no override" and restores
/// the default ceiling.
/// Returns the current per-allocation byte ceiling.
/// Runs `f` with the per-allocation ceiling raised to **at least** `min_bytes`,
/// restoring the previous ceiling afterward (even on panic).
///
/// Used by the persisted-index **load** path: the on-disk vector payload has
/// already been validated to fit within the actual file length (see
/// `validate_vectors_file_len`), so it is a *real, legitimately-built* size — it
/// must reload regardless of the process-wide backstop. Bounding the temporary
/// raise by the file-derived `min_bytes` (rather than removing the ceiling) keeps
/// the backstop meaningful: a corrupt oversized header is still rejected earlier
/// by the file-length check, and unrelated allocations during `f` are still
/// bounded by `max(previous_limit, min_bytes)`.
///
/// If the current ceiling already covers `min_bytes`, this is a transparent
/// pass-through with no mutation.
/// RAII helper that restores [`ALLOC_BYTE_LIMIT`] to a saved value on drop,
/// including during unwinding. Used by [`with_min_alloc_byte_limit`].
;
/// Validates that a requested allocation of `bytes` is within the configured
/// ceiling, *without* allocating.
///
/// Lets callers reject pathological sizes before building a [`Layout`] or
/// reserving a `Vec`. Thread this in front of resize / gather / reorder paths.
///
/// # Errors
///
/// Returns [`Error::AllocationFailed`](crate::error::Error::AllocationFailed) if
/// `bytes` exceeds [`alloc_byte_limit`].
/// RAII guard for raw allocations.
///
/// Ensures memory is deallocated if dropped, preventing leaks on panic.
/// Use `into_raw()` to take ownership and prevent deallocation.
// SAFETY: `AllocGuard` is `Send` because it owns an allocation handle only.
// - Condition 1: No aliasing references are stored, only pointer + layout metadata.
// - Condition 2: Mutation requires `&mut self`, preventing cross-thread races on the type.
// SAFETY: Heap allocations are not thread-affine; ownership transfer across threads is sound.
unsafe
// AllocGuard is NOT Sync - concurrent access to raw memory is unsafe
// (intentionally not implementing Sync)