Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
fix(slab): O(1) aligned-page cross-thread frees + retire-on-live-count (no global hot-path lock)
Martin Vogel487377459fce
diff --git a/src/foundation/slab_alloc.c b/src/foundation/slab_alloc.cindex 81818ac18..95d23587e 100644--- a/src/foundation/slab_alloc.c+++ b/src/foundation/slab_alloc.c@@ -1,5 +1,5 @@/*- * slab_alloc.c — Thread-local slab allocator for tree-sitter.+ * slab_alloc.c — Slab allocator for tree-sitter.** Replaces malloc/calloc/realloc/free for ALL tree-sitter allocations,* eliminating ptmalloc2's per-thread arena fragmentation (the root cause@@ -13,15 +13,37 @@* in production builds (MI_OVERRIDE=1). This eliminates the complex* tier2 bump allocator and its O(n) ownership checks.*- * On slab_destroy_thread: free all slab pages.+ * Cross-thread frees (tree-sitter's allocator callbacks are process-global,+ * so a chunk allocated on parser thread A can be freed on thread B):+ *+ * - Each slab page is allocated SLAB_PAGE_SIZE-aligned, so the owning page+ * of ANY chunk is recovered in O(1) by masking the pointer — no per-op+ * scan and no global hot-path lock. A tiny 3-level radix page map (keyed+ * by page number, lock-free reads, cold-path writes) tells slab_free+ * whether a masked base is a real slab page or a plain heap pointer,+ * without ever dereferencing an unrelated heap address.+ * - A free by the owning thread returns the chunk to the thread-local free+ * list (fast path, no atomics on the list). A foreign free is pushed onto+ * that page's lock-free MPSC remote-free stack; the owner drains it on its+ * next refill. Neither path takes a global lock.+ *+ * On reclaim/destroy: free pages with no live chunks; retire pages that still+ * have live chunks (owner=NULL, kept reachable) and free them when the final+ * chunk returns. Each page carries a refcount = (handed-out chunks) + (1 owner+ * guard while owned); the thread that drops it to zero frees the page. A page+ * holding a still-live tree-sitter lexer chunk is therefore never freed under+ * it (fixes the cross-thread invalid free and the #852 use-after-free).* realloc handles slab-to-heap promotion with minimal copying.*/#include "foundation/constants.h"#include "foundation/slab_alloc.h"#include "foundation/compat.h"+#include "foundation/compat_thread.h"#include <stdbool.h>+#include <stddef.h>#include <stdint.h>+#include <stdatomic.h>#include <stdlib.h>#include <string.h>@@ -31,75 +53,231 @@* All slab allocations are this size regardless of requested size. */#define SLAB_CHUNK_SIZE 64-/* Each slab page: 64KB = 1024 chunks of 64 bytes.- * Amortizes allocation overhead. One page per ~1 large file. */-#define SLAB_PAGE_CHUNKS 1024-#define SLAB_PAGE_SIZE (SLAB_CHUNK_SIZE * SLAB_PAGE_CHUNKS)+/* Each slab page is a 64KB region, allocated aligned to its own size so that+ * masking any interior chunk pointer with SLAB_PAGE_MASK yields the page base+ * (which is where the page header lives). */+#define SLAB_PAGE_SIZE ((size_t)65536)+#define SLAB_PAGE_SHIFT 16 /* log2(SLAB_PAGE_SIZE) */+#define SLAB_PAGE_MASK (~((uintptr_t)SLAB_PAGE_SIZE - 1))++/* Chunk region starts after the page header. SLAB_DATA_OFFSET must be a+ * multiple of SLAB_CHUNK_SIZE (so chunks stay 64-byte aligned) and at least+ * sizeof(slab_page_t). 64 bytes leaves 1023 usable chunks per page. */+#define SLAB_DATA_OFFSET 64+#define SLAB_PAGE_CHUNKS ((SLAB_PAGE_SIZE - SLAB_DATA_OFFSET) / SLAB_CHUNK_SIZE)/* Free list node — occupies the first 8 bytes of a free chunk. */typedef struct slab_free_node {struct slab_free_node *next;} slab_free_node_t;-/* One slab page — a contiguous block of SLAB_PAGE_CHUNKS chunks. */+typedef struct slab_state slab_state_t;++/* One slab page. The header lives at the SLAB_PAGE_SIZE-aligned base; the+ * SLAB_PAGE_CHUNKS chunks begin at (char*)page + SLAB_DATA_OFFSET. */typedef struct slab_page {- struct slab_page *next; /* linked list of pages */- char data[SLAB_PAGE_SIZE];+ struct slab_page *next; /* owner's page list (owner thread only) */+ _Atomic(slab_state_t *) owner; /* owning TLS state; NULL once retired */+ _Atomic(slab_free_node_t *) remote_free_head; /* lock-free MPSC stack of cross-thread frees */+ atomic_uint refcount; /* handed-out chunks + 1 owner guard (while owned) */} slab_page_t;+_Static_assert(sizeof(slab_page_t) <= SLAB_DATA_OFFSET,+ "slab_page header must fit in SLAB_DATA_OFFSET");+_Static_assert(SLAB_DATA_OFFSET % SLAB_CHUNK_SIZE == 0, "SLAB_DATA_OFFSET must be chunk-aligned");+/* Per-thread Tier 1 state. */-typedef struct {- slab_page_t *pages; /* linked list of all allocated pages */- slab_free_node_t *freelist; /* singly-linked free list */+struct slab_state {+ slab_page_t *pages; /* linked list of pages owned by this thread */+ slab_free_node_t *freelist; /* singly-linked free list (thread-local) */bool installed;-} slab_state_t;+};static CBM_TLS slab_state_t tls_slab;-/* ── Tier 1 helpers ────────────────────────────────────────────────── */+/* ── Page map: safe O(1) "is this a slab page?" lookup ───────────────+ *+ * A 3-level radix trie keyed by page number (base >> SLAB_PAGE_SHIFT) covering+ * the low 32 bits of the page number — i.e. all 48-bit addresses that malloc/+ * posix_memalign/_aligned_malloc return on every supported platform. Reads are+ * lock-free (atomic-acquire loads only, never dereferencing the queried+ * pointer). Writes (page create / free / retire — all cold paths) take a+ * dedicated spinlock that is NEVER touched on the alloc/free hot path.+ *+ * Intermediate tables are never freed during the run and stay reachable from+ * the static root, so lock-free readers never touch freed table memory. */+#define SLAB_MAP_L1_BITS 11+#define SLAB_MAP_L2_BITS 11+#define SLAB_MAP_L3_BITS 10+#define SLAB_MAP_TOTAL_BITS (SLAB_MAP_L1_BITS + SLAB_MAP_L2_BITS + SLAB_MAP_L3_BITS) /* 32 */+#define SLAB_MAP_L1_SIZE ((size_t)1 << SLAB_MAP_L1_BITS)+#define SLAB_MAP_L2_SIZE ((size_t)1 << SLAB_MAP_L2_BITS)+#define SLAB_MAP_L3_SIZE ((size_t)1 << SLAB_MAP_L3_BITS)-/* Rebuild free list from all existing pages. O(pages * SLAB_PAGE_CHUNKS). */-static void slab_rebuild_freelist(slab_state_t *s) {- s->freelist = NULL;- for (slab_page_t *p = s->pages; p; p = p->next) {- for (size_t i = 0; i < SLAB_PAGE_CHUNKS; i++) {- slab_free_node_t *node = (slab_free_node_t *)(p->data + (i * SLAB_CHUNK_SIZE));- node->next = s->freelist;- s->freelist = node;+typedef struct {+ _Atomic(slab_page_t *) e[SLAB_MAP_L3_SIZE];+} slab_map_l3_t;+typedef struct {+ _Atomic(slab_map_l3_t *) e[SLAB_MAP_L2_SIZE];+} slab_map_l2_t;++static _Atomic(slab_map_l2_t *) g_slab_map_root[SLAB_MAP_L1_SIZE];+static atomic_flag g_slab_map_lock = ATOMIC_FLAG_INIT;++static void slab_map_lock(void) {+ while (atomic_flag_test_and_set_explicit(&g_slab_map_lock, memory_order_acquire)) {+ /* Spin — cold path only (page create/destroy/retire). */+ }+}+static void slab_map_unlock(void) {+ atomic_flag_clear_explicit(&g_slab_map_lock, memory_order_release);+}++static bool slab_map_indices(uintptr_t base, size_t *i1, size_t *i2, size_t *i3) {+ uintptr_t pnum = base >> SLAB_PAGE_SHIFT;+ if ((pnum >> SLAB_MAP_TOTAL_BITS) != 0) {+ return false; /* address beyond coverage — never produced by malloc here */+ }+ *i1 = (size_t)((pnum >> (SLAB_MAP_L2_BITS + SLAB_MAP_L3_BITS)) & (SLAB_MAP_L1_SIZE - 1));+ *i2 = (size_t)((pnum >> SLAB_MAP_L3_BITS) & (SLAB_MAP_L2_SIZE - 1));+ *i3 = (size_t)(pnum & (SLAB_MAP_L3_SIZE - 1));+ return true;+}++/* Lock-free. Returns the slab page whose base == (ptr & mask), or NULL if the+ * masked base is not a registered slab page (i.e. ptr is a plain heap block). */+static slab_page_t *slab_map_lookup(uintptr_t base) {+ size_t i1, i2, i3;+ if (!slab_map_indices(base, &i1, &i2, &i3)) {+ return NULL;+ }+ slab_map_l2_t *l2 = atomic_load_explicit(&g_slab_map_root[i1], memory_order_acquire);+ if (!l2) {+ return NULL;+ }+ slab_map_l3_t *l3 = atomic_load_explicit(&l2->e[i2], memory_order_acquire);+ if (!l3) {+ return NULL;+ }+ return atomic_load_explicit(&l3->e[i3], memory_order_acquire);+}++/* Cold path. Sets the leaf entry for `base` to `val` (page to register, NULL to+ * unregister), allocating intermediate tables on demand. Returns false only if+ * a needed table allocation fails while registering. */+static bool slab_map_set(uintptr_t base, slab_page_t *val) {+ size_t i1, i2, i3;+ if (!slab_map_indices(base, &i1, &i2, &i3)) {+ return false;+ }+ slab_map_lock();+ slab_map_l2_t *l2 = atomic_load_explicit(&g_slab_map_root[i1], memory_order_relaxed);+ if (!l2) {+ if (!val) {+ slab_map_unlock();+ return true; /* nothing to unregister */}+ l2 = (slab_map_l2_t *)calloc(1, sizeof(*l2));+ if (!l2) {+ slab_map_unlock();+ return false;+ }+ atomic_store_explicit(&g_slab_map_root[i1], l2, memory_order_release);}+ slab_map_l3_t *l3 = atomic_load_explicit(&l2->e[i2], memory_order_relaxed);+ if (!l3) {+ if (!val) {+ slab_map_unlock();+ return true;+ }+ l3 = (slab_map_l3_t *)calloc(1, sizeof(*l3));+ if (!l3) {+ slab_map_unlock();+ return false;+ }+ atomic_store_explicit(&l2->e[i2], l3, memory_order_release);+ }+ atomic_store_explicit(&l3->e[i3], val, memory_order_release);+ slab_map_unlock();+ return true;}-/* Add a new page to the slab and prepend its chunks to the free list.- * Pages are allocated via malloc (= mimalloc in production). */+/* ── Tier 1 helpers ────────────────────────────────────────────────── */++static void slab_free(void *ptr);+static bool slab_map_register_page(slab_page_t *page);+static void slab_map_unregister_page(slab_page_t *page);++/* Allocate and register a new SLAB_PAGE_SIZE-aligned page, threading its chunks+ * onto the thread-local free list. Returns false on OOM (caller falls back to+ * malloc). Registration happens before any chunk is handed out so that a later+ * cross-thread free can always recover the page. */static bool slab_grow(slab_state_t *s) {- slab_page_t *page = (slab_page_t *)malloc(sizeof(slab_page_t));- if (!page) {+ void *mem = NULL;+ if (cbm_aligned_alloc(&mem, SLAB_PAGE_SIZE, SLAB_PAGE_SIZE) != 0 || !mem) {return false;}+ slab_page_t *page = (slab_page_t *)mem;page->next = s->pages;+ atomic_init(&page->owner, s);+ atomic_init(&page->remote_free_head, (slab_free_node_t *)NULL);+ atomic_init(&page->refcount, 1u); /* owner guard */++ if (!slab_map_register_page(page)) {+ cbm_aligned_free(page);+ return false;+ }s->pages = page;- /* Thread page's chunks onto the free list */for (size_t i = 0; i < SLAB_PAGE_CHUNKS; i++) {- slab_free_node_t *node = (slab_free_node_t *)(page->data + (i * SLAB_CHUNK_SIZE));+ slab_free_node_t *node =+ (slab_free_node_t *)((char *)page + SLAB_DATA_OFFSET + i * SLAB_CHUNK_SIZE);node->next = s->freelist;s->freelist = node;}return true;}-/* Check if a pointer belongs to any slab page (for realloc/free).- * Linear scan is bounded: per-file reclaim keeps page count small. */-static bool slab_owns(const slab_state_t *s, const void *ptr) {- uintptr_t p = (uintptr_t)ptr;- for (const slab_page_t *page = s->pages; page; page = page->next) {- uintptr_t lo = (uintptr_t)page->data;- if (p >= lo && p < lo + (uintptr_t)SLAB_PAGE_SIZE) {- return true;+/* Refill the thread-local free list: first reclaim any cross-thread frees+ * queued on owned pages, then grow a fresh page if still empty. */+static void slab_refill(slab_state_t *s) {+ for (slab_page_t *p = s->pages; p; p = p->next) {+ slab_free_node_t *rf = atomic_exchange_explicit(+ &p->remote_free_head, (slab_free_node_t *)NULL, memory_order_acquire);+ while (rf) {+ slab_free_node_t *next = rf->next;+ rf->next = s->freelist;+ s->freelist = rf;+ rf = next;+ }+ }+ if (s->freelist) {+ return;+ }+ (void)slab_grow(s);+}++/* Retire ownership and drop the owner guard for every page this thread owns.+ * A page with no live chunks is freed immediately; a page still holding+ * foreign-live chunks is retired (owner=NULL, left registered) and freed by+ * whichever thread returns its last chunk. */+static void slab_reclaim_pages(slab_state_t *s, bool clear_installed) {+ slab_page_t *p = s->pages;+ while (p) {+ slab_page_t *next = p->next;+ atomic_store_explicit(&p->owner, (slab_state_t *)NULL, memory_order_relaxed);+ unsigned prev = atomic_fetch_sub_explicit(&p->refcount, 1u, memory_order_acq_rel);+ if (prev == 1u) {+ slab_map_unregister_page(p);+ cbm_aligned_free(p);}+ p = next;+ }+ s->pages = NULL;+ s->freelist = NULL;+ if (clear_installed) {+ s->installed = false;}- return false;}/* ── Allocator functions (installed as tree-sitter callbacks) ───── */@@ -112,12 +290,15 @@ static void *slab_malloc(size_t size) {if (size <= SLAB_CHUNK_SIZE) {slab_state_t *s = &tls_slab;if (!s->freelist) {- if (!slab_grow(s)) {- return malloc(size); /* fallback */+ slab_refill(s);+ if (!s->freelist) {+ return malloc(size); /* grow failed → heap fallback */}}slab_free_node_t *node = s->freelist;s->freelist = node->next;+ slab_page_t *page = (slab_page_t *)((uintptr_t)node & SLAB_PAGE_MASK);+ atomic_fetch_add_explicit(&page->refcount, 1u, memory_order_relaxed);return node;}@@ -145,18 +326,13 @@ static void *slab_realloc(void *ptr, size_t new_size) {}if (new_size == 0) {/* realloc(ptr, 0) = free + return NULL */- if (slab_owns(&tls_slab, ptr)) {- slab_free_node_t *node = (slab_free_node_t *)ptr;- node->next = tls_slab.freelist;- tls_slab.freelist = node;- } else {- free(ptr);- }+ slab_free(ptr);return NULL;}- /* Case 1: ptr is in slab (≤64B block) */- if (slab_owns(&tls_slab, ptr)) {+ /* Case 1: ptr is in a slab page (≤64B block) */+ slab_page_t *page = slab_map_lookup((uintptr_t)ptr & SLAB_PAGE_MASK);+ if (page) {if (new_size <= SLAB_CHUNK_SIZE) {/* Still fits in a slab chunk — reuse same slot */return ptr;@@ -167,10 +343,7 @@ static void *slab_realloc(void *ptr, size_t new_size) {return NULL;}memcpy(new_ptr, ptr, SLAB_CHUNK_SIZE);- /* Return slab slot to free list */- slab_free_node_t *node = (slab_free_node_t *)ptr;- node->next = tls_slab.freelist;- tls_slab.freelist = node;+ slab_free(ptr);return new_ptr;}@@ -182,15 +355,48 @@ static void slab_free(void *ptr) {if (!ptr) {return;}- /* Slab page */- if (slab_owns(&tls_slab, ptr)) {- slab_free_node_t *node = (slab_free_node_t *)ptr;- node->next = tls_slab.freelist;- tls_slab.freelist = node;+ uintptr_t base = (uintptr_t)ptr & SLAB_PAGE_MASK;+ slab_page_t *page = slab_map_lookup(base);+ if (!page) {+ /* Not a slab chunk → plain heap pointer (>64B or grow-fallback). */+ free(ptr);return;}- /* Heap fallback */- free(ptr);++ /* It is a slab chunk. The chunk itself keeps its page alive (refcount ≥ 1)+ * until this very free, so the page cannot be freed underneath us. */+ slab_state_t *s = &tls_slab;+ slab_free_node_t *node = (slab_free_node_t *)ptr;++ if (atomic_load_explicit(&page->owner, memory_order_relaxed) == s) {+ /* Fast path: owner returns the chunk to its thread-local free list. */+ node->next = s->freelist;+ s->freelist = node;+ atomic_fetch_sub_explicit(&page->refcount, 1u, memory_order_acq_rel);+ return; /* owner guard keeps refcount ≥ 1; page is reused, not freed */+ }++ /* Foreign (or retired) free: push onto the page's lock-free MPSC stack. */+ slab_free_node_t *head = atomic_load_explicit(&page->remote_free_head, memory_order_relaxed);+ do {+ node->next = head;+ } while (!atomic_compare_exchange_weak_explicit(&page->remote_free_head, &head, node,+ memory_order_release, memory_order_relaxed));+ unsigned prev = atomic_fetch_sub_explicit(&page->refcount, 1u, memory_order_acq_rel);+ if (prev == 1u) {+ /* We returned the final chunk of a retired page → release it. */+ slab_map_unregister_page(page);+ cbm_aligned_free(page);+ }+}++/* ── Page-map registration wrappers (declared after slab_map_set) ── */++static bool slab_map_register_page(slab_page_t *page) {+ return slab_map_set((uintptr_t)page, page);+}+static void slab_map_unregister_page(slab_page_t *page) {+ (void)slab_map_set((uintptr_t)page, (slab_page_t *)NULL);}/* ── Public API ─────────────────────────────────────────────────── */@@ -204,43 +410,23 @@ void cbm_slab_install(void) {}void cbm_slab_reset_thread(void) {- slab_state_t *s = &tls_slab;- if (!s->pages) {- return;- }- slab_rebuild_freelist(s);+ cbm_slab_reclaim();}void cbm_slab_destroy_thread(void) {- slab_state_t *s = &tls_slab;- slab_page_t *p = s->pages;- while (p) {- slab_page_t *next = p->next;- free(p);- p = next;- }- s->pages = NULL;- s->freelist = NULL;- s->installed = false;+ slab_reclaim_pages(&tls_slab, true);}-/* Reclaim all slab memory for the current thread.+/* Reclaim slab memory owned by the current thread.*- * Call ONLY when no live allocations remain — i.e., after ts_tree_delete()- * AND ts_parser_delete() have freed everything back to the free lists.- * This keeps peak memory bounded per-file (not cumulative across files). */+ * Call ONLY when no LOCAL live allocations remain — i.e., after ts_tree_delete()+ * AND ts_parser_delete() have freed this thread's parser-owned chunks. If a+ * chunk from one of these pages is still held by another parser thread, the+ * page is retired instead of freed and released on the final cross-thread free.+ * This keeps peak memory bounded per-file without handing foreign slab chunks+ * to plain free(). */void cbm_slab_reclaim(void) {- slab_state_t *s = &tls_slab;- slab_page_t *p = s->pages;- while (p) {- slab_page_t *next = p->next;- free(p);- p = next;- }- s->pages = NULL;- s->freelist = NULL;- /* NOTE: keep s->installed true — allocator is still active,- * just with empty pages. Next slab_malloc will call slab_grow. */+ slab_reclaim_pages(&tls_slab, false);}/* ── Test API (thin wrappers for unit testing) ──────────────────── */diff --git a/src/foundation/slab_alloc.h b/src/foundation/slab_alloc.hindex 9648ba167..677be7ccf 100644--- a/src/foundation/slab_alloc.h+++ b/src/foundation/slab_alloc.h@@ -1,12 +1,17 @@/*- * slab_alloc.h — Thread-local slab allocator for tree-sitter.+ * slab_alloc.h — Slab allocator for tree-sitter.** Replaces malloc/calloc/realloc/free for ALL tree-sitter allocations* to eliminate ptmalloc2's per-thread arena fragmentation.** Tier 1 (≤64B): Fixed-size slab free list — O(1) alloc/free.* Matches tree-sitter SubtreeHeapData (CBM_SZ_64 bytes). Backed by- * 64KB slab pages via malloc (= mimalloc in production).+ * 64KB slab pages, each allocated aligned to its own size so the owning+ * page of any chunk is recovered in O(1) by masking the pointer. Pages are+ * reused per thread; cross-thread frees are recognized as slab pointers+ * (never handed to plain free()) and a page holding a still-live chunk is+ * retired, then freed when the final chunk returns. No global lock and no+ * per-op scan on the alloc/free hot path.** All allocations >64B go directly to malloc (= mimalloc in production),* which handles size classes, thread caching, and OS page return@@ -15,7 +20,7 @@* Usage:* cbm_slab_install(); // once, before any parsing* ... parse files ...- * cbm_slab_destroy_thread(); // on thread exit — frees all memory+ * cbm_slab_destroy_thread(); // on thread exit — frees owned memory*/#ifndef CBM_SLAB_ALLOC_H#define CBM_SLAB_ALLOC_H@@ -26,20 +31,23 @@* Must be called once before any ts_parser_new() calls. Thread-safe. */void cbm_slab_install(void);-/* Reset the current thread's slab: all chunks become available.+/* Reset the current thread's slab: owned pages are reclaimed or retired.* WARNING: Do NOT call between files if the parser retains live state.* Only safe after cbm_destroy_thread_parser() has been called. */void cbm_slab_reset_thread(void);-/* Destroy the current thread's allocator state: free all slab pages.- * Call on thread exit. */+/* Destroy the current thread's allocator state. Pages with no live chunks are+ * freed; pages still holding cross-thread live chunks are retired and freed on+ * the last free. Call on thread exit. */void cbm_slab_destroy_thread(void);-/* Reclaim all slab memory for the current thread.- * Call ONLY when no live allocations remain (after ts_tree_delete AND- * ts_parser_delete). Keeps the allocator installed — next allocation- * will grow fresh pages as needed. This bounds peak memory per-file- * rather than accumulating across all files in a worker. */+/* Reclaim current-thread slab memory.+ * Call ONLY when no LOCAL live allocations remain (after ts_tree_delete AND+ * ts_parser_delete). If another parser thread still holds a chunk from one of+ * these pages, that page is retired instead of freed and released on the final+ * cross-thread free. Keeps the allocator installed — next allocation will grow+ * fresh pages as needed. This bounds peak memory per-file rather than+ * accumulating across all files in a worker. */void cbm_slab_reclaim(void);/* Test/diagnostic API: direct access to the slab allocator.diff --git a/src/pipeline/pass_parallel.c b/src/pipeline/pass_parallel.cindex 8724d47c8..d0fb4fb72 100644--- a/src/pipeline/pass_parallel.c+++ b/src/pipeline/pass_parallel.c@@ -2672,6 +2672,13 @@ static void resolve_worker(int worker_id, void *ctx_ptr) {memory_order_relaxed);}+ /* Tear down this worker's thread-local parser + slab state, mirroring+ * extract_worker. Without this, resolve-worker pages keep an owner pointer+ * into dead TLS and are never retired, so a later cross-thread free can+ * never bring their refcount to zero (leak). Retiring them here releases+ * each page as its final chunk returns. */+ cbm_destroy_thread_parser();+ cbm_slab_destroy_thread();cbm_service_pattern_cache_end();}diff --git a/tests/test_mem.c b/tests/test_mem.cindex debb9b505..8a1330d75 100644--- a/tests/test_mem.c+++ b/tests/test_mem.c@@ -8,6 +8,7 @@#include "../src/foundation/mem.h"#include "../src/foundation/arena.h"#include "../src/foundation/slab_alloc.h"+#include "../src/foundation/compat_thread.h"#include "pipeline/pipeline.h"#include "pipeline/pipeline_internal.h"#include "graph_buffer/graph_buffer.h"@@ -521,6 +522,124 @@ TEST(slab_mixed_alloc_free_stress) {PASS();}+/* ── Cross-thread slab-free safety (distilled from PR #782, closes #852) ──+ *+ * Tree-sitter's allocator callbacks are process-global: a ≤64B chunk allocated+ * on parser thread A can be freed on parser thread B. The pre-fix thread-local+ * slab_owns() only scanned the FREEING thread's pages, so a cross-thread free+ * missed A's pages and fell through to free() on a pointer INTERIOR to a+ * malloc'd page (invalid free / SIGABRT). Separately (#852), destroying/+ * reclaiming a thread's slab while a live chunk is still referenced by a+ * tree-sitter lexer freed the page under it (heap-use-after-free).+ *+ * These are RED on main (invalid free / UAF, caught by ASan) and GREEN with+ * the O(1) aligned-page + retire-on-live-count allocator. */++typedef struct {+ void *ptr;+ atomic_int *go;+} slab_cross_thread_free_ctx_t;++static void *slab_cross_thread_free_worker(void *arg) {+ slab_cross_thread_free_ctx_t *ctx = (slab_cross_thread_free_ctx_t *)arg;+ while (ctx->go && !atomic_load_explicit(ctx->go, memory_order_acquire)) {+ cbm_usleep(1000);+ }+ /* Free on a DIFFERENT thread than the one that allocated. On main this+ * falls through to free() on an interior slab pointer → invalid free. */+ cbm_slab_test_free(ctx->ptr);+ return NULL;+}++/* #852 exact guard — deterministic, single-thread, NOT cross-suite-order+ * dependent. Destroy the current thread's slab while a chunk is still live,+ * then read and free the chunk. On main, destroy frees the page → the read is+ * a heap-use-after-free and the free is an invalid free. With retire-on-+ * live-count the page is retired (not freed) while the chunk lives and released+ * only when the final chunk returns. */+TEST(slab_destroy_thread_with_live_chunk_no_uaf) {+ cbm_slab_install();++ void *p = cbm_slab_test_malloc(48); /* ≤64B → slab chunk */+ ASSERT_NOT_NULL(p);+ memset(p, 0x7E, 48);++ /* Tear down slab TLS with p still referenced (models the live lexer). */+ cbm_slab_destroy_thread();++ /* p must still be valid — its page is retired, not freed. */+ for (int i = 0; i < 48; i++) {+ ASSERT_EQ(((unsigned char *)p)[i], 0x7E);+ }++ /* Returning the last live chunk releases the retired page (no leak). */+ cbm_slab_test_free(p);+ PASS();+}++TEST(slab_cross_thread_free_is_safe) {+ cbm_slab_install();++ void *p = cbm_slab_test_malloc(32);+ ASSERT_NOT_NULL(p);+ memset(p, 0x5A, 32);++ atomic_int go;+ atomic_init(&go, 1);+ slab_cross_thread_free_ctx_t ctx = {.ptr = p, .go = &go};+ cbm_thread_t t;+ ASSERT_EQ(cbm_thread_create(&t, 0, slab_cross_thread_free_worker, &ctx), 0);+ ASSERT_EQ(cbm_thread_join(&t), 0);++ cbm_slab_destroy_thread();+ PASS();+}++TEST(slab_reclaim_with_foreign_live_chunk_is_safe) {+ cbm_slab_install();++ void *p = cbm_slab_test_malloc(32);+ ASSERT_NOT_NULL(p);+ memset(p, 0xA5, 32);++ atomic_int go;+ atomic_init(&go, 0);+ slab_cross_thread_free_ctx_t ctx = {.ptr = p, .go = &go};+ cbm_thread_t t;+ ASSERT_EQ(cbm_thread_create(&t, 0, slab_cross_thread_free_worker, &ctx), 0);++ /* Reclaim while another thread still owns a live chunk from our page.+ * On main, reclaim frees the page → the pending cross-thread free is a+ * use-after-free. With retire-on-live-count, the page is retired. */+ cbm_slab_reclaim();+ atomic_store_explicit(&go, 1, memory_order_release);+ ASSERT_EQ(cbm_thread_join(&t), 0);++ cbm_slab_destroy_thread();+ PASS();+}++TEST(slab_destroy_with_foreign_live_chunk_is_safe) {+ cbm_slab_install();++ void *p = cbm_slab_test_malloc(32);+ ASSERT_NOT_NULL(p);+ memset(p, 0x3C, 32);++ atomic_int go;+ atomic_init(&go, 0);+ slab_cross_thread_free_ctx_t ctx = {.ptr = p, .go = &go};+ cbm_thread_t t;+ ASSERT_EQ(cbm_thread_create(&t, 0, slab_cross_thread_free_worker, &ctx), 0);++ /* Destroy TLS while another thread still owns a live chunk. */+ cbm_slab_destroy_thread();+ atomic_store_explicit(&go, 1, memory_order_release);+ ASSERT_EQ(cbm_thread_join(&t), 0);++ PASS();+}+/* ── Parallel extraction integration test ──────────────────── */static char g_mem_tmpdir[256];@@ -665,6 +784,11 @@ SUITE(mem) {RUN_TEST(slab_realloc_slab_to_heap);RUN_TEST(slab_calloc_zeroed);RUN_TEST(slab_mixed_alloc_free_stress);+ /* Cross-thread free safety + retire-on-live-count (#782 / #852) */+ RUN_TEST(slab_destroy_thread_with_live_chunk_no_uaf);+ RUN_TEST(slab_cross_thread_free_is_safe);+ RUN_TEST(slab_reclaim_with_foreign_live_chunk_is_safe);+ RUN_TEST(slab_destroy_with_foreign_live_chunk_is_safe);/* Integration */RUN_TEST(parallel_extract_with_slab);}