Skip to content
Open
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
160 changes: 160 additions & 0 deletions experiments/otel-window/Probe.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
<?php

declare(strict_types=1);

require_once __DIR__ . '/../otel-callback/bootstrap.php';

use Tracewick\Sampler\ExcimerTraceConverter;
use Tracewick\Sampler\StackAggregator;
use Tracewick\Sampler\Frame;
use Tracewick\Sampler\Sample;

/** Isolated sequential harness. The caller owns every scope transition in an eligible window. */
final class Probe
{
public ExcimerProfiler $native;
private ExcimerTraceConverter $converter;
private array $groups = [];
private array $history = [];
private array $pending = [];
private ?string $token = null;
private int $originLow;
private int $originHigh;
public int $callbacks = 0;
public int $changes = 0;
public int $nativeWeight = 0;
public int $weight = 0;
public int $coalesced = 0;
public int $queuePeak = 0;
public int $overflow = 0;

public function __construct(
private string $mode, int $hz, int $depth, private bool $eligible = true,
private ?Closure $observer = null, private int $limit = 512,
) {
class_exists(Frame::class);
class_exists(Sample::class);
$this->converter = new ExcimerTraceConverter(0, $depth, null);
$this->groups[''] = new StackAggregator(512);
$this->originLow = hrtime(true);
$this->native = new ExcimerProfiler();
$this->originHigh = hrtime(true);
$this->native->setPeriod(1 / $hz);
$this->native->setEventType(EXCIMER_REAL);
$this->native->setMaxDepth($depth);
$this->native->setFlushCallback($this->capture(...), in_array($mode, ['immediate', 'otel', 'deferred'], true) ? 1 : 10000);
$this->afterChange();
$this->changes = 0;
}

public function beforeChange(): void
{
$this->token = null;
if ($this->mode === 'history' && $this->history !== []) {
$i = array_key_last($this->history);
$this->history[$i][1] = hrtime(true);
}
}

public function afterChange(): void
{
++$this->changes;
if (!$this->eligible || !in_array($this->mode, ['history','deferred'], true)) {
return;
}
$this->token = self::readToken();
if ($this->mode === 'history') {
if (count($this->history) >= $this->limit) {
$this->history = [];
++$this->overflow;
}
$this->history[] = [hrtime(true), PHP_INT_MAX, $this->token];
}
}

public static function readToken(): ?string
{
$pair = experimentContext();
return $pair === null ? null : implode('/', $pair);
}

private function lookup(float $timestamp): ?string
{
$ns = (int) round($timestamp * 1e9);
$earliest = $this->originLow + $ns - 1;
$latest = $this->originHigh + $ns + 1;
$lo = 0;
$hi = count($this->history);
while ($lo < $hi) {
$mid = ($lo + $hi) >> 1;
if ($this->history[$mid][0] < $earliest) {
$lo = $mid + 1;
} else {
$hi = $mid;
}
}
if ($lo === 0) {
return null;
}
[, $end, $token] = $this->history[$lo - 1];
return $latest < $end ? $token : null;
}

private function capture(ExcimerLog $log): void
{
++$this->callbacks;
if ($this->observer !== null) { $this->nativeWeight += $log->getEventCount(); }
if ($this->mode === 'deferred' && count($log) === 1) {
if (count($this->pending) < $this->limit) {
$this->pending[] = [$log, $this->token];
$this->queuePeak = max($this->queuePeak, count($this->pending));
return;
}
++$this->overflow;
}
$token = $this->eligible && ($this->mode === 'late' || ($this->mode === 'otel' && count($log) === 1))
? self::readToken() : null;
$this->ingest($log, $token);
}

private function ingest(ExcimerLog $log, ?string $token): void
{
foreach ($log as $entry) {
$weight = $entry->getEventCount();
$this->weight += $weight;
$key = $this->mode === 'history' ? $this->lookup($entry->getTimestamp()) : $token;
if ($weight > 1) {
$this->coalesced += $weight;
$key = null;
}
$key ??= '';
if (!isset($this->groups[$key]) && count($this->groups) >= 16) {
$key = '';
}
$trace = $entry->getTrace();
if ($this->observer !== null) {
($this->observer)($trace, $key, $weight);
}
$group = $this->groups[$key] ??= new StackAggregator(512);
$this->converter->ingestEntry($trace, $weight, $group);
}
}

/** Caller must stop sampling before draining. An active timer can append during traversal. */
public function drain(): array
{
$this->native->flush();
foreach ($this->pending as [$log, $token]) {
$this->ingest($log, $token);
}
$this->pending = [];
$weights = [];
foreach ($this->groups as $key => $group) {
foreach ($group->toSamples(0) as $sample) {
$weights[$key] = ($weights[$key] ?? 0) + $sample->count;
}
}
$this->groups = ['' => new StackAggregator(512)];
return $weights;
}
}
96 changes: 96 additions & 0 deletions experiments/otel-window/correctness.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<?php

declare(strict_types=1);
require __DIR__ . '/Probe.php';

use OpenTelemetry\API\Trace\Span;
use OpenTelemetry\API\Trace\SpanContext;
use OpenTelemetry\SDK\Trace\Sampler\AlwaysOffSampler;

function spin(): void {
$end = hrtime(true) + 24_000_000;
while (hrtime(true) < $end) { hash('sha256', 'sample'); }
}
function parentWork(): void { spin(); }
function childWork(): void { spin(); }
function emptyWork(): void { spin(); }
function remoteWork(): void { spin(); }
function unsampledWork(): void { spin(); }
function fiberWork(): void { spin(); }

function change(Probe $probe, Closure $operation): mixed {
$probe->beforeChange();
$result = $operation();
$probe->afterChange();
return $result;
}

function checkWindow(string $mode, bool $eligible, int $limit): array {
$tracer = experimentProvider()->getTracer('window');
$off = experimentProvider(new AlwaysOffSampler())->getTracer('off');
$remote = Span::wrap(SpanContext::createFromRemoteParent(str_repeat('a', 32), str_repeat('b', 16), 1));
$expected = ['emptyWork' => '', 'remoteWork' => '', 'fiberWork' => ''];
$wrong = $seen = [];
$observer = static function ($trace, $key, $weight) use (&$expected, &$wrong, &$seen, $eligible) {
foreach ($trace as $frame) {
$phase = $frame['function'] ?? '';
if (!isset($expected[$phase])) { continue; }
$seen[$phase][$key === '' ? 'empty' : 'linked'] = true;
if ($key !== '' && (!$eligible || $key !== $expected[$phase] || $weight > 1)) {
$wrong[] = $phase;
}
break;
}
};
$p = new Probe($mode, 1000, 48, $eligible, $observer, $limit);
$total = 0;
for ($unit = 0; $unit < 2; ++$unit) {
$p->native->start();
emptyWork();
$r = change($p, $remote->activate(...)); remoteWork();
$parent = $tracer->spanBuilder('local')->startSpan();
$s = change($p, $parent->activate(...));
$expected['parentWork'] = Probe::readToken(); parentWork();
$child = $tracer->spanBuilder('child')->startSpan();
$c = change($p, $child->activate(...));
$expected['childWork'] = Probe::readToken(); $child->end(); childWork();
$p->native->stop();
$total += array_sum($p->drain());
$p->native->start();
change($p, $c->detach(...)); parentWork();
$c = change($p, $child->activate(...)); childWork(); change($p, $c->detach(...));
usleep(13000);
if (!$eligible) { (new Fiber(fiberWork(...)))->start(); }
change($p, $s->detach(...)); $parent->end(); remoteWork(); change($p, $r->detach(...));
$span = $off->spanBuilder('unsampled')->startSpan();
$s = change($p, $span->activate(...));
$expected['unsampledWork'] = Probe::readToken(); unsampledWork();
change($p, $s->detach(...)); $span->end(); emptyWork();
$p->native->stop();
$total += array_sum($p->drain());
if ($p->drain() !== []) { throw new LogicException('Repeated flush produced weight'); }
}
$pass = ($mode === 'late' ? count($wrong) > 0 : !$wrong)
&& $total === $p->nativeWeight && $total === $p->weight && $p->coalesced > 0;
foreach (array_keys($expected) as $phase) {
if ($eligible && $phase === 'fiberWork') { continue; }
$pass = $pass && isset($seen[$phase]);
if ($eligible && $mode !== 'late' && $limit === 512 && $expected[$phase] !== '') {
$pass = $pass && isset($seen[$phase]['linked']);
}
}
if ($limit === 4) { $pass = $pass && $p->overflow > 0; }
return compact('mode','eligible','limit','total','pass','seen') +
['wrong' => count($wrong), 'coalesced_weight' => $p->coalesced, 'overflow' => $p->overflow];
}

$results = [];
foreach (['history','deferred','late'] as $mode) {
$results[] = checkWindow($mode, true, 512);
if ($mode !== 'late') {
$results[] = checkWindow($mode, false, 512);
$results[] = checkWindow($mode, true, 4);
}
}
echo json_encode($results, JSON_PRETTY_PRINT), "\n";
exit(in_array(false, array_column($results,'pass'), true) ? 1 : 0);
24 changes: 24 additions & 0 deletions experiments/otel-window/io.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);

require __DIR__ . '/Probe.php';

$mode = $argv[1];
$provider = experimentProvider();
$parent = $provider->getTracer('io')->spanBuilder('parent')->startSpan();
$scope = $parent->activate();
$p = new Probe($mode, 1000, 48, limit: 4);
$marker = fopen('php://fd/3', 'w');
$original = (new ReflectionMethod($p, 'capture'))->getClosure($p);
$p->native->setFlushCallback(static function (ExcimerLog $log) use ($marker, $original): void {
fwrite($marker, "OTEL_CB_BEGIN\n");
try { $original($log); }
finally { fwrite($marker, "OTEL_CB_END\n"); }
}, $mode === 'history' ? 8 : 1);
$p->native->start();
$end = hrtime(true) + 90_000_000;
while (hrtime(true) < $end) { hash('sha256', 'io'); }
$p->native->stop();
$weights = $p->drain();
if (array_sum($weights) < 1) { throw new LogicException('Missing weight'); }
$scope->detach(); $parent->end(); $provider->shutdown();
24 changes: 24 additions & 0 deletions experiments/otel-window/run.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);

mt_srand(20261123);
foreach ([48,256] as $depth) {
foreach ([100,1000] as $hz) {
foreach ([1,128] as $cycles) {
for ($round = 1; $round <= 7; ++$round) {
$modes = ['off','batched','immediate','otel','deferred','history'];
shuffle($modes);
foreach ($modes as $position => $mode) {
$proc = proc_open([PHP_BINARY,'-d','pcov.enabled=0','-d','opcache.enable_cli=0',
__DIR__.'/worker.php',$mode,$hz,$depth,$cycles], [1 => ['pipe','w']], $pipes);
$row = json_decode(stream_get_contents($pipes[1]), true, flags: JSON_THROW_ON_ERROR);
fclose($pipes[1]);
if (proc_close($proc) || $row['checksum'] !== ($expected ??= $row['checksum'])) {
throw new RuntimeException('Worker failure or checksum mismatch');
}
echo json_encode($row + compact('round','position')), "\n";
}
}
}
}
}
37 changes: 37 additions & 0 deletions experiments/otel-window/summarize.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
"""Paired, descriptive statistics for the window experiment."""
import json
import statistics
import sys
from collections import defaultdict
from pathlib import Path

rows = [json.loads(line) for line in Path(sys.argv[1]).read_text().splitlines()]
cells = defaultdict(dict)
for r in rows:
cell = cells[r['depth'], r['hz'], r['cycles']]
key = r['round'], r['mode']
if key in cell:
raise ValueError('Duplicate worker')
cell[key] = r
if len(rows) != 336 or len({r['checksum'] for r in rows}) != 1 or len(cells) != 8:
raise ValueError('Incomplete campaign')

print('| Depth | Hz | Changes | Mode | CPU Δ %, median [min, max] | Work Δ % | Flush ms | RSS MiB | Callbacks/s | Changes/s | Linked weight % |')
print('|---:|---:|---:|---|---:|---:|---:|---:|---:|---:|---:|')
for (depth, hz, cycles), cell in sorted(cells.items()):
for mode in ('off','batched','immediate','otel','deferred','history'):
arm = [cell[i, mode] for i in range(1, 8)]
def ratios(metric):
return [100 * (r[metric] / cell[r['round'], 'batched'][metric] - 1) for r in arm]
def median(metric, divisor=1):
return statistics.median(r[metric] / divisor for r in arm)
cpu = ratios('total_cpu_ns')
work = statistics.median(ratios('work_wall_ns'))
callback_rate = statistics.median(r['callbacks'] * 1e9 / r['total_wall_ns'] for r in arm)
change_rate = statistics.median(r['changes'] * 1e9 / r['work_wall_ns'] for r in arm)
linked = '—'
if mode in ('deferred', 'history'):
linked = f"{statistics.median(100 * (1 - r['unknown_weight'] / r['weight']) for r in arm):.1f}"
print(f'| {depth} | {hz} | {cycles*2} | {mode} | {statistics.median(cpu):+.1f} '
f'[{min(cpu):+.1f}, {max(cpu):+.1f}] | {work:+.1f} | {median("final_flush_ns",1e6):.2f} '
f'| {median("max_rss_kib",1024):.1f} | {callback_rate:.0f} | {change_rate:.0f} | {linked} |')
Loading