165 lines
10 KiB
Markdown
165 lines
10 KiB
Markdown
# NEW Memory subsystem
|
||
|
||
Status: NEW design; no Memory source directory or target exists in the inspected
|
||
foundation inventory. All tasks are **PLANNED**. Baseline:
|
||
`f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24.
|
||
|
||
## Existing capabilities to reuse
|
||
|
||
[Containers ObjectPool/FixedPool](../../../include/Void/Containers/Pool.hpp) manage typed
|
||
objects; [BufferPool](../../../include/Void/Containers/BufferPool.hpp) recycles power-of-two
|
||
vector buffers. Their leases/deleters currently reference pool objects. These are
|
||
Containers APIs, not existing Memory resources. Their
|
||
[pool](../../../tests/standalone/Containers/Pool.cpp) and
|
||
[buffer-pool tests](../../../tests/standalone/Containers/BufferPool.cpp) provide fixtures
|
||
for later adapters. [Core Scope](../../../include/Void/Core/Scope.hpp) can supply lifetime
|
||
guards above a low-level resource without becoming an allocator implementation.
|
||
These source files were read; coverage reported no recorded graph gaps. No current
|
||
resource-accounting or allocator-performance claim is inferred from their existence.
|
||
|
||
## Owner, dependency and backend decisions
|
||
|
||
Memory owns allocation facilities under [C-01/C-04/C-05](../ARCHITECTURE.md). Select native
|
||
bounded arenas, tracking/budget resources and fixed-block free lists on top of standard
|
||
`std::pmr::memory_resource`. The foundation needs only the standard library. Typed object
|
||
pools, small vectors and lease semantics remain in Containers. Do not pull Containers,
|
||
Runtime, IO, Log or platform allocators into Memory. System may later provide an OS page
|
||
resource adapter above this contract; Memory must not require mmap or huge pages.
|
||
No replacement global operator new, process allocator interposition or mandatory
|
||
jemalloc/mimalloc backend is part of the initial design.
|
||
|
||
NEW proposed paths: `include/Void/Memory/Resource.hpp`, `Arena.hpp`, `BudgetResource.hpp`,
|
||
`BlockPool.hpp`, `src/Memory/module.cmake` and `tests/standalone/Memory/`. Their creation
|
||
is future feature work, not an artifact claimed by this documentation task.
|
||
|
||
## NEW API shape
|
||
|
||
Illustrative proposed declarations:
|
||
|
||
```cpp
|
||
namespace Void::Memory {
|
||
enum class AllocationError { invalid_alignment, size_overflow, exhausted,
|
||
upstream_failure, live_allocations };
|
||
struct ResourceStats {
|
||
std::size_t requested_live, committed_live, peak_committed;
|
||
std::uint64_t allocations, failures;
|
||
};
|
||
class BudgetResource : public std::pmr::memory_resource {
|
||
public:
|
||
explicit BudgetResource(std::size_t byte_limit,
|
||
std::pmr::memory_resource& upstream);
|
||
std::expected<void*, AllocationError>
|
||
try_allocate(std::size_t bytes, std::size_t alignment) noexcept;
|
||
ResourceStats stats() const noexcept;
|
||
// PMR virtual allocate/deallocate/equality overrides supplied by implementation.
|
||
};
|
||
class Arena {
|
||
public:
|
||
explicit Arena(std::span<std::byte> initial, std::size_t maximum_bytes,
|
||
std::pmr::memory_resource& upstream);
|
||
std::expected<void*, AllocationError> try_allocate(std::size_t, std::size_t) noexcept;
|
||
std::expected<void, AllocationError> reset();
|
||
};
|
||
}
|
||
```
|
||
|
||
Keep the compact enum allocation-free; Functional owns its optional error adaptation.
|
||
PMR `allocate()` throws `std::bad_alloc` on exhaustion as its standard contract requires;
|
||
`try_allocate` translates upstream allocation failure to the enum and does not allocate
|
||
diagnostics. Programmer misuse (wrong owner, byte size or alignment on deallocation)
|
||
is a contract violation with debug diagnostics, not silently ignored successful cleanup.
|
||
Resources compare equal only when their deallocation ownership domains are interchangeable.
|
||
|
||
## Allocation algorithms and ownership
|
||
|
||
BudgetResource admits committed bytes atomically before asking upstream. Charge requested
|
||
bytes plus resource-controlled alignment/header overhead, guard addition against overflow,
|
||
and undo the reservation if upstream fails. Current and high-water counts use the same
|
||
definitions. Standard upstream hidden allocator overhead/RSS is measured separately;
|
||
a resource limit does not falsely bound all process memory or allocations by arbitrary
|
||
user callbacks. Deallocate is noexcept and updates counters after returning memory to the
|
||
same upstream owner. Optional event observers receive compact records after bookkeeping
|
||
and outside locks; no dependency on a logging/export backend exists.
|
||
|
||
Arena uses checked aligned bump offsets in owned slabs. Initial profile: 64 KiB slabs,
|
||
maximum 16 MiB per arena, power-of-two geometric growth up to 1 MiB/slab. An empty initial
|
||
span requests the first owned slab lazily; a fixed-buffer mode has no upstream fallback.
|
||
Alignment must be a nonzero power of two; over-aligned requests use an appropriately
|
||
aligned slab and charge padding. Zero-byte allocation reserves one addressable byte,
|
||
making its accounting explicit. Reset invalidates all raw pointers; it is legal only
|
||
after clients release their objects/leases. The arena does not discover destructors of
|
||
raw allocations. A separate typed scope records destructors in reverse construction
|
||
order within a bounded metadata budget (4,096 registrations default).
|
||
|
||
Arena checkpoints contain resource identity, generation, slab and offset. Rewind accepts
|
||
only a current checkpoint with no surviving typed allocations after it; generation
|
||
validation rejects stale checkpoints. Do not imply rewind undoes externally visible
|
||
side effects. `reset()` on an arena with registered live leases returns `live_allocations`.
|
||
Bare raw-pointer clients obey the documented precondition; no runtime can prove every
|
||
raw pointer has gone away.
|
||
|
||
BlockPool preallocates slab metadata and uses a free-index list for fixed-size aligned
|
||
blocks. Default cap: 4,096 blocks and 16 MiB committed bytes, whichever is reached first.
|
||
Free/recycle performs no allocation. A single-thread resource is the default; a NEW
|
||
synchronized wrapper serializes admission/free and snapshots stats. Do not advertise
|
||
lock-free allocation. Idle trimming is explicit and never releases outstanding blocks.
|
||
Large-object fallback is opt-in, charged to the same budget and owner.
|
||
|
||
Borrowed `memory_resource*` must outlive every allocation, PMR container, final backend
|
||
completion and destructor using it. NEW `SharedResource` retains a stationary resource
|
||
control block for owning cross-component leases; it does not extend the lifetime of a
|
||
separately borrowed upstream. Containers' owning pool leases retain that state, while
|
||
embedded callers may choose documented borrowing. Runtime holds its resources through
|
||
stop-admission → cancel/drain → join → destroy-objects → destroy-resources. Memory owns
|
||
no threads and cannot itself cancel outstanding application work.
|
||
|
||
## Admission and performance policy
|
||
|
||
Aggregate resources may be nested (request within service within process). Charge every
|
||
owned allocation to each relevant parent once; avoid counting an arena slab both as its
|
||
own internal allocation and a duplicate child request in the same reported total.
|
||
Expose requested bytes and committed slab bytes separately. Cancellation/failure paths
|
||
must release reserved capacity even when construction above Memory throws.
|
||
|
||
Budget exhaustion reports before partial object construction. Callers may explicitly
|
||
wait for capacity through Async, but Memory never blocks on an executor or starts a
|
||
reclaimer thread. Zero cap allows no positive allocation. Unlimited policy is a named
|
||
tag, not zero. Sensitive erasure belongs to Security's buffer type: Memory reuse is not
|
||
a promise that prior bytes are scrubbed.
|
||
|
||
## Task DAG
|
||
|
||
| Task | Phase; dependencies | Scope and acceptance | Recommended role |
|
||
| --- | --- | --- | --- |
|
||
| S-MEMORY-01 | P0; existing pool inventory; shared C-04/C-05 | Define requested/committed accounting and resource lifetime fixtures; enumerate pool migrations without changing their APIs yet. | astra_implementer |
|
||
| S-MEMORY-02 | P1; S-MEMORY-01 | Add resource/budget/PMR contracts and failure-safe admission; zero/exact/overflow and concurrent cap tests show no leaked reservation. | sol_implementer |
|
||
| S-MEMORY-03 | P1; S-MEMORY-02 | Implement fixed/growing arenas, generation checkpoints and typed destructor scopes; over-alignment, failed growth and stale rewind tests pass. | sol_implementer |
|
||
| S-MEMORY-04 | P1; S-MEMORY-02 | Implement bounded block pool and synchronized wrapper; recycle allocates zero and trimming never touches live blocks. | sol_implementer |
|
||
| S-MEMORY-05 | P2; S-MEMORY-03–04; Containers lease contract | Add SharedResource and adapt typed pools without a reverse dependency; retained leases safely release after front-end owner destruction. | astra_implementer |
|
||
| S-MEMORY-06 | P3; S-MEMORY-05; Runtime shutdown gate | Validate embedded/managed teardown and allocator workload profiles; installed Memory-only consumer links with no runtime/backend packages. | sol_implementer |
|
||
|
||
## Validation, migration and rollback
|
||
|
||
CURRENT source tests above cover existing pools only; no Memory test or benchmark exists
|
||
or was run. PROPOSED checks require the NEW target/suites and supported toolchain:
|
||
allocation-failure injection at every upstream call; alignment 1 through over-aligned
|
||
types; SIZE_MAX arithmetic; zero-byte requests; destructor ordering; generation wrap;
|
||
cross-owner misuse diagnostics; concurrent admission/free; and shutdown with outstanding
|
||
leases. ASAN/UBSAN validate storage lifetime, TSAN the synchronized resource; invariants
|
||
also need deterministic counters and free-list model tests.
|
||
|
||
Profiles compare std::pmr defaults, bounded arena, fixed block and synchronized wrappers
|
||
for request parsing, coroutine/frame storage and buffer churn. Report p50/p95/p99,
|
||
allocations, throughput, committed/requested peaks, RSS/CPU and build cost under
|
||
[PERFORMANCE](../PERFORMANCE.md). Separate fresh-page cost from warmed recycle cost.
|
||
No allocator-speed claim is made in advance.
|
||
|
||
[Migration](../MIGRATION.md) introduces Memory independently, then replaces pool internals
|
||
behind tested Containers adapters. Caller-supplied PMR pointers remain explicitly borrowed;
|
||
no migration silently promotes them to owned. Rollback restores old pool implementations
|
||
and package selection after draining all new-resource allocations. Never free through
|
||
another allocator or unload a plugin generation while its resource/deleter is still used.
|
||
See [VALIDATION](../VALIDATION.md), [DEPENDENCIES](../DEPENDENCIES.md),
|
||
[DELIVERY](../DELIVERY.md), [requirements](../REQUIREMENTS.md),
|
||
[Containers](../modules/Containers.md) and [Runtime](Runtime.md).
|