Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 9 additions & 1 deletion src/Ipc/ResultSlotTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
46 changes: 46 additions & 0 deletions src/Shm/Arena.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down Expand Up @@ -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
*
Expand Down
69 changes: 69 additions & 0 deletions tests/Shm/ArenaTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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();
Expand Down
Loading