From ab5d4cf1c06759805f3680bf9c4d946c79f21595 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 16 Aug 2026 09:11:11 +0000 Subject: [PATCH] fix(shm): fault a pre-sized table in at creation instead of over the run The arena is MAP_ANONYMOUS, so a block's pages arrive on first write. A structure that hands out one record at a time - ResultSlotTable, one slot per spawn - therefore pays for its pages a fault at a time for the whole life of a run, even though the table was pre-sized before the fork and nothing is being allocated. No arena counter can see it: the watermark and the allocator cursor are byte-flat throughout, and the only symptom is the family's RSS climbing with the workload, which is exactly what a memory gate calls a leak. native-php-coroutines#24 reported it as one: ~64 bytes of RSS per slot id consumed - the slot record - with both arena counters at +0.0. Arena::prefault() stores one zero per page across a block. The block is freshly bumped and therefore already zero, so it changes nothing; it only decides whether the residency is charged at creation or spread across the run. ResultSlotTable::create() calls it, which is a pre-fork moment, so the pages are materialized once and shared by the whole family. Measured on the reporting soak (8 slots/round): arena mapping RSS went from 60 KiB climbing to 84 KiB across 392 slots, to a flat 84 KiB from round one. No record shape, table meaning or globals[0] target changes, so LAYOUT_VERSION stays at 5. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_01U5QRWPfmkZME7hDjU6i5EA --- AGENTS.md | 9 +++++ src/Ipc/ResultSlotTable.php | 10 +++++- src/Shm/Arena.php | 46 +++++++++++++++++++++++++ tests/Shm/ArenaTest.php | 69 +++++++++++++++++++++++++++++++++++++ 4 files changed, 133 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 5888703..091c713 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -110,6 +110,15 @@ shared struct before it aborts* — siblings then read plausible garbage with no child calling it is a deliberate no-op. Do not re-arm it. - Every rewrite of a shared string costs a new arena block (a reader may be following the old pointer right now). Exhaustion is a typed `ArenaException`, never a crash. +- **A pre-sized table that is consumed gradually is `prefault()`ed at creation.** The mapping is + anonymous, so its pages arrive on first write. A structure handing out one record at a time — + `ResultSlotTable` is the case — therefore charges its memory a page at a time for the whole life + of the run, while the watermark, the allocator counter and every arena metric stay flat, because + nothing is being allocated. The only visible symptom is the family's RSS climbing with the + workload, which is indistinguishable from a leak and was reported as one + (native-php-coroutines#24). Touch the block once, in the creating process, before the fork: it + does not add memory, it decides when the memory is charged, and afterwards a climb really is + a climb. - Gate memory claims with the soaks, and watch the **watermark plateau** rather than the peak: ```bash diff --git a/src/Ipc/ResultSlotTable.php b/src/Ipc/ResultSlotTable.php index 5d32d29..e9b1ee1 100644 --- a/src/Ipc/ResultSlotTable.php +++ b/src/Ipc/ResultSlotTable.php @@ -101,9 +101,17 @@ public static function create( throw IpcException::invalidCapacity('Result slot table', $capacity); } $arena = $allocator->arena(); - $address = $arena->allocate((self::HEADER_WORDS + $capacity * self::SLOT_WORDS) * 8, 64); + $size = (self::HEADER_WORDS + $capacity * self::SLOT_WORDS) * 8; + $address = $arena->allocate($size, 64); $mutex = $arena->allocateMutex(); + // Pre-sized means pre-sized. Slots are handed out one at a time for the whole life of the + // run, so without this the table's pages fault in one per eight slots and the family's RSS + // climbs with the workload while the arena watermark - correctly - never moves. That is + // indistinguishable from a leak to any memory gate, and it was reported as one + // (native-php-coroutines#24). Creation happens before the fork, so the cost is paid once. + $arena->prefault($address, $size); + $arena->writeWord($address + self::WORD_CAPACITY * 8, $capacity); $arena->writeWord($address + self::WORD_MUTEX * 8, $mutex); diff --git a/src/Shm/Arena.php b/src/Shm/Arena.php index 1928712..d4951bb 100644 --- a/src/Shm/Arena.php +++ b/src/Shm/Arena.php @@ -137,6 +137,12 @@ final class Arena private const int MAX_ALIGNMENT = 4096; + /** + * Bytes the kernel materializes per fault; only prefault() cares, and only to space its + * stores out. A host with larger pages simply gets a few redundant stores, never a miss. + */ + private const int PAGE_SIZE = 4096; + /** * Offsets of the fields inside one roots-directory entry, in words */ @@ -370,6 +376,46 @@ public function allocate(int $size, int $align = 16): int return $this->baseAddress + $aligned; } + /** + * Makes every page of a block resident now, instead of one fault at a time later + * + * The mapping is MAP_ANONYMOUS, so its pages exist only once something writes to them. For + * a structure that is filled in gradually over the life of a run - a result-slot table + * handing out one slot per spawn is the case that motivated this - that turns a table that + * was PRE-SIZED before the fork into one whose cost arrives a page at a time for hours. + * Nothing about the arena grows, so no watermark and no allocator counter moves, yet the + * process's RSS climbs with the workload and every memory gate reads it as a leak + * (native-php-coroutines#24). + * + * Touching the pages up front is the honest fix rather than a suppression: the memory was + * always going to be resident, this only decides whether it is charged at creation or + * spread across the run, and afterwards a climb really is a climb. + * + * Call it from the creating process **before the fork**. The block is freshly bumped and + * therefore already zero, so the write stores a zero over a zero and changes nothing; the + * pages are shared, so the family pays for them once. + * + * @param int $address Start of the block, as returned by allocate() + * @param int $length Bytes to make resident + */ + public function prefault(int $address, int $length): void + { + $this->assertRange($address, $length); + + // One store per page is what the kernel needs to materialize it; a memcpy over the whole + // block would do the same thing and cost a PHP string the size of the table. The first + // touch is at $address rather than at its page boundary, which may belong to the block + // allocated before this one. + $end = $address + $length; + $word = $address & ~7; + + while ($word + 8 <= $end) { + $this->words[($word - $this->baseAddress) >> 3] = 0; + + $word = ($word + self::PAGE_SIZE) & ~(self::PAGE_SIZE - 1); + } + } + /** * Publishes an address under a name every process of the family can look up * diff --git a/tests/Shm/ArenaTest.php b/tests/Shm/ArenaTest.php index dfc0624..707b0f2 100644 --- a/tests/Shm/ArenaTest.php +++ b/tests/Shm/ArenaTest.php @@ -32,6 +32,34 @@ private function makeArena(?int $size = null): Arena return Arena::create($size ?? self::TEST_SIZE); } + /** Resident bytes of the mapping holding $address, straight out of /proc/self/smaps */ + private function mappingRss(int $address): int + { + $handle = fopen('/proc/self/smaps', 'r'); + $inRange = false; + + if ($handle === false) { + return 0; + } + + try { + while (($line = fgets($handle)) !== false) { + if (preg_match('/^([0-9a-f]+)-([0-9a-f]+) /', $line, $bounds) === 1) { + $inRange = hexdec($bounds[1]) <= $address && $address < hexdec($bounds[2]); + + continue; + } + if ($inRange && str_starts_with($line, 'Rss:')) { + return ((int) filter_var($line, FILTER_SANITIZE_NUMBER_INT)) * 1024; + } + } + } finally { + fclose($handle); + } + + return 0; + } + public function testFreshArenaStartsEmptyAboveItsHeader(): void { $arena = $this->makeArena(); @@ -132,6 +160,47 @@ public function testWordAndByteAccessRoundTrip(): void $this->assertSame('hello arena', $arena->readBytes($address + 8, 11)); } + public function testPrefaultTouchesOnlyItsOwnBlock(): void + { + $arena = $this->makeArena(); + + // The neighbour comes first, so its tail shares a page with the head of the block being + // prefaulted: a loop that started at the page boundary instead of at the block would + // overwrite it, and nothing else in the arena would ever notice + $neighbour = $arena->allocate(64); + $arena->writeWord($neighbour, 0x5A5A5A5A5A); + + $block = $arena->allocate(3 * 4096 + 24, 8); + $arena->prefault($block, 3 * 4096 + 24); + + $this->assertSame(0x5A5A5A5A5A, $arena->readWord($neighbour)); + + // A bumped block is fresh mapping, so prefault stores a zero over a zero and the block + // reads exactly as it did before + foreach ([0, 4096, 8192, 3 * 4096 + 16] as $offset) { + $this->assertSame(0, $arena->readWord($block + $offset)); + } + } + + public function testPrefaultMakesTheBlockResidentUpFront(): void + { + if (!is_readable('/proc/self/smaps')) { + $this->markTestSkipped('residency is read from /proc/self/smaps, which is not available here'); + } + + $arena = $this->makeArena(2 << 20); + $block = $arena->allocate(1 << 20, 4096); + + $before = $this->mappingRss($arena->baseAddress()); + $arena->prefault($block, 1 << 20); + $after = $this->mappingRss($arena->baseAddress()); + + // The point of the call: pages that would otherwise arrive one fault at a time, for as + // long as the structure is being filled, are all here now. Half the block is a generous + // floor - the kernel may have faulted some of it in already + $this->assertGreaterThan($before + (512 << 10), $after); + } + public function testAccessOutsideThePayloadIsRefused(): void { $arena = $this->makeArena();