Skip to content

Optimize garbage collection with a generational GC - #2129

Draft
pguyot wants to merge 3 commits into
atomvm:release-0.7from
pguyot:w08/generational-gc
Draft

pguyot wants to merge 3 commits into
atomvm:release-0.7from
pguyot:w08/generational-gc

Conversation

@pguyot

@pguyot pguyot commented Feb 22, 2026 •

Copy link
Copy Markdown
Collaborator

Continuation of:

Semantics follow BEAM: a per-process fullsweep_after counter, settable with spawn_opt/1 and process_flag/2 (spec fixed accordingly), defaulting to 65535 like BEAM. 0 disables the generational collector (always full-sweep).

The first two commits are independent fixes that the generational collector exposes or depends on, reviewable separately:

  1. put_map_exact wrote the key operand into the shared keys tuple, a pre-existing bug masked by full-sweep GC, exposed by any sharing-preserving collector
  2. a finishing process still in Spawning state was not removed from the waiting_processes list in context_destroy

These changes are made under both the "Apache 2.0" and the "GNU Lesser General
Public License 2.1 or later" license terms (dual license).

SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later

@petermm

This comment was marked as outdated.

@pguyot
pguyot force-pushed the w08/generational-gc branch 3 times, most recently from 2a1dab6 to 554c7f5 Compare March 8, 2026 09:08
@petermm

This comment was marked as outdated.

@petermm

This comment was marked as outdated.

@pguyot
pguyot force-pushed the w08/generational-gc branch from 554c7f5 to 611ae42 Compare March 8, 2026 13:31
@pguyot

pguyot commented Mar 8, 2026 •

Copy link
Copy Markdown
Collaborator Author

I removed the defensive block that would process pointers from old -> young, which cannot exist as Erlang data structures are immutable. This confused the LLMs.

@petermm

petermm commented Mar 8, 2026

Copy link
Copy Markdown
Contributor

I removed the defensive block that would process pointers from old -> young, which cannot exist as Erlang data structures are immutable. This confused the LLMs.

You know best, this is way beyond my skill level - llm does suggest cleaning docs up if you back that out..

@pguyot
pguyot force-pushed the w08/generational-gc branch from 611ae42 to 4d58b57 Compare March 16, 2026 07:05
Comment thread tests/test-heap.c Fixed
Comment thread tests/test-heap.c Fixed
Comment thread tests/test-heap.c Fixed
Comment thread tests/test-heap.c Fixed
Comment thread tests/test-heap.c Fixed
Comment thread tests/test-heap.c Fixed
@pguyot
pguyot force-pushed the w08/generational-gc branch 2 times, most recently from 4191e7d to 8a8f998 Compare March 16, 2026 21:38
@pguyot
pguyot force-pushed the w08/generational-gc branch from 8a8f998 to c881d09 Compare May 24, 2026 18:53
@pguyot
pguyot changed the base branch from main to release-0.7 May 24, 2026 18:56
@pguyot
pguyot marked this pull request as draft May 24, 2026 18:57
@pguyot
pguyot force-pushed the w08/generational-gc branch 6 times, most recently from d377b55 to 1dd8ed6 Compare May 30, 2026 08:51
Comment thread tests/test-heap.c Fixed
@pguyot
pguyot force-pushed the w08/generational-gc branch 5 times, most recently from f289efe to 74158b9 Compare June 2, 2026 19:08
@pguyot
pguyot force-pushed the w08/generational-gc branch from 3c35158 to cb19ec3 Compare June 8, 2026 20:26
@pguyot
pguyot force-pushed the w08/generational-gc branch 3 times, most recently from de08cad to 359bfeb Compare July 14, 2026 05:57
Comment thread tests/test-heap.c Fixed
Comment thread tests/test-heap.c Fixed
@pguyot
pguyot force-pushed the w08/generational-gc branch 8 times, most recently from 9d34e8a to ba145d4 Compare July 14, 2026 17:59
@pguyot
pguyot marked this pull request as ready for review July 14, 2026 18:02
@pguyot
pguyot force-pushed the w08/generational-gc branch from ba145d4 to f6558d1 Compare July 25, 2026 17:24
@petermm

This comment was marked as outdated.

@pguyot
pguyot force-pushed the w08/generational-gc branch from f6558d1 to f0503b5 Compare July 26, 2026 12:37
@pguyot

pguyot commented Jul 26, 2026

Copy link
Copy Markdown
Collaborator Author

I don't want to bump JIT binary version until 0.7 is released.

@pguyot
pguyot force-pushed the w08/generational-gc branch 3 times, most recently from b713be5 to a3466e2 Compare July 27, 2026 04:16
@pguyot
pguyot marked this pull request as draft July 27, 2026 04:22
@pguyot
pguyot force-pushed the w08/generational-gc branch from a3466e2 to 06296a6 Compare September 25, 2026 16:09
Only the value may be written; the key already in the tuple is kept.
Fix both the emulator and the JIT lowering, with a regression test
that exercises promotion via allocation-driven minor collections.

Signed-off-by: Paul Guyot <pguyot@kallisys.net>
Signed-off-by: Paul Guyot <pguyot@kallisys.net>
@pguyot
pguyot force-pushed the w08/generational-gc branch from 06296a6 to e71f5fa Compare December 5, 2026 05:51
@petermm

petermm commented Dec 5, 2026

Copy link
Copy Markdown
Contributor

think we are at absolutely nits, ignore 1 llm still insists on version bumping:

PR #2129 review — Generational garbage collection

Recommendation: request changes. The highest-priority fix is to invalidate native code built for the old Context layout.

Scope: the last commit, e71f5faac, against its parent 8907e3614. The oracle independently reviewed the same commit; the findings below were checked against the code. None of the proposed patches were applied to the PR.

Findings

P1 — The runtime still accepts native code with the old Context offsets

jit.c:152–170 and the backends change the register offsets on both 32- and 64-bit targets, but jit.h:273 and jit.hrl:21 still advertise native format version 1. module.c:1153–1199 uses that version to accept both embedded AVMN chunks and cached native code. For example, on 64-bit targets an old store to x[0] at 0x30 now writes heap.old_heap_start; an old access to e at 0x28 reads or writes heap.high_water_mark. Mixed-version artifacts can corrupt the process before the collector runs.

Bump both ends together and rebuild bundled precompiled code. Use the next unallocated format version on the integration branch if the PR is rebased over another ABI bump.

--- a/src/libAtomVM/jit.h
+++ b/src/libAtomVM/jit.h
@@ -273 +273 @@
-#define JIT_FORMAT_VERSION 1
+#define JIT_FORMAT_VERSION 2
--- a/libs/jit/include/jit.hrl
+++ b/libs/jit/include/jit.hrl
@@ -21 +21 @@
--define(JIT_FORMAT_VERSION, 1).
+-define(JIT_FORMAT_VERSION, 2).

Add a loader regression with bytecode and a same-architecture version-1 native chunk: assert the loader does not install a native entry (do not execute the incompatible payload). On an emulator-enabled build, also assert bytecode still runs. Pair it with a current-version chunk to rule out a loader that skips both. A cache-version mismatch test would cover the other entry path. The updated backend tests check freshly generated code, not stale artifacts.

P2 — Large fullsweep_after values select a different GC policy than BEAM

nifs.c:1532–1537 and nifs.c:3273–3279 keep the entire accepted small integer in a size_t. OTP 29 stores the threshold in a 16-bit field: 65536 becomes 0 (full sweeps only), and 65537 becomes 1. The current AtomVM commit preserves both values. test-heap.c:577–632 currently asserts the opposite contract by setting the field directly.

If BEAM compatibility is the intended contract, normalize after validation at both public API boundaries and replace the large-value C test (including its call in main) with a public boundary test. If preservation is intentional, document the divergence instead of claiming BEAM semantics for these values.

--- a/src/libAtomVM/nifs.c
+++ b/src/libAtomVM/nifs.c
@@ -1537 +1537 @@
-        new_ctx->fullsweep_after = term_to_int(fullsweep_after_term);
+        new_ctx->fullsweep_after = (uint16_t) term_to_int(fullsweep_after_term);
@@ -3278 +3278 @@
-                ctx->fullsweep_after = term_to_int(value);
+                ctx->fullsweep_after = (uint16_t) term_to_int(value);
--- a/tests/erlang_tests/test_process_flag_fullsweep_after.erl
+++ b/tests/erlang_tests/test_process_flag_fullsweep_after.erl
@@ -103,4 +103,7 @@
     OldVal = erlang:process_flag(fullsweep_after, 10),
     10 = erlang:process_flag(fullsweep_after, 0),
-    0 = erlang:process_flag(fullsweep_after, OldVal),
+    0 = erlang:process_flag(fullsweep_after, 65535),
+    65535 = erlang:process_flag(fullsweep_after, 65536),
+    {fullsweep_after, 0} = erlang:process_info(self(), fullsweep_after),
+    0 = erlang:process_flag(fullsweep_after, OldVal),
     ok = expect_badarg(fun() -> erlang:process_flag(fullsweep_after, -1) end),
@@ -115,7 +118,7 @@
             Parent ! {fullsweep_after, Val}
         end,
-        [{fullsweep_after, 42}]
+        [{fullsweep_after, 65537}]
     ),
     ok =
         receive
-            {fullsweep_after, 42} -> ok
+            {fullsweep_after, 1} -> ok

P2 — spawn_opt accepts an explicitly invalid [] threshold

nifs.c:1490 uses a property lookup whose default is []. nifs.c:1532 then interprets [] as “option absent,” so spawn_opt(Fun, [{fullsweep_after, []}]) starts a child with the default instead of raising badarg. Use a distinct sentinel, as monitor already does nearby.

--- a/src/libAtomVM/nifs.c
+++ b/src/libAtomVM/nifs.c
@@ -1490 +1490 @@
-    term fullsweep_after_term = interop_proplist_get_value(opts_term, FULLSWEEP_AFTER_ATOM);
+    term fullsweep_after_term = interop_proplist_get_value_default(opts_term, FULLSWEEP_AFTER_ATOM, term_invalid_term());
@@ -1532 +1532 @@
-    if (fullsweep_after_term != term_nil()) {
+    if (fullsweep_after_term != term_invalid_term()) {
--- a/tests/erlang_tests/test_process_flag_fullsweep_after.erl
+++ b/tests/erlang_tests/test_process_flag_fullsweep_after.erl
@@ -124,3 +124,4 @@
     ok = expect_badarg(fun() -> spawn_opt(fun() -> ok end, [{fullsweep_after, -1}]) end),
     ok = expect_badarg(fun() -> spawn_opt(fun() -> ok end, [{fullsweep_after, foo}]) end),
+    ok = expect_badarg(fun() -> spawn_opt(fun() -> ok end, [{fullsweep_after, []}]) end),
     ok.

Missing regression coverage

Exercise MSO ownership across two actual minor collections

test-heap.c:327–355 requests two free words in MEMORY_NO_SHRINK mode when there is already enough space. That call performs no collection. The subsequent full GC proves both references are eventually released, not that a minor GC releases the dead young binary while preserving the old one. Give the old heap headroom, force the second minor through an allocation request, and check the list as well as the surviving reference count:

--- a/tests/test-heap.c
+++ b/tests/test-heap.c
@@ -320,3 +320,4 @@
     // Minor GC: refc (via tuple1) should be promoted to old heap, refc2 stays young
+    ctx->heap_growth_strategy = BoundedFreeHeapGrowth;
     res = memory_ensure_free_with_roots(ctx, TERM_BOXED_REFC_BINARY_SIZE + TUPLE_SIZE(2), 2, roots, MEMORY_NO_SHRINK);
     assert(res == MEMORY_GC_OK);
@@ -336,7 +337,11 @@
     roots[0] = tuple3;
     roots[1] = term_nil();
-    res = memory_ensure_free_with_roots(ctx, TUPLE_SIZE(1), 2, roots, MEMORY_NO_SHRINK);
+    size_t minor_count = ctx->gc_count;
+    res = memory_ensure_free_with_roots(ctx, context_avail_free_memory(ctx) + 1, 2, roots, MEMORY_NO_SHRINK);
     assert(res == MEMORY_GC_OK);
+    assert(ctx->gc_count == minor_count + 1);
 
-    // refc should still be alive in old heap
+    // The dead young binary was released; the old binary is still owned once.
+    assert(refc_binaries->next == &refc_ptr->head);
+    assert(refc_binaries->prev == &refc_ptr->head);
     assert(refc_ptr->ref_count == 1);

Separately, destroy a context with a resource still in its old MSO list and assert its destructor runs exactly once. The current test collects everything before destruction.

Swap a root fragment after the old generation exists

test-heap.c:641–684 exercises clearing the high-water mark but never sets up a populated old generation before the swap. Add a promotion before the existing MEMORY_NO_GC request. Verify that the old generation survives the swap, then keep the existing post-collection tuple assertions. An old resource would also cover preservation of old_mso_list; the minimal tuple extension below exercises the pointer bookkeeping.

--- a/tests/test-heap.c
+++ b/tests/test-heap.c
@@ -659,10 +659,16 @@
     // First GC sets HWM
     res = memory_ensure_free_with_roots(ctx, TUPLE_SIZE(2), 2, roots, MEMORY_CAN_SHRINK);
     assert(res == MEMORY_GC_OK);
     assert(ctx->heap.high_water_mark != NULL);
-    tuple1 = roots[0];
+
+    ctx->heap_growth_strategy = BoundedFreeHeapGrowth;
+    res = memory_ensure_free_with_roots(ctx, context_avail_free_memory(ctx) + 1, 2, roots, MEMORY_NO_SHRINK);
+    assert(res == MEMORY_GC_OK);
+    term *old_heap_start = ctx->heap.old_heap_start;
+    term *old_heap_ptr = ctx->heap.old_heap_ptr;
+    assert(old_heap_start != NULL && old_heap_ptr > old_heap_start);
 
     // A no-GC allocation larger than the free space swaps in a new root
     // fragment (the path NIFs take when they cannot GC)
     size_t free_space = context_avail_free_memory(ctx);
     res = memory_ensure_free_opt(ctx, free_space + 16, MEMORY_NO_GC);
@@ -671,5 +677,7 @@
     // high_water_mark no longer belongs to the root fragment: it must be
     // cleared so the next minor GC runs with an empty mature region
     assert(ctx->heap.high_water_mark == NULL);
+    assert(ctx->heap.old_heap_start == old_heap_start);
+    assert(ctx->heap.old_heap_ptr == old_heap_ptr);
 
     // The next collection must preserve the data reachable from roots

Small comment fix: memory.c:120–125 says clearing the high-water mark forces a full GC, but memory.c:307–327 can still choose a minor collection. This is a documentation mismatch, not a reason to change collection policy.

--- a/src/libAtomVM/memory.c
+++ b/src/libAtomVM/memory.c
@@ -120,3 +120,3 @@
     // The swap strands the mature region in the old root fragment (now
     // root->next): high_water_mark no longer delimits anything in the new
-    // root, so clear it to force the next collection to be a full GC.
+    // root, so clear it to leave the new root's mature region empty.

Verification

  • A fresh macOS arm64 Debug interpreter build passed test-heap and the existing test_process_flag_fullsweep_after module.
  • The same Erlang probe on OTP 29 and the reviewed AtomVM build returned {0,1,0} versus {65536,65537,1}. The fields are the threshold read after setting 65536, the child threshold after spawning with 65537, and 1 if spawning with [] was accepted (0 for badarg).
  • The two proposed C regression extensions also passed against the reviewed runtime when compiled from a scratch copy. The proposed Erlang regression assertions passed on OTP 29.
  • The native-format finding is based on the emitted offsets and the loader's version checks, not on executing a stale chunk. No lost-root or double-release defect was established in the inspected collector paths. The coverage suggestions are not reports of reproduced collector bugs.

Semantics follow BEAM: a per-process fullsweep_after counter, settable
with spawn_opt/1 and process_flag/2 (spec fixed accordingly), defaulting
to 65535 like BEAM. Minor collections run in between; 0 disables the
generational collector (always full-sweep).

Signed-off-by: Paul Guyot <pguyot@kallisys.net>
@pguyot
pguyot force-pushed the w08/generational-gc branch from e71f5fa to f4c91ea Compare December 5, 2026 19:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants