Skip to content

Bug: lib/std/alloc.w destructors (naked Type.drop(mut self)) never run — arenas/pools leak (§2.4) #641

Closed

Description

@ehartford

Summary

Every allocator type in lib/std/alloc.w declares its destructor as a naked free method pub fn Type.drop(mut self: Type) — Arena.drop (:210), FrameArena.drop (:220), ArenaScope.drop (:251), TempArena.drop (:290), Pool.drop (:330), PoolAllocator.drop (:343). That convention is not the language's destructor mechanism (§2.4 defines it as impl Drop for Type: fn drop(self)), so these methods are never invoked at scope exit. The arenas therefore leak everything they own.

Repro (TempArena — the §8.3.2.5 / #481 case)

use std.alloc
fn use_arena() -> Unit:
    var temp = scratch_arena()
    let p = temp.alloc(32)
    let _ = p          // temp leaves scope here
fn main:
    use_arena()
    print("ok")

with run --debug-alloc →

debug-alloc: LEAK addr=... size=32 origin=with_alloc   // the alloc(32), never freed
debug-alloc: LEAK addr=... size=64 origin=Vec          // TempArena.allocations backing
debug-alloc: leak count=2

An explicit temp.reset() frees the with_alloc block (reset works), but the internal allocations: Vec still leaks because TempArena.drop (which would drop the Vec) never runs.

Minimal proof the naked convention doesn't fire

var LOG = ""
type Widget { id: i32 }
pub fn Widget.drop(mut self: Widget) -> Unit: LOG = LOG ++ "D"
fn scope() -> Unit:
    let w = Widget { id: 1 }
    let _ = w.id
fn main:
    scope()
    print(f"[{LOG}]")     // prints []  — the drop never ran

Switching to impl Drop for Widget: fn drop(self) is the spec form and fires (existing tests: test/behavior/behav_drop_*.w).

Spec

§2.4 (docs/with-specification.md:414-495): destructors are impl Drop for Type. A method merely named drop is an ordinary method.

Fix direction

Convert the six lib/std/alloc.w destructors from pub fn Type.drop(mut self) to impl Drop for Type: fn drop(mut self). (Decide separately whether the compiler should also recognize a naked .drop() method as a destructor, or diagnose it — a method named drop that silently never runs is a footgun.)

Impact

Silent leaks from every std arena/pool. Blocks #481 (its acceptance wants an observable TempArena.drop -> reset assertion, which currently fails). #481 referenced #430 as the possible cause, but #430 is closed — this is the real cause.

Secondary (needs its own investigation)

impl Drop for Widget: fn drop(mut self) -> Unit: print("dropped") passed with check but failed with run with error: code generation failed, while other impl Drop structs codegen fine — a pattern-specific codegen gap (possibly print/side-effect in drop, or mut self). Filed here as a lead; may warrant a separate issue once minimized.

Activity

  1. ehartford commented on Jul 4, 2026

    @ehartford
    ContributorAuthor

    Attempted the impl-Drop conversion (2026-07-03) — it requires a foundational allocator rework, not a mechanical change. Reverted cleanly; documenting the exact blocker.

    Confirmed root cause of the leak

    The compiler recognizes a destructor only via the Drop trait: Sema.type_has_drop_impl (src/Sema.w:4110) checks has_drop_method → select_trait_impl(type, drop) (src/Sema.w:5170) and the impl_extra scan for syms.drop. A naked free method fn Type.drop(mut self) is neither, so type_needs_drop is 0 for every alloc type and no destructor is ever emitted → the arenas/pools leak (§2.4 defines the destructor as impl Drop for Type: fn drop(self)).

    Why the obvious fix cascades

    Converting the six alloc destructors to impl Drop for Type: fn drop(move self: Self) makes the types needs-drop — and the entire allocator API is built on by-value mutable receivers mut self: Arena (alloc.w:111 Arena.alloc, :141 alloc_zeroed, :185 reset, :159 reset_to, :235 scope, and the FrameArena/Pool/PoolAllocator equivalents). For a non-Drop value mut self: T is in-place mutation; once T: Drop, each mut self: T call moves the receiver in and drops it at return. Result (verified after converting): arena_new(64).alloc(8) allocates a block then immediately frees the whole arena and returns null; the entire arena/pool test suite fails (behav_arena_region no output, behav_arena_scope asserts on a null alloc).

    The real fix (foundation work)

    To make these types Drop-correct, the mutating receivers must move from mut self: Arena (by-value) to &mut Arena (borrow) across the whole module — alloc/alloc_zeroed/reset/reset_to/scope/add_block/Pool alloc/free/etc. — plus:

    • composite ownership: ArenaScope { arena: Arena } and PoolAllocator { pool: Pool } should rely on transitive field drop (empty impl-Drop bodies), not an explicit self.arena.drop() (which double-frees at scope exit — the explicit call runs AND the field auto-drops);
    • the explicit-drop tests (behav_pool_alloc calls pool.drop()/allocator.drop()).

    This is an allocator-ownership redesign, deferred as its own task (related: #437 first-class allocators).

    Secondary compiler issues surfaced (candidates for their own issue)

    1. fn drop(self) and fn drop(mut self) pass with check but fail with run with a generic error: code generation failed; only fn drop(move self: Self) codegens. fn drop(self: Self) correctly says "method receiver requires an explicit mode" — the self/mut self forms should give the same clear diagnostic at check time instead of a late codegen failure.
    2. Explicit x.drop() on a struct with Drop fields runs only the drop body, NOT the transitive field drops (scope-exit drop runs both) — an asymmetry that leaks fields on explicit drop.
    3. A method merely named drop (not impl Drop) silently never runs — a footgun; the compiler should recognize or diagnose it.
  2. ehartford commented on Jul 4, 2026

    @ehartford
    ContributorAuthor

    BDFL rulings (2026-07-04) — three, reshaping this fix:

    1. mut self: Self is a NON-consuming mutable borrow, including for Drop types. The observed consume+drop of a Drop-typed mut-self receiver mid-call (arena.alloc() freeing the arena) is a compiler bug in receiver lowering — root-cause and fix THAT. No &mut API rework of lib/std/alloc.w: after the lowering fix, this issue reduces to converting the six naked fn Type.drop(mut self) methods to impl Drop for Type: fn drop(move self: Self).
    2. Explicit .drop() stays legal and becomes fully correct (Vale Higher-RAII): a consuming call that runs the destructor body AND the field drop glue, binding consumed, nothing left for scope exit. Fixes the verified asymmetry (explicit call currently skips field drops; manual field drops in the body currently double-drop at scope exit).
    3. Receiver form ruled on Bug: impl Drop with fn drop(self) / fn drop(mut self) fails codegen instead of a check-time diagnostic (§2.4) #642 (move self only). Spec §2.4 amended with the normative note (examples corrected to move self: Self).

    Execution order: fix the mut-self-on-Drop lowering first (keystone), then the alloc.w impl Drop conversions + explicit-drop glue, then #481's observable fixture.

  3. ehartford commented on Jul 4, 2026

    @ehartford
    ContributorAuthor

    Keystone landed in f57cc73: mut self/&self receivers are true borrows on both sides of the call (no callee drop, OK_COPY receiver operand), and explicit .drop() routes through the full scope-exit glue (body + field drops + consume). Fixpoint + full suite + debug-alloc lane green; 12 new fixtures pin the matrix. Remaining for this issue (Cycle 2): convert the six naked fn Type.drop(mut self) in lib/std/alloc.w to impl Drop — which now works, since the by-value mut-self receivers no longer move+drop once the type is Drop.

  4. ehartford commented on Jul 4, 2026

    @ehartford
    ContributorAuthor

    Completed in 3362ccd (keystone in f57cc73). The six naked destructors are now real §2.4 'impl Drop' destructors; composites rely on transitive field glue. Verified: scoped scratch_arena user allocations all free (was 6 leaks → only the #608 by-design POD Vec backing remains); arena/pool behavior family + full gate + debug-alloc lane green. The rulings' whole package landed: mut-self borrows (no mid-call drops), explicit .drop() = full glue + consume, drop(x) re-arms on reassign, #642 check-time receiver error.

  5. added a commit that references this issue on Jul 4, 2026
    3362ccd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions