rob-revisited/ide/tests/Profile/ProfilerTest.php

325 lines
17 KiB
PHP

<?php
namespace JumPHP\Ide\Tests\Profile;
use JumPHP\Ide\Agent\AgentTools;
use JumPHP\Ide\Ide;
use JumPHP\Ide\Lang\Messages;
use JumPHP\Ide\Profile\Analysis;
use JumPHP\Ide\Profile\ProfileBuilder;
use JumPHP\Ide\Profile\ProfileStore;
use JumPHP\Ide\Profile\Profiler;
use JumPHP\Ide\Workspace\LocalWorkspace;
use PHPUnit\Framework\TestCase;
/** The profiler end to end on the real Xdebug files of the fixture: prepare, parse, store, top lists, ranges, comparison, exports. */
final class ProfilerTest extends TestCase
{
private const FIXTURES = __DIR__ . '/../fixtures/profile';
private string $root;
/** @var list<array{0: string, 1: array}> */
private array $events = [];
protected function setUp(): void
{
Messages::setLocale('en');
$this->root = sys_get_temp_dir() . '/jumphp-profile-' . bin2hex(random_bytes(4));
mkdir($this->root, 0775, true);
$this->events = [];
}
protected function tearDown(): void
{
ProfileStore::removeTree($this->root);
Messages::reset();
}
private function profiler(): Profiler
{
return new Profiler($this->root, function (string $e, array $p): void {
$this->events[] = [$e, $p];
});
}
/** a run's files as Xdebug leaves them, and the profile made from them @return array<string, mixed> */
private function profileOf(Profiler $pr, string $mode = 'both', array $meta = []): array
{
$run = $pr->prepare(['mode' => $mode]);
$raw = $this->root . '/var/profiles/' . $run['id'] . '/raw';
copy(self::FIXTURES . '/workload.cachegrind', "$raw/cachegrind.out.1");
if ($mode !== 'cpu') {
copy(self::FIXTURES . '/workload.xt', "$raw/trace.1.xt");
}
$pr->parse($run['id'], $meta + ['label' => 'Run workload', 'mode' => $mode, 'target' => ['key' => 'run:workload', 'label' => 'Run workload'], 'wallSeconds' => 0.5]);
$profile = $pr->finishNow($run['id']);
self::assertIsArray($profile);
return $profile;
}
public function testPrepareTellsBinJumphpWhereAndWhatToWrite(): void
{
$pr = $this->profiler();
$cpu = $pr->prepare(['mode' => 'cpu']);
self::assertSame('profile', $cpu['env']['JUMPHP_PROFILE_MODE']);
self::assertSame("var/profiles/{$cpu['id']}/raw", $cpu['env']['JUMPHP_PROFILE']);
self::assertDirectoryExists($this->root . '/' . $cpu['env']['JUMPHP_PROFILE']);
self::assertArrayNotHasKey('JUMPHP_MAX_FRAMES', $cpu['env']);
$mem = $pr->prepare(['mode' => 'memory', 'durationKind' => 'frames', 'durationValue' => 120]);
self::assertSame('profile,trace', $mem['env']['JUMPHP_PROFILE_MODE']);
self::assertSame('120', $mem['env']['JUMPHP_MAX_FRAMES']);
$sec = $pr->prepare(['mode' => 'both', 'durationKind' => 'seconds', 'durationValue' => 5]);
self::assertSame('300', $sec['env']['JUMPHP_MAX_FRAMES']);
$linked = $pr->prepare(['mode' => 'cpu', 'game' => 'pong']);
self::assertStringStartsWith('games/pong/var/profiles/', $linked['env']['JUMPHP_PROFILE']);
self::assertSame('games/pong/', $linked['strip']);
}
public function testPhpDebuggerCannotProfileAndSaysWhy(): void
{
$engines = array_column($this->profiler()->engines(), null, 'id');
self::assertNull($engines['xdebug']['cpu']);
self::assertStringContainsString('step debugger', $engines['php-debugger']['cpu']);
$this->expectExceptionMessage('step debugger');
$this->profiler()->prepare(['mode' => 'cpu', 'engine' => 'php-debugger']);
}
public function testTheRealFilesBecomeAProfileWithSaneNumbers(): void
{
$pr = $this->profiler();
$p = $this->profileOf($pr);
$names = array_column($p['functions'], null, 'n');
self::assertArrayHasKey('fib', $names);
self::assertSame(67, $names['fib']['calls']);
self::assertSame(200, $names['php::str_repeat']['calls']);
self::assertSame('php', $names['php::str_repeat']['ns']);
self::assertSame('app', $names['fib']['ns']);
self::assertGreaterThan(0, $p['summary']['totalMs']);
self::assertLessThanOrEqual($p['summary']['totalMs'], $names['work']['incl']);
self::assertGreaterThan(20000, $names['allocate']['imem']);
self::assertGreaterThan(20000, $p['summary']['peakBytes']);
self::assertSame('trace', $p['flame']['source']);
$flame = $p['flame']['root'];
self::assertSame('{main}', $flame['ch'][0]['n']);
$kids = array_column($flame['ch'][0]['ch'], null, 'n');
self::assertArrayHasKey('allocate', $kids);
self::assertArrayHasKey('fib', $kids);
self::assertGreaterThan(200, count($p['timeline']['t']));
self::assertNotEmpty($p['slices']['names']);
self::assertNull($p['insight']); // not a game: no frame function
// the raw files are gone once read, the profile stays
self::assertDirectoryDoesNotExist($this->root . "/var/profiles/{$p['id']}/raw");
self::assertContains('profile.done', array_column($this->events, 0));
self::assertSame($p['id'], $pr->store()->load($p['id'])['id']);
}
public function testACpuOnlyRunHasAFlameFromTheCallGraphAndNoMemoryChart(): void
{
$p = $this->profileOf($this->profiler(), 'cpu');
self::assertSame('edges', $p['flame']['source']);
self::assertNull($p['timeline']);
self::assertNull($p['summary']['peakBytes']);
$main = $p['flame']['root']['ch'][0];
self::assertSame('{main}', $main['n']);
self::assertContains('fib', array_column($main['ch'], 'n'));
// children never add up to more than their parent
$check = function (array $n) use (&$check): void {
if (!empty($n['ch'])) {
self::assertLessThanOrEqual($n['v'] + 0.01, array_sum(array_column($n['ch'], 'v')));
array_map($check, $n['ch']);
}
};
$check($p['flame']['root']);
}
public function testTopListsRangesNeighboursAndLines(): void
{
$p = $this->profileOf($this->profiler());
$self = Analysis::top($p, 'self', 3);
self::assertCount(3, $self);
self::assertGreaterThanOrEqual($self[1]['self'], $self[0]['self']);
self::assertSame('php::str_repeat', Analysis::top($p, 'calls', 1)[0]['n']); // 200 calls, fib has 67
$mem = Analysis::top($p, 'mem', 2);
self::assertGreaterThanOrEqual(abs($mem[1]['mem']), abs($mem[0]['mem']));
$all = Analysis::range($p, 0, 99);
$half = Analysis::range($p, 0, 49);
self::assertGreaterThan(0, $all['ms']);
self::assertLessThanOrEqual($all['ms'] + 1e-6, $half['ms']);
self::assertGreaterThan(0.0, $half['ms']);
self::assertSame($all['ms'], Analysis::range($p, -5, 500)['ms']);
$nb = Analysis::neighbours($p, 'allocate');
self::assertSame(['{main}'], array_column($nb['callers'], 'n'));
self::assertSame(['php::str_repeat'], array_column($nb['callees'], 'n'));
$sites = Analysis::callSites($p, 'php::str_repeat'); // a PHP function has no file: its call sites are how to find it
self::assertNotEmpty($sites);
self::assertStringEndsWith('workload.php', $sites[0]['file']);
self::assertGreaterThan(0, $sites[0]['line']);
self::assertSame(200, array_sum(array_column($sites, 'calls')));
$lines = Analysis::hotLines($p, 3);
self::assertNotEmpty($lines);
self::assertStringEndsWith('workload.php', $lines[0]['file']);
}
public function testTheSummaryForAnAiIsCompactAndPointsAtFileAndLine(): void
{
$p = $this->profileOf($this->profiler());
$md = Analysis::markdown($p, 5);
self::assertStringContainsString('Where the CPU goes', $md);
self::assertStringContainsString('`fib`', $md);
self::assertMatchesRegularExpression('#workload\.php:\d+#', $md);
self::assertStringContainsString('Where the memory goes', $md);
self::assertLessThan(6000, strlen($md));
}
public function testTwoRunsAreComparedWithTheirDeltas(): void
{
$pr = $this->profiler();
$a = $this->profileOf($pr);
$b = $a;
$b['id'] = 'later';
foreach ($b['functions'] as &$f) {
if ($f['n'] === 'fib') {
$f['self'] *= 2;
$f['mem'] += 5000;
}
if ($f['n'] === 'work') {
$f['self'] /= 2;
}
}
unset($f);
$b['summary']['totalMs'] += 10;
$c = Analysis::compare($a, $b);
self::assertSame('fib', $c['slower'][0]['n']);
self::assertGreaterThan(0, $c['slower'][0]['self'][2]);
self::assertSame('work', $c['faster'][0]['n']);
self::assertLessThan(0, $c['faster'][0]['self'][2]);
self::assertSame('fib', $c['heavier'][0]['n']);
self::assertSame(5000, $c['heavier'][0]['mem'][2]);
self::assertEqualsWithDelta(10.0, $c['summary']['totalMs'][2], 1e-6);
self::assertStringContainsString('Slower', Analysis::compareMarkdown($c));
}
public function testSpeedscopeExportCarriesTheSameTime(): void
{
$p = $this->profileOf($this->profiler());
$s = Analysis::speedscope($p);
self::assertStringContainsString('speedscope', $s['$schema']);
$profile = $s['profiles'][0];
self::assertSame('sampled', $profile['type']);
self::assertCount(count($profile['samples']), $profile['weights']);
self::assertEqualsWithDelta($p['flame']['root']['v'], array_sum($profile['weights']), $p['flame']['root']['v'] * 0.01 + 0.01);
foreach ($profile['samples'] as $stack) {
foreach ($stack as $i) {
self::assertArrayHasKey($i, $s['shared']['frames']);
}
}
json_encode($s, JSON_THROW_ON_ERROR);
}
public function testTheStoreKeepsTheLastRunsOfATargetOnly(): void
{
$store = new ProfileStore($this->root, 3);
for ($i = 0; $i < 5; $i++) {
$store->save(['id' => "20260101-00000$i-aaa", 'label' => 'x', 'mode' => 'cpu', 'engine' => 'xdebug', 'created' => 100 + $i, 'target' => ['key' => 'run:a'],
'summary' => ['totalMs' => 1, 'peakBytes' => null, 'allocBytes' => 0, 'calls' => 1, 'truncated' => false]]);
}
$store->save(['id' => '20260101-000009-bbb', 'label' => 'y', 'mode' => 'cpu', 'engine' => 'xdebug', 'created' => 50, 'target' => ['key' => 'run:b'],
'summary' => ['totalMs' => 1, 'peakBytes' => null, 'allocBytes' => 0, 'calls' => 1, 'truncated' => false]]);
self::assertCount(3, $store->all('run:a'));
self::assertSame('20260101-000004-aaa', $store->all('run:a')[0]['id']);
self::assertCount(1, $store->all('run:b'));
self::assertNull($store->load('nope'));
self::assertSame(dirname($store->dir()), dirname(dirname($store->dir('../etc')))); // an id never leaves var/profiles
$this->expectException(\InvalidArgumentException::class);
$store->dir('..');
}
public function testAProgramThatLeftNothingFailsClearly(): void
{
$pr = $this->profiler();
$run = $pr->prepare(['mode' => 'cpu']);
$pr->parse($run['id'], ['label' => 'x']);
self::assertNull($pr->finishNow($run['id']));
$failed = array_values(array_filter($this->events, fn ($e) => $e[0] === 'profile.failed'));
self::assertCount(1, $failed);
self::assertStringContainsString('left no profile', $failed[0][1]['error']);
}
public function testAGameRunGivesTheFrameInsight(): void
{
// a cachegrind file of a game: Engine->tick calls SceneManager->update and ->render, 3 frames of 2, 3 and 10 ms
$cg = "events: Time_(10ns) Memory_(bytes)\n\nfl=(1) /workspace/engine/src/Kernel/Engine.php\nfn=(1) JumPHP\\Kernel\\Engine->tick\n10 5000 0\n"
. "cfl=(2) /workspace/engine/src/Scene/SceneManager.php\ncfn=(2) JumPHP\\Scene\\SceneManager->update\ncalls=3 0 0\n20 30000 100\n"
. "cfl=(2)\ncfn=(3) JumPHP\\Scene\\SceneManager->render\ncalls=3 0 0\n30 70000 200\n\n"
. "fl=(3) /workspace/games/g/src/Scene/PlayScene.php\nfn=(4) App\\Scene\\PlayScene->update\n5 30000 100\n\nsummary: 105000 300\n";
// three tick calls, one per frame, as the caller's per-call records
$main = "fl=(9) /workspace/app.php\nfn=(9) {main}\n1 1 0\n";
foreach ([[200000, 0], [300000, 0], [1000000, 0]] as [$t]) {
$main .= "cfl=(1)\ncfn=(1)\ncalls=1 0 0\n2 $t 0\n";
}
$run = ($pr = $this->profiler())->prepare(['mode' => 'cpu']);
file_put_contents($this->root . "/var/profiles/{$run['id']}/raw/cachegrind.out.1", str_replace('summary:', $main . "\nsummary:", $cg));
$pr->parse($run['id'], ['label' => 'game', 'mode' => 'cpu', 'strip' => 'games/g/']);
$p = $pr->finishNow($run['id']);
$in = $p['insight'];
self::assertNotNull($in);
self::assertSame(3, $in['frames']['count']);
self::assertEqualsWithDelta(5.0, $in['frames']['avgMs'], 0.01);
self::assertEqualsWithDelta(10.0, $in['frames']['slowest'][0]['ms'], 0.001);
self::assertSame(3, $in['frames']['slowest'][0]['frame']);
self::assertSame([2.0, 3.0, 10.0], $in['frames']['series']);
self::assertEqualsWithDelta(200.0, $in['frames']['fps'], 0.5);
self::assertGreaterThan($in['split']['updateMs'], $in['split']['renderMs']);
self::assertSame('JumPHP\Scene\SceneManager->update', $in['frameChildren'][1]['n'] ?? $in['frameChildren'][0]['n']);
$names = array_column($p['functions'], 'f', 'n');
self::assertSame('src/Scene/PlayScene.php', $names['App\Scene\PlayScene->update']); // a linked game: paths inside the game's own folder
}
public function testTheToolsOfTheAiAreOffered(): void
{
$names = array_column(AgentTools::all(), 'name');
foreach (['profile_run', 'profile_summary', 'profile_compare'] as $tool) {
self::assertContains($tool, $names);
}
$run = AgentTools::find('profile_run');
self::assertSame(['config'], $run['inputSchema']['required'] ?? ['config']);
self::assertSame(['cpu', 'memory', 'both'], $run['inputSchema']['properties']['mode']['enum']);
self::assertContains('profile_compare', array_column(AgentTools::all(), 'name'));
self::assertStringContainsString('profile_run', AgentTools::INSTRUCTIONS);
}
public function testTheInterfaceCommandsAnswer(): void
{
mkdir($this->root . '/bin', 0775, true);
file_put_contents($this->root . '/bin/jumphp', "#!/bin/sh\n");
$ide = new Ide(new LocalWorkspace($this->root));
foreach (['profile.engines', 'profile.prepare', 'profile.parse', 'profile.list', 'profile.get', 'profile.summary', 'profile.compare', 'profile.range', 'profile.export', 'profile.lines'] as $c) {
self::assertTrue($ide->has($c), $c);
}
$run = $ide->handle('profile.prepare', ['mode' => 'both']);
copy(self::FIXTURES . '/workload.cachegrind', $this->root . "/var/profiles/{$run['id']}/raw/cachegrind.out.1");
copy(self::FIXTURES . '/workload.xt', $this->root . "/var/profiles/{$run['id']}/raw/trace.1.xt");
$ide->handle('profile.parse', ['id' => $run['id'], 'meta' => ['label' => 'x', 'mode' => 'both', 'target' => ['key' => 'run:w']]]);
$guard = 0;
while ($ide->handle('profile.busy', [])['busy'] && $guard++ < 1000) {
$ide->tick(0.5);
}
$list = $ide->handle('profile.list', ['target' => 'run:w']);
self::assertCount(1, $list);
self::assertStringContainsString('fib', $ide->handle('profile.summary', ['id' => $list[0]['id']])['markdown']);
$lines = $ide->handle('profile.lines', ['path' => 'ide/tests/fixtures/profile/workload.php', 'target' => 'run:w']);
self::assertNotEmpty((array)$lines['lines']);
self::assertSame($list[0]['id'], $ide->handle('profile.get', ['id' => 'latest'])['id']);
$export = $ide->handle('profile.export', ['id' => $list[0]['id']]);
self::assertStringContainsString('speedscope', (string)file_get_contents($this->root . '/' . $export['path']));
}
public function testNamespacesAreTold(): void
{
self::assertSame('engine', ProfileBuilder::space('JumPHP\Kernel\Engine->tick', '/workspace/engine/src/Kernel/Engine.php'));
self::assertSame('app', ProfileBuilder::space('App\Scene\PlayScene->update', '/workspace/games/x/src/Scene/PlayScene.php'));
self::assertSame('vendor', ProfileBuilder::space('React\EventLoop\Loop->run', '/workspace/games/x/vendor/react/event-loop/src/Loop.php'));
self::assertSame('php', ProfileBuilder::space('php::str_repeat', 'php:internal'));
self::assertSame('App\Scene\PlayScene', ProfileBuilder::classOf('App\Scene\PlayScene->update'));
self::assertNull(ProfileBuilder::classOf('fib'));
}
}