diff --git a/.gitignore b/.gitignore index a75accd..ad6b9e9 100644 --- a/.gitignore +++ b/.gitignore @@ -22,6 +22,4 @@ Thumbs.db /stand/app/composer.lock # Cursor / agent scratch .cursor/ -scripts/__pycache__/ - -tests/__pycache__/ +__pycache__/ diff --git a/LIMITATIONS.md b/LIMITATIONS.md index 468d47a..f227bd9 100644 --- a/LIMITATIONS.md +++ b/LIMITATIONS.md @@ -16,7 +16,7 @@ What this repository does **not** claim. Aligns with [METHOD.md](METHOD.md) non- - **Canonical** capacity goldens for overhead / spool pressure / chaos / high-RPS use `WORK_STACK_DEPTH=48` on the 8 vCPU stand (same wall budget as shallow; larger profiles). Nov-3 depth-`0` reports on 2 vCPU are **historical** only — useful to see how depth multiplies spool bytes; do not cite them as current overhead/pipeline numbers, and do not mix host-size + depth into one “delta”. - High-RPS figures are **single-instance** (one VPS: app + reader + Pyroscope + k6 on the same host unless a report says otherwise). A sustained RPS number is the **ceiling of that host + work unit + FPM pool**, not a universal Tracewick SLO and not multi-node “prod highload”. With PHP `tracewick-drain` at ~700 RPS, spool sat at soft admission (~600 files). With go-agent `0.1.0` on the same hold, spool stayed below soft `max_files` (~222 peak / ~109 last) — reader choice matters for pipeline headroom. Soft overshoot past `max_files` is fail-open by design, not a hard-cap bug. - Depth-48 soak evidence for FPM/RR/Swoole×agent is checked in; 72h shallow FPM+drain remains historical. -- Layer C checks order-of-magnitude signal only; flame-graph symbol share is not a contractual metric in v1. +- Capacity layer C checks order-of-magnitude signal. A separate [controlled function-share experiment](reports/2026-11-18-profile-shares.md) compares selected wall-time workloads with independent elapsed-time measurements; flame-graph symbol share is not a universal or contractual metric in v1. ## Explicit-flush weight correction diff --git a/METHOD.md b/METHOD.md index 63b66e7..f2e71d4 100644 --- a/METHOD.md +++ b/METHOD.md @@ -34,6 +34,15 @@ Runs: **baseline** (Tracewick off / kill switch) vs **on** at a pinned `sampleRa Profiles arrive in Pyroscope within the run window; sample volume is consistent with order-of-magnitude `RPS × sampleRate`. We do **not** claim exact per-symbol CPU percentages. +Controlled wall-time share experiments use the separate +[known-function probe](scripts/share-accuracy/README.md): elapsed-time measurements around +mutually exclusive functions form an independent reference, and actual Pyroscope inclusive +weights form the observation. Predeclare seeds, periods, repeats, minimum weighted volume, +share-error and unclassified-weight bounds; retain every run and a total-preserving +swapped-symbol negative control. Such a result describes its pinned workloads and runtime, +not a universal accuracy guarantee or an overhead measurement. See the +[recorded function-share experiment](reports/2026-11-18-profile-shares.md). + ## Tools | Tool | Role | diff --git a/Makefile b/Makefile index 4681704..4834a5f 100644 --- a/Makefile +++ b/Makefile @@ -9,6 +9,7 @@ SHELL := /bin/bash COMPOSE ?= docker compose K6_IMAGE ?= grafana/k6:1.8.2 +SHARE_PHP_IMAGE ?= tracewick-php:8.5 REPORTS_DIR ?= reports/_local BASE_URL ?= http://127.0.0.1:8080 APP_PORT ?= 8080 @@ -17,7 +18,7 @@ PYROSCOPE_PORT ?= 4040 RATE ?= 20 DURATION ?= 2m -.PHONY: check-soak plot-soak help build build-rr build-swoole up up-rr up-swoole down up-chaos wait-ready wait-app k6-version bench-smoke bench-overhead bench-spool-pressure bench-chaos bench-soak bench-rps prepare-reports-dir collect-report smoke-check +.PHONY: bench-share-accuracy check-soak plot-soak help build build-rr build-swoole up up-rr up-swoole down up-chaos wait-ready wait-app k6-version bench-smoke bench-overhead bench-spool-pressure bench-chaos bench-soak bench-rps prepare-reports-dir collect-report smoke-check help: ## Show targets @awk 'BEGIN {FS = ":.*##"; printf "Targets:\n"} /^[a-zA-Z0-9_-]+:.*?##/ { printf " %-18s %s\n", $$1, $$2 }' $(MAKEFILE_LIST) @@ -197,3 +198,6 @@ check-soak: ## Soak telemetry/validity regression tests and configuration syntax plot-soak: ## Render preserved soak telemetry (RUN_DIR=..., requires python3-matplotlib) python3 scripts/plot-soak.py "$(RUN_DIR)" + +bench-share-accuracy: ## Known-function wall-time shares in isolated Pyroscope (requires prepared core PHP image) + python3 scripts/share-accuracy/run.py --php-image "$(SHARE_PHP_IMAGE)" diff --git a/README.md b/README.md index 8b3dbf8..fece554 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,10 @@ It is correctness evidence, not a replacement for the capacity reports below. Those reports predate the explicit-flush fix; do not reuse their absolute profile weights as post-fix evidence or apply a blanket divide-by-two correction. +The separate [known-function share experiment](reports/2026-11-18-profile-shares.md) +checks wall-time proportions against independently measured function durations. +Its [runbook](scripts/share-accuracy/README.md) defines the fixed matrix and limits. + Local run scratch: `reports/_local/`. **Canonical** cloud goldens (cite these — `WORK_STACK_DEPTH=48` on the 8 vCPU stand, except soak): - [overhead A/B](reports/2026-11-06-overhead-depth48-cloud.md) diff --git a/reports/2026-11-18-profile-shares.md b/reports/2026-11-18-profile-shares.md new file mode 100644 index 0000000..f638a97 --- /dev/null +++ b/reports/2026-11-18-profile-shares.md @@ -0,0 +1,113 @@ +# Known-function wall-time shares + +Date: 2026-11-18. Method: [METHOD.md](../METHOD.md), controlled signal-share experiment; +[executable runbook](../scripts/share-accuracy/README.md). + +## Result + +**PASS for all 18 predeclared CLI runs.** Actual Pyroscope inclusive phase weights are within +5 percentage points of independent elapsed-time measurements in every run. Maximum absolute +error: **1.044 pp**; median: **0.066 pp**. +Maximum weight outside the two phase markers: **0.183%** +(limit 1%). Each run exceeds its weighted-volume floor. Swapping the two phase weights preserves +the total but fails the share check in **18/18** negative controls. + +This is evidence about the measured develop snapshots, not a selection or certification of the +future RC. No profiler, agent or Symfony production code was changed by this experiment. +The completed total-weight conservation campaign was not rerun. + +![All individual run errors and the predeclared acceptance limit](2026-11-18-profile-shares/errors.svg) + +## Revisions and environment + +- Core: `37e5928506cee2b1c395c2c8d01e89f2bf43a6b8`. +- Agent: `a15f0d310ba6d5942e67b37d3c3c55dc1b3b8100`; Go 1.27.4. +- Benchmarks base: `472be2566a1d03d0f5f636b31ea7e84dca0f73c1`; added harness input SHA-256s + are recorded in the [manifest](2026-11-18-profile-shares/manifest.json). +- Managed shared Linux host: kernel 6.18.57, x86_64, three logical CPUs visible, no affinity + or CPU limits imposed for this experiment. No capacity equivalence or resource-isolation claim. +- Docker 29.9.2; Python 3.12.14; PHP CLI 8.5.12; Excimer 1.2.7; OPcache CLI off, JIT disabled. +- PHP image used locally: `tracewick-uow-php:8.5`, ID + `sha256:87fc0fefa75d730cc8f56072ad2c5fc66996a52f6a27d8c72009fb35130bb5fb`. The runbook supports the normal core stand image via + `--php-image`; it need not share this locally assigned tag. +- Pyroscope 2.4.3, default segment-writer path, isolated fresh container; ID + `sha256:d7642a49eb85faf046ac286b40881cb6e55dc6a2a2e008a2468816e676dfd2e9`; image digest + `sha256:bf667534cd403320573063894e3faba20a5a5d1bfb92eddaecfabeb2446c502b`. +- Run ID `20261118T114657Z`. User-matched CLI container and Go reader; no FPM/RR server. + +## Fixed method + +The matrix contains PHP/PHP 70:30, PHP/PHP 20:80 and PHP/usleep 70:30 workloads, each at +100/1000 Hz and three deterministic repetitions. Every repetition starts a fresh process, +warms both functions, then records at least 40/12 seconds respectively. Native flush threshold +1000 exercises normal log callbacks; sampleRate is 1.0 and the UoW duration-rotation setting +remains its default off. There is no sampler freeze, native-log oracle or callback replacement. + +Each cycle randomizes phase order and jitters requested duration over 20–80 ms. The oracle +measures wall time around each marked function call with hrtime. This includes actual sleep +overshoot, descheduling and profiler work that occurs during the call. Expected shares use those +**measured** durations, not the nominal 70/30 or 20/80 request. The source sink's counts are only +diagnostics, not the ground truth for share accuracy. + +A real Go agent delivers each unique service to live Pyroscope. Analysis uses inclusive weights +below mutually exclusive `shareAlpha` / `shareBeta` nodes, including nested VM-interrupt callback +frames. It bounds unclassified weight separately before accepting normalized shares. The +measured function shares and actual backend shares are tabulated below. As an additional +readback check, source and Pyroscope alpha/beta/other weights match exactly in every run. + +100 Hz requires at least 3000 classified weighted periods; 1000 Hz requires 9000. Observed +weight/period is not a count of independent Bernoulli trials, especially around a C call. +No binomial confidence interval is claimed. Acceptance is per individual run; neither the +median nor a pooled total can hide a failed repetition. Integer cross-products implement the +inclusive 5 pp / 1% boundaries without floating-point acceptance drift. + +## All runs + +| Case | Measured alpha % | Pyroscope alpha % | Error pp | Other % | Weighted periods | +| --- | ---: | ---: | ---: | ---: | ---: | +| busy-20-1000hz-r1 | 19.897 | 20.941 | 1.044 | 0.183 | 12005 | +| busy-20-1000hz-r2 | 19.995 | 19.997 | 0.002 | 0.017 | 12012 | +| busy-20-1000hz-r3 | 20.105 | 20.180 | 0.075 | 0.025 | 12007 | +| busy-20-100hz-r1 | 20.036 | 20.045 | 0.009 | 0.000 | 4001 | +| busy-20-100hz-r2 | 19.998 | 20.130 | 0.132 | 0.025 | 4004 | +| busy-20-100hz-r3 | 20.062 | 20.150 | 0.088 | 0.000 | 4000 | +| busy-70-1000hz-r1 | 69.538 | 69.485 | 0.054 | 0.041 | 12066 | +| busy-70-1000hz-r2 | 69.985 | 69.927 | 0.058 | 0.042 | 12024 | +| busy-70-1000hz-r3 | 70.000 | 70.025 | 0.025 | 0.042 | 12030 | +| busy-70-100hz-r1 | 69.980 | 70.010 | 0.030 | 0.050 | 3998 | +| busy-70-100hz-r2 | 69.985 | 70.262 | 0.277 | 0.025 | 4005 | +| busy-70-100hz-r3 | 69.891 | 69.730 | 0.161 | 0.025 | 4004 | +| mixed-70-1000hz-r1 | 69.854 | 69.799 | 0.055 | 0.058 | 11993 | +| mixed-70-1000hz-r2 | 69.077 | 69.048 | 0.029 | 0.041 | 12051 | +| mixed-70-1000hz-r3 | 69.906 | 69.979 | 0.073 | 0.017 | 12005 | +| mixed-70-100hz-r1 | 69.899 | 69.642 | 0.256 | 0.075 | 3999 | +| mixed-70-100hz-r2 | 69.669 | 69.815 | 0.146 | 0.075 | 4002 | +| mixed-70-100hz-r3 | 69.830 | 69.855 | 0.025 | 0.025 | 4004 | + +## Evidence and validation + +- [Manifest / seeds / image IDs / input hashes](2026-11-18-profile-shares/manifest.json). +- [Complete summary and every negative control](2026-11-18-profile-shares/summary.json). +- [Compressed raw oracle and backend responses for every case](2026-11-18-profile-shares/evidence.json.gz). + `gzip -dc reports/2026-11-18-profile-shares/evidence.json.gz` yields a JSON object keyed by case ID; + each entry contains spec, complete per-cycle oracle, ProfileTypes, Querier response and result. +- All 18 cases and all 18 total-preserving swapped-symbol negative controls were retained. +- Local Python regression suite: 30 tests pass, including 14 share-check/matrix cases. PHP + syntax, Python compilation, existing shell checks, Compose configuration and diff checks pass. +- Cold-backend setup probes are excluded from this complete matrix: one short 2-second probe + correctly failed the weighted-volume floor; initial readback needed more time than expected. + HTTP readiness did not imply immediate profile visibility. The final run allows 300 seconds + for backend readback; that wait occurs after sampling and changes no accuracy threshold. + +## Limits + +This establishes aggregate **wall-time** attribution for these selected CLI workloads on the +recorded revisions. The oracle describes the profiled execution, not a separate unprofiled CPU +baseline. `usleep` exercises weighted VM-interrupt attribution after a C wait; it does not prove +arbitrary PDO/curl timelines or remove core ADR 11's resolution limit. + +There is no claim about CPU-mode accuracy, low-rate request selection, arbitrary stack depths, +FPM/RoadRunner/Swoole share accuracy, overhead, latency, production UID behavior elsewhere, +long-term stability or universal <=5 pp error. The working 72h soak VPS was not contacted or +modified. Its eventual result remains separate. Revisit affected measurements if final-RC +changes alter sampling, stack conversion, aggregation or encoding. diff --git a/reports/2026-11-18-profile-shares/errors.svg b/reports/2026-11-18-profile-shares/errors.svg new file mode 100644 index 0000000..35bee9a --- /dev/null +++ b/reports/2026-11-18-profile-shares/errors.svg @@ -0,0 +1,1426 @@ + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/reports/2026-11-18-profile-shares/evidence.json.gz b/reports/2026-11-18-profile-shares/evidence.json.gz new file mode 100644 index 0000000..ca3e822 Binary files /dev/null and b/reports/2026-11-18-profile-shares/evidence.json.gz differ diff --git a/reports/2026-11-18-profile-shares/manifest.json b/reports/2026-11-18-profile-shares/manifest.json new file mode 100644 index 0000000..493c520 --- /dev/null +++ b/reports/2026-11-18-profile-shares/manifest.json @@ -0,0 +1,212 @@ +{ + "revisions": { + "tracewick": "37e5928506cee2b1c395c2c8d01e89f2bf43a6b8", + "agent": "a15f0d310ba6d5942e67b37d3c3c55dc1b3b8100", + "benchmarks_base": "472be2566a1d03d0f5f636b31ea7e84dca0f73c1" + }, + "images": { + "php_image": "tracewick-uow-php:8.5", + "pyroscope_image": "grafana/pyroscope:2.4.3", + "port": 14040 + }, + "image_ids": { + "php": "sha256:87fc0fefa75d730cc8f56072ad2c5fc66996a52f6a27d8c72009fb35130bb5fb", + "pyroscope": "sha256:d7642a49eb85faf046ac286b40881cb6e55dc6a2a2e008a2468816e676dfd2e9" + }, + "host": { + "platform": "Linux-6.18.57-x86_64-with-glibc2.41", + "cpus_visible": 3 + }, + "files_sha256": { + "run.py": "178e513b6caf1b807b10206cdc38c4e642b0c228d24f140c136c9d6ba635fc8f", + "analyze.py": "771a3985fa66e08a2bf3a474928e7ad84ecb44e371b2f4bdb6ac19fa9b85daac", + "capture.php": "17d7222edb7a86863cdef1099af17dc5dc10a982a05789afbfc3b6d32d96b99b" + }, + "matrix": [ + { + "id": "busy-70-100hz-r2", + "application": "share-20261118T114657Z-busy-70-100hz-r2", + "seed": 83001, + "period_ns": 10000000, + "duration_ns": 40000000000, + "min_periods": 3000, + "alpha_percent": 70, + "sleep_beta": false + }, + { + "id": "mixed-70-100hz-r3", + "application": "share-20261118T114657Z-mixed-70-100hz-r3", + "seed": 83008, + "period_ns": 10000000, + "duration_ns": 40000000000, + "min_periods": 3000, + "alpha_percent": 70, + "sleep_beta": true + }, + { + "id": "busy-70-100hz-r3", + "application": "share-20261118T114657Z-busy-70-100hz-r3", + "seed": 83002, + "period_ns": 10000000, + "duration_ns": 40000000000, + "min_periods": 3000, + "alpha_percent": 70, + "sleep_beta": false + }, + { + "id": "mixed-70-1000hz-r1", + "application": "share-20261118T114657Z-mixed-70-1000hz-r1", + "seed": 83015, + "period_ns": 1000000, + "duration_ns": 12000000000, + "min_periods": 9000, + "alpha_percent": 70, + "sleep_beta": true + }, + { + "id": "busy-20-100hz-r2", + "application": "share-20261118T114657Z-busy-20-100hz-r2", + "seed": 83004, + "period_ns": 10000000, + "duration_ns": 40000000000, + "min_periods": 3000, + "alpha_percent": 20, + "sleep_beta": false + }, + { + "id": "busy-20-1000hz-r2", + "application": "share-20261118T114657Z-busy-20-1000hz-r2", + "seed": 83013, + "period_ns": 1000000, + "duration_ns": 12000000000, + "min_periods": 9000, + "alpha_percent": 20, + "sleep_beta": false + }, + { + "id": "busy-20-100hz-r3", + "application": "share-20261118T114657Z-busy-20-100hz-r3", + "seed": 83005, + "period_ns": 10000000, + "duration_ns": 40000000000, + "min_periods": 3000, + "alpha_percent": 20, + "sleep_beta": false + }, + { + "id": "mixed-70-1000hz-r2", + "application": "share-20261118T114657Z-mixed-70-1000hz-r2", + "seed": 83016, + "period_ns": 1000000, + "duration_ns": 12000000000, + "min_periods": 9000, + "alpha_percent": 70, + "sleep_beta": true + }, + { + "id": "busy-70-1000hz-r3", + "application": "share-20261118T114657Z-busy-70-1000hz-r3", + "seed": 83011, + "period_ns": 1000000, + "duration_ns": 12000000000, + "min_periods": 9000, + "alpha_percent": 70, + "sleep_beta": false + }, + { + "id": "mixed-70-1000hz-r3", + "application": "share-20261118T114657Z-mixed-70-1000hz-r3", + "seed": 83017, + "period_ns": 1000000, + "duration_ns": 12000000000, + "min_periods": 9000, + "alpha_percent": 70, + "sleep_beta": true + }, + { + "id": "mixed-70-100hz-r2", + "application": "share-20261118T114657Z-mixed-70-100hz-r2", + "seed": 83007, + "period_ns": 10000000, + "duration_ns": 40000000000, + "min_periods": 3000, + "alpha_percent": 70, + "sleep_beta": true + }, + { + "id": "busy-20-1000hz-r1", + "application": "share-20261118T114657Z-busy-20-1000hz-r1", + "seed": 83012, + "period_ns": 1000000, + "duration_ns": 12000000000, + "min_periods": 9000, + "alpha_percent": 20, + "sleep_beta": false + }, + { + "id": "busy-20-1000hz-r3", + "application": "share-20261118T114657Z-busy-20-1000hz-r3", + "seed": 83014, + "period_ns": 1000000, + "duration_ns": 12000000000, + "min_periods": 9000, + "alpha_percent": 20, + "sleep_beta": false + }, + { + "id": "busy-70-1000hz-r1", + "application": "share-20261118T114657Z-busy-70-1000hz-r1", + "seed": 83009, + "period_ns": 1000000, + "duration_ns": 12000000000, + "min_periods": 9000, + "alpha_percent": 70, + "sleep_beta": false + }, + { + "id": "busy-20-100hz-r1", + "application": "share-20261118T114657Z-busy-20-100hz-r1", + "seed": 83003, + "period_ns": 10000000, + "duration_ns": 40000000000, + "min_periods": 3000, + "alpha_percent": 20, + "sleep_beta": false + }, + { + "id": "busy-70-1000hz-r2", + "application": "share-20261118T114657Z-busy-70-1000hz-r2", + "seed": 83010, + "period_ns": 1000000, + "duration_ns": 12000000000, + "min_periods": 9000, + "alpha_percent": 70, + "sleep_beta": false + }, + { + "id": "busy-70-100hz-r1", + "application": "share-20261118T114657Z-busy-70-100hz-r1", + "seed": 83000, + "period_ns": 10000000, + "duration_ns": 40000000000, + "min_periods": 3000, + "alpha_percent": 70, + "sleep_beta": false + }, + { + "id": "mixed-70-100hz-r1", + "application": "share-20261118T114657Z-mixed-70-100hz-r1", + "seed": 83006, + "period_ns": 10000000, + "duration_ns": 40000000000, + "min_periods": 3000, + "alpha_percent": 70, + "sleep_beta": true + } + ], + "run_id": "20261118T114657Z", + "thresholds": { + "max_error_pp": 5, + "max_other_percent": 1 + } +} diff --git a/reports/2026-11-18-profile-shares/summary.json b/reports/2026-11-18-profile-shares/summary.json new file mode 100644 index 0000000..6f315c8 --- /dev/null +++ b/reports/2026-11-18-profile-shares/summary.json @@ -0,0 +1,924 @@ +{ + "complete": true, + "pass": true, + "results": [ + { + "expected": { + "alpha": 0.6998485670554151, + "beta": 0.30015143294458496 + }, + "observed": { + "alpha": 0.702621722846442, + "beta": 0.2973782771535581 + }, + "error_pp": { + "alpha": 0.2773155791026882, + "beta": 0.2773155791026882 + }, + "other_percent": 0.024962556165751375, + "weighted_periods": 4005.0, + "weights_ns": { + "alpha": 28140000000, + "beta": 11910000000, + "other": 10000000, + "total": 40060000000 + }, + "pass": true, + "failures": [], + "id": "busy-70-100hz-r2", + "negative_control": { + "expected": { + "alpha": 0.6998485670554151, + "beta": 0.30015143294458496 + }, + "observed": { + "alpha": 0.2973782771535581, + "beta": 0.702621722846442 + }, + "error_pp": { + "alpha": 40.247028990185704, + "beta": 40.247028990185704 + }, + "other_percent": 0.024962556165751375, + "weighted_periods": 4005.0, + "weights_ns": { + "alpha": 11910000000, + "beta": 28140000000, + "other": 10000000, + "total": 40060000000 + }, + "pass": false, + "failures": [ + "share_error" + ] + } + }, + { + "expected": { + "alpha": 0.6983027120134867, + "beta": 0.30169728798651335 + }, + "observed": { + "alpha": 0.6985514485514486, + "beta": 0.3014485514485514 + }, + "error_pp": { + "alpha": 0.02487365379618689, + "beta": 0.02487365379619244 + }, + "other_percent": 0.024968789013732832, + "weighted_periods": 4004.0, + "weights_ns": { + "alpha": 27970000000, + "beta": 12070000000, + "other": 10000000, + "total": 40050000000 + }, + "pass": true, + "failures": [], + "id": "mixed-70-100hz-r3", + "negative_control": { + "expected": { + "alpha": 0.6983027120134867, + "beta": 0.30169728798651335 + }, + "observed": { + "alpha": 0.3014485514485514, + "beta": 0.6985514485514486 + }, + "error_pp": { + "alpha": 39.68541605649353, + "beta": 39.68541605649352 + }, + "other_percent": 0.024968789013732832, + "weighted_periods": 4004.0, + "weights_ns": { + "alpha": 12070000000, + "beta": 27970000000, + "other": 10000000, + "total": 40050000000 + }, + "pass": false, + "failures": [ + "share_error" + ] + } + }, + { + "expected": { + "alpha": 0.6989134842969648, + "beta": 0.3010865157030353 + }, + "observed": { + "alpha": 0.6973026973026973, + "beta": 0.3026973026973027 + }, + "error_pp": { + "alpha": 0.16107869942674213, + "beta": 0.16107869942674213 + }, + "other_percent": 0.024968789013732832, + "weighted_periods": 4004.0, + "weights_ns": { + "alpha": 27920000000, + "beta": 12120000000, + "other": 10000000, + "total": 40050000000 + }, + "pass": true, + "failures": [], + "id": "busy-70-100hz-r3", + "negative_control": { + "expected": { + "alpha": 0.6989134842969648, + "beta": 0.3010865157030353 + }, + "observed": { + "alpha": 0.3026973026973027, + "beta": 0.6973026973026973 + }, + "error_pp": { + "alpha": 39.621618159966204, + "beta": 39.621618159966204 + }, + "other_percent": 0.024968789013732832, + "weighted_periods": 4004.0, + "weights_ns": { + "alpha": 12120000000, + "beta": 27920000000, + "other": 10000000, + "total": 40050000000 + }, + "pass": false, + "failures": [ + "share_error" + ] + } + }, + { + "expected": { + "alpha": 0.6985426659644937, + "beta": 0.30145733403550634 + }, + "observed": { + "alpha": 0.6979904944550988, + "beta": 0.3020095055449012 + }, + "error_pp": { + "alpha": 0.055217150939490534, + "beta": 0.05521715093948498 + }, + "other_percent": 0.05833333333333334, + "weighted_periods": 11993.0, + "weights_ns": { + "alpha": 8371000000, + "beta": 3622000000, + "other": 7000000, + "total": 12000000000 + }, + "pass": true, + "failures": [], + "id": "mixed-70-1000hz-r1", + "negative_control": { + "expected": { + "alpha": 0.6985426659644937, + "beta": 0.30145733403550634 + }, + "observed": { + "alpha": 0.3020095055449012, + "beta": 0.6979904944550988 + }, + "error_pp": { + "alpha": 39.65331604195924, + "beta": 39.65331604195924 + }, + "other_percent": 0.05833333333333334, + "weighted_periods": 11993.0, + "weights_ns": { + "alpha": 3622000000, + "beta": 8371000000, + "other": 7000000, + "total": 12000000000 + }, + "pass": false, + "failures": [ + "share_error" + ] + } + }, + { + "expected": { + "alpha": 0.19998104235944808, + "beta": 0.800018957640552 + }, + "observed": { + "alpha": 0.2012987012987013, + "beta": 0.7987012987012987 + }, + "error_pp": { + "alpha": 0.131765893925323, + "beta": 0.13176589392532856 + }, + "other_percent": 0.024968789013732832, + "weighted_periods": 4004.0, + "weights_ns": { + "alpha": 8060000000, + "beta": 31980000000, + "other": 10000000, + "total": 40050000000 + }, + "pass": true, + "failures": [], + "id": "busy-20-100hz-r2", + "negative_control": { + "expected": { + "alpha": 0.19998104235944808, + "beta": 0.800018957640552 + }, + "observed": { + "alpha": 0.7987012987012987, + "beta": 0.2012987012987013 + }, + "error_pp": { + "alpha": 59.87202563418506, + "beta": 59.872025634185064 + }, + "other_percent": 0.024968789013732832, + "weighted_periods": 4004.0, + "weights_ns": { + "alpha": 31980000000, + "beta": 8060000000, + "other": 10000000, + "total": 40050000000 + }, + "pass": false, + "failures": [ + "share_error" + ] + } + }, + { + "expected": { + "alpha": 0.199947491550299, + "beta": 0.800052508449701 + }, + "observed": { + "alpha": 0.19996669996669997, + "beta": 0.8000333000333001 + }, + "error_pp": { + "alpha": 0.0019208416400962047, + "beta": 0.0019208416400906536 + }, + "other_percent": 0.0166472448809722, + "weighted_periods": 12012.0, + "weights_ns": { + "alpha": 2402000000, + "beta": 9610000000, + "other": 2000000, + "total": 12014000000 + }, + "pass": true, + "failures": [], + "id": "busy-20-1000hz-r2", + "negative_control": { + "expected": { + "alpha": 0.199947491550299, + "beta": 0.800052508449701 + }, + "observed": { + "alpha": 0.8000333000333001, + "beta": 0.19996669996669997 + }, + "error_pp": { + "alpha": 60.008580848300106, + "beta": 60.0085808483001 + }, + "other_percent": 0.0166472448809722, + "weighted_periods": 12012.0, + "weights_ns": { + "alpha": 9610000000, + "beta": 2402000000, + "other": 2000000, + "total": 12014000000 + }, + "pass": false, + "failures": [ + "share_error" + ] + } + }, + { + "expected": { + "alpha": 0.20061857705538677, + "beta": 0.7993814229446132 + }, + "observed": { + "alpha": 0.2015, + "beta": 0.7985 + }, + "error_pp": { + "alpha": 0.08814229446132416, + "beta": 0.08814229446132416 + }, + "other_percent": 0.0, + "weighted_periods": 4000.0, + "weights_ns": { + "alpha": 8060000000, + "beta": 31940000000, + "other": 0, + "total": 40000000000 + }, + "pass": true, + "failures": [], + "id": "busy-20-100hz-r3", + "negative_control": { + "expected": { + "alpha": 0.20061857705538677, + "beta": 0.7993814229446132 + }, + "observed": { + "alpha": 0.7985, + "beta": 0.2015 + }, + "error_pp": { + "alpha": 59.78814229446132, + "beta": 59.78814229446132 + }, + "other_percent": 0.0, + "weighted_periods": 4000.0, + "weights_ns": { + "alpha": 31940000000, + "beta": 8060000000, + "other": 0, + "total": 40000000000 + }, + "pass": false, + "failures": [ + "share_error" + ] + } + }, + { + "expected": { + "alpha": 0.6907730193630622, + "beta": 0.3092269806369377 + }, + "observed": { + "alpha": 0.6904821176665837, + "beta": 0.3095178823334163 + }, + "error_pp": { + "alpha": 0.029090169647849606, + "beta": 0.02909016964786071 + }, + "other_percent": 0.041473125414731256, + "weighted_periods": 12051.0, + "weights_ns": { + "alpha": 8321000000, + "beta": 3730000000, + "other": 5000000, + "total": 12056000000 + }, + "pass": true, + "failures": [], + "id": "mixed-70-1000hz-r2", + "negative_control": { + "expected": { + "alpha": 0.6907730193630622, + "beta": 0.3092269806369377 + }, + "observed": { + "alpha": 0.3095178823334163, + "beta": 0.6904821176665837 + }, + "error_pp": { + "alpha": 38.12551370296459, + "beta": 38.125513702964604 + }, + "other_percent": 0.041473125414731256, + "weighted_periods": 12051.0, + "weights_ns": { + "alpha": 3730000000, + "beta": 8321000000, + "other": 5000000, + "total": 12056000000 + }, + "pass": false, + "failures": [ + "share_error" + ] + } + }, + { + "expected": { + "alpha": 0.6999990093231262, + "beta": 0.3000009906768738 + }, + "observed": { + "alpha": 0.7002493765586035, + "beta": 0.2997506234413965 + }, + "error_pp": { + "alpha": 0.02503672354773334, + "beta": 0.02503672354772779 + }, + "other_percent": 0.04154549231408392, + "weighted_periods": 12030.0, + "weights_ns": { + "alpha": 8424000000, + "beta": 3606000000, + "other": 5000000, + "total": 12035000000 + }, + "pass": true, + "failures": [], + "id": "busy-70-1000hz-r3", + "negative_control": { + "expected": { + "alpha": 0.6999990093231262, + "beta": 0.3000009906768738 + }, + "observed": { + "alpha": 0.2997506234413965, + "beta": 0.7002493765586035 + }, + "error_pp": { + "alpha": 40.02483858817297, + "beta": 40.024838588172976 + }, + "other_percent": 0.04154549231408392, + "weighted_periods": 12030.0, + "weights_ns": { + "alpha": 3606000000, + "beta": 8424000000, + "other": 5000000, + "total": 12035000000 + }, + "pass": false, + "failures": [ + "share_error" + ] + } + }, + { + "expected": { + "alpha": 0.699059667597603, + "beta": 0.30094033240239704 + }, + "observed": { + "alpha": 0.6997917534360683, + "beta": 0.3002082465639317 + }, + "error_pp": { + "alpha": 0.07320858384652906, + "beta": 0.07320858384653461 + }, + "other_percent": 0.016656950112434413, + "weighted_periods": 12005.0, + "weights_ns": { + "alpha": 8401000000, + "beta": 3604000000, + "other": 2000000, + "total": 12007000000 + }, + "pass": true, + "failures": [], + "id": "mixed-70-1000hz-r3", + "negative_control": { + "expected": { + "alpha": 0.699059667597603, + "beta": 0.30094033240239704 + }, + "observed": { + "alpha": 0.3002082465639317, + "beta": 0.6997917534360683 + }, + "error_pp": { + "alpha": 39.88514210336713, + "beta": 39.88514210336712 + }, + "other_percent": 0.016656950112434413, + "weighted_periods": 12005.0, + "weights_ns": { + "alpha": 3604000000, + "beta": 8401000000, + "other": 2000000, + "total": 12007000000 + }, + "pass": false, + "failures": [ + "share_error" + ] + } + }, + { + "expected": { + "alpha": 0.6966868790908607, + "beta": 0.3033131209091393 + }, + "observed": { + "alpha": 0.6981509245377311, + "beta": 0.30184907546226886 + }, + "error_pp": { + "alpha": 0.1464045446870399, + "beta": 0.14640454468704545 + }, + "other_percent": 0.0749063670411985, + "weighted_periods": 4002.0, + "weights_ns": { + "alpha": 27940000000, + "beta": 12080000000, + "other": 30000000, + "total": 40050000000 + }, + "pass": true, + "failures": [], + "id": "mixed-70-100hz-r2", + "negative_control": { + "expected": { + "alpha": 0.6966868790908607, + "beta": 0.3033131209091393 + }, + "observed": { + "alpha": 0.30184907546226886, + "beta": 0.6981509245377311 + }, + "error_pp": { + "alpha": 39.483780362859186, + "beta": 39.48378036285918 + }, + "other_percent": 0.0749063670411985, + "weighted_periods": 4002.0, + "weights_ns": { + "alpha": 12080000000, + "beta": 27940000000, + "other": 30000000, + "total": 40050000000 + }, + "pass": false, + "failures": [ + "share_error" + ] + } + }, + { + "expected": { + "alpha": 0.19897398926660292, + "beta": 0.8010260107333971 + }, + "observed": { + "alpha": 0.20941274468971263, + "beta": 0.7905872553102874 + }, + "error_pp": { + "alpha": 1.0438755423109707, + "beta": 1.043875542310968 + }, + "other_percent": 0.18292175937474017, + "weighted_periods": 12005.0, + "weights_ns": { + "alpha": 2514000000, + "beta": 9491000000, + "other": 22000000, + "total": 12027000000 + }, + "pass": true, + "failures": [], + "id": "busy-20-1000hz-r1", + "negative_control": { + "expected": { + "alpha": 0.19897398926660292, + "beta": 0.8010260107333971 + }, + "observed": { + "alpha": 0.7905872553102874, + "beta": 0.20941274468971263 + }, + "error_pp": { + "alpha": 59.16132660436845, + "beta": 59.16132660436845 + }, + "other_percent": 0.18292175937474017, + "weighted_periods": 12005.0, + "weights_ns": { + "alpha": 9491000000, + "beta": 2514000000, + "other": 22000000, + "total": 12027000000 + }, + "pass": false, + "failures": [ + "share_error" + ] + } + }, + { + "expected": { + "alpha": 0.20105171219429993, + "beta": 0.7989482878057 + }, + "observed": { + "alpha": 0.20179895061214292, + "beta": 0.7982010493878571 + }, + "error_pp": { + "alpha": 0.07472384178429936, + "beta": 0.07472384178429659 + }, + "other_percent": 0.02497918401332223, + "weighted_periods": 12007.0, + "weights_ns": { + "alpha": 2423000000, + "beta": 9584000000, + "other": 3000000, + "total": 12010000000 + }, + "pass": true, + "failures": [], + "id": "busy-20-1000hz-r3", + "negative_control": { + "expected": { + "alpha": 0.20105171219429993, + "beta": 0.7989482878057 + }, + "observed": { + "alpha": 0.7982010493878571, + "beta": 0.20179895061214292 + }, + "error_pp": { + "alpha": 59.71493371935571, + "beta": 59.71493371935571 + }, + "other_percent": 0.02497918401332223, + "weighted_periods": 12007.0, + "weights_ns": { + "alpha": 9584000000, + "beta": 2423000000, + "other": 3000000, + "total": 12010000000 + }, + "pass": false, + "failures": [ + "share_error" + ] + } + }, + { + "expected": { + "alpha": 0.6953816082232084, + "beta": 0.3046183917767917 + }, + "observed": { + "alpha": 0.6948450190618266, + "beta": 0.3051549809381734 + }, + "error_pp": { + "alpha": 0.053658916138177304, + "beta": 0.05365891613817175 + }, + "other_percent": 0.04142158893215144, + "weighted_periods": 12066.0, + "weights_ns": { + "alpha": 8384000000, + "beta": 3682000000, + "other": 5000000, + "total": 12071000000 + }, + "pass": true, + "failures": [], + "id": "busy-70-1000hz-r1", + "negative_control": { + "expected": { + "alpha": 0.6953816082232084, + "beta": 0.3046183917767917 + }, + "observed": { + "alpha": 0.3051549809381734, + "beta": 0.6948450190618266 + }, + "error_pp": { + "alpha": 39.0226627285035, + "beta": 39.02266272850349 + }, + "other_percent": 0.04142158893215144, + "weighted_periods": 12066.0, + "weights_ns": { + "alpha": 3682000000, + "beta": 8384000000, + "other": 5000000, + "total": 12071000000 + }, + "pass": false, + "failures": [ + "share_error" + ] + } + }, + { + "expected": { + "alpha": 0.20035604797910705, + "beta": 0.799643952020893 + }, + "observed": { + "alpha": 0.20044988752811796, + "beta": 0.799550112471882 + }, + "error_pp": { + "alpha": 0.009383954901090452, + "beta": 0.009383954901098779 + }, + "other_percent": 0.0, + "weighted_periods": 4001.0, + "weights_ns": { + "alpha": 8020000000, + "beta": 31990000000, + "other": 0, + "total": 40010000000 + }, + "pass": true, + "failures": [], + "id": "busy-20-100hz-r1", + "negative_control": { + "expected": { + "alpha": 0.20035604797910705, + "beta": 0.799643952020893 + }, + "observed": { + "alpha": 0.799550112471882, + "beta": 0.20044988752811796 + }, + "error_pp": { + "alpha": 59.91940644927749, + "beta": 59.9194064492775 + }, + "other_percent": 0.0, + "weighted_periods": 4001.0, + "weights_ns": { + "alpha": 31990000000, + "beta": 8020000000, + "other": 0, + "total": 40010000000 + }, + "pass": false, + "failures": [ + "share_error" + ] + } + }, + { + "expected": { + "alpha": 0.6998463701835007, + "beta": 0.30015362981649923 + }, + "observed": { + "alpha": 0.699268130405855, + "beta": 0.30073186959414505 + }, + "error_pp": { + "alpha": 0.0578239777645706, + "beta": 0.0578239777645817 + }, + "other_percent": 0.041566214980463874, + "weighted_periods": 12024.0, + "weights_ns": { + "alpha": 8408000000, + "beta": 3616000000, + "other": 5000000, + "total": 12029000000 + }, + "pass": true, + "failures": [], + "id": "busy-70-1000hz-r2", + "negative_control": { + "expected": { + "alpha": 0.6998463701835007, + "beta": 0.30015362981649923 + }, + "observed": { + "alpha": 0.30073186959414505, + "beta": 0.699268130405855 + }, + "error_pp": { + "alpha": 39.911450058935564, + "beta": 39.91145005893558 + }, + "other_percent": 0.041566214980463874, + "weighted_periods": 12024.0, + "weights_ns": { + "alpha": 3616000000, + "beta": 8408000000, + "other": 5000000, + "total": 12029000000 + }, + "pass": false, + "failures": [ + "share_error" + ] + } + }, + { + "expected": { + "alpha": 0.6998004586404231, + "beta": 0.30019954135957694 + }, + "observed": { + "alpha": 0.7001000500250125, + "beta": 0.2998999499749875 + }, + "error_pp": { + "alpha": 0.029959138458945933, + "beta": 0.029959138458945933 + }, + "other_percent": 0.05, + "weighted_periods": 3998.0, + "weights_ns": { + "alpha": 27990000000, + "beta": 11990000000, + "other": 20000000, + "total": 40000000000 + }, + "pass": true, + "failures": [], + "id": "busy-70-100hz-r1", + "negative_control": { + "expected": { + "alpha": 0.6998004586404231, + "beta": 0.30019954135957694 + }, + "observed": { + "alpha": 0.2998999499749875, + "beta": 0.7001000500250125 + }, + "error_pp": { + "alpha": 39.990050866543555, + "beta": 39.990050866543555 + }, + "other_percent": 0.05, + "weighted_periods": 3998.0, + "weights_ns": { + "alpha": 11990000000, + "beta": 27990000000, + "other": 20000000, + "total": 40000000000 + }, + "pass": false, + "failures": [ + "share_error" + ] + } + }, + { + "expected": { + "alpha": 0.6989876927189759, + "beta": 0.3010123072810242 + }, + "observed": { + "alpha": 0.6964241060265066, + "beta": 0.3035758939734934 + }, + "error_pp": { + "alpha": 0.2563586692469255, + "beta": 0.25635866924691997 + }, + "other_percent": 0.07496251874062969, + "weighted_periods": 3999.0, + "weights_ns": { + "alpha": 27850000000, + "beta": 12140000000, + "other": 30000000, + "total": 40020000000 + }, + "pass": true, + "failures": [], + "id": "mixed-70-100hz-r1", + "negative_control": { + "expected": { + "alpha": 0.6989876927189759, + "beta": 0.3010123072810242 + }, + "observed": { + "alpha": 0.3035758939734934, + "beta": 0.6964241060265066 + }, + "error_pp": { + "alpha": 39.54117987454825, + "beta": 39.54117987454824 + }, + "other_percent": 0.07496251874062969, + "weighted_periods": 3999.0, + "weights_ns": { + "alpha": 12140000000, + "beta": 27850000000, + "other": 30000000, + "total": 40020000000 + }, + "pass": false, + "failures": [ + "share_error" + ] + } + } + ] +} diff --git a/scripts/share-accuracy/README.md b/scripts/share-accuracy/README.md new file mode 100644 index 0000000..703ed7c --- /dev/null +++ b/scripts/share-accuracy/README.md @@ -0,0 +1,89 @@ +# Known-function wall-time shares + +Method: [METHOD.md](../../METHOD.md), signal layer C. This is a controlled accuracy experiment, +not an overhead comparison, capacity test, long soak or universal profiler accuracy guarantee. +The earlier exact-weight campaign is separate and is not repeated here. + +## Run + +Use sibling checkouts at `/workspace/tracewick`, `/workspace/agent` and `/workspace/benchmarks`. +Install the core's Composer dependencies. Core/agent source trees must be clean. Requires Python +3.12+, Go, Docker and a PHP CLI image with Excimer 1.2.7. Build the normal core stand PHP image +with `make -C ../tracewick stand-build PHP_VERSION=8.5` (no services need to be started), then: + +```bash +make bench-share-accuracy +# Or explicitly select prepared images and an unused loopback port: +python3 scripts/share-accuracy/run.py --php-image tracewick-php:8.5 \ + --pyroscope-image grafana/pyroscope:2.4.3 --port 14040 +``` + +The runner builds the current Go agent, records revisions/image IDs and its input file hashes, +starts its own fresh Pyroscope container, then executes the serial matrix. It refuses an occupied +port and removes only its own container on completion/failure. Do not run it on a host whose soak +is in progress. It does not operate the canonical Compose stand or contact the benchmark VPS. +Local evidence is under `reports/_local/share-/`; preserve a selected **complete** run in a +report before removing scratch output. Never publish the built agent binary or unrelated files. + +## Fixed matrix and acceptance + +Three workloads, two periods and three deterministic repetitions give **18 predeclared runs**: + +| Workload | Requested alpha/beta time | Beta implementation | +| --- | --- | --- | +| busy-70 | 70/30 | PHP loop | +| busy-20 | 20/80 | PHP loop | +| mixed-70 | 70/30 | `usleep` | + +- CLI sequential UoW, `sampleRate=1.0`, wall event, default depth 256, native flush threshold 1000. +- Periods: 10 ms (100 Hz), 1 ms (1000 Hz). +- Warm up both functions before sampling; then at least 40 seconds/run at 100 Hz and 12 seconds + at 1000 Hz. At least 3000/9000 weighted classified sampling periods, respectively. +- Deterministic seeds and a shuffled case order are saved before work starts. Every cycle has a + jittered total duration between 20 and 80 ms and randomized alpha/beta order to reduce phase + locking. Each repetition starts a fresh PHP process. +- The oracle sums `hrtime()` elapsed intervals around `shareAlpha` and `shareBeta` calls. Nominal + requested proportions are **not** the expected result: timer rounding, descheduling, callback + time and `usleep` overshoot belong to the actual elapsed-time reference. +- A real Go-agent drains the resulting spool to Pyroscope. The checker reads a unique service's + actual `SelectMergeStacktraces` flamegraph; it does not substitute source-profile counts. +- Use **inclusive** weights below each mutually exclusive phase marker. Child frames (including + Excimer's callbacks and the called C function) belong to the enclosing phase, so leaf self + weights alone are not the quantity being compared. +- Each phase's absolute error must be **<=5 percentage points** relative to the independently + measured alpha/beta elapsed-time split. Weight outside the two markers must be **<=1%** of the + backend total, preventing normalization from hiding missing attribution. Boundary comparisons + use integer cross-products to avoid floating-point rounding changing acceptance. +- Weighted periods are weight/period, **not independent Bernoulli observations**. No binomial + confidence interval or statistical-independence claim is made. Repetitions expose variability; + every individual run must pass, not just an average or selected seed. +- The swapped-symbol negative control preserves the total weight but must fail the share bound + for every run. Unit tests also cover hidden unclassified weight, small volume, exact thresholds, + malformed graphs and missing/overlapping markers. + +The source sink records per-phase counts only for diagnostics; it never defines the oracle. +Normal UoW stop/flush and automatic native-log callbacks are used; no reflection, sampler freeze +or callback replacement. An empty, dropped, failed or silently inactive profile fails the probe. + +Pyroscope's HTTP readiness does not guarantee immediate first-query visibility. A cold 2.4.3 +backend in this environment needed additional startup time before ProfileTypes exposed ingested +data; the runner allows up to 300 seconds for readback and saves raw responses. This wait is +outside the captured workload and does not relax accuracy or sample-volume thresholds. + +## Evidence and limits + +Keep the complete manifest, all 18 oracle/spec/Querier/result files and the summary. The oracle +contains each cycle's measured durations/order, runtime versions and profiler diagnostics. Startup +or aborted setup probes are not completed matrix results and must not be promoted to passes. + +This establishes aggregate wall-time attribution for the recorded CLI workloads/runtime/revisions. +It does not establish arbitrary C-call timelines (core ADR 11), CPU-mode accuracy, low-rate request +sampling representativeness, FPM/RR/Swoole accuracy, overhead, production UID behavior on another +host, tail latency, stability or final-RC certification. Revisit affected evidence when the final +candidate changes these paths. Retain historical measurements as measurements of their own pins. + +The report figure is optional and requires Matplotlib (not needed for capture or validation): + +```bash +python3 scripts/share-accuracy/plot.py reports//summary.json errors.svg +``` diff --git a/scripts/share-accuracy/analyze.py b/scripts/share-accuracy/analyze.py new file mode 100644 index 0000000..639c6b7 --- /dev/null +++ b/scripts/share-accuracy/analyze.py @@ -0,0 +1,55 @@ +"""Strict, independent analysis of actual Pyroscope flamegraph node weights.""" + +PHASES = {'shareAlpha': 'alpha', 'shareBeta': 'beta'} +MAX_ERROR_PP = 5 +MAX_OTHER_PERCENT = 1 + + +def phase_weights(response): + graph = response['flamegraph'] + total = int(graph['total']) + if total <= 0: + raise ValueError('Empty profile') + names = graph['names'] + weights = {'alpha': 0, 'beta': 0} + for level in graph['levels']: + row = level['values'] + if len(row) % 4: + raise ValueError('Malformed flamegraph tuples') + for offset in range(0, len(row), 4): + width, own, name_id = map(int, row[offset + 1:offset + 4]) + if width < 0 or own < 0 or own > width or name_id < 0 or name_id >= len(names): + raise ValueError('Invalid node') + phase = PHASES.get(names[name_id]) + if phase: + weights[phase] += width + if min(weights.values()) <= 0 or sum(weights.values()) > total: + raise ValueError('Missing, overlapping or invalid phase weights') + return weights | {'other': total - sum(weights.values()), 'total': total} + + +def assess(oracle, weights): + measured = oracle['elapsed_ns'] + duration = sum(measured.values()) + classified = weights['alpha'] + weights['beta'] + total = weights['total'] + if duration <= 0 or min(measured.values()) <= 0 or classified <= 0 or total <= 0: + raise ValueError('Invalid oracle or observations') + expected = {p: measured[p] / duration for p in ('alpha', 'beta')} + observed = {p: weights[p] / classified for p in ('alpha', 'beta')} + errors = {p: abs(expected[p] - observed[p]) * 100 for p in expected} + other_percent = weights['other'] / total * 100 + effective_periods = classified / oracle['spec']['period_ns'] + floor = oracle['spec']['min_periods'] + failures = [] + # Integer cross-products keep the inclusive 5 pp boundary exact. + if any(abs(measured[p] * classified - weights[p] * duration) * 100 + > MAX_ERROR_PP * duration * classified for p in expected): + failures.append('share_error') + if weights['other'] * 100 > MAX_OTHER_PERCENT * total: + failures.append('unclassified_weight') + if classified < floor * oracle['spec']['period_ns']: + failures.append('insufficient_period_weight') + return {'expected': expected, 'observed': observed, 'error_pp': errors, + 'other_percent': other_percent, 'weighted_periods': effective_periods, + 'weights_ns': weights, 'pass': not failures, 'failures': failures} diff --git a/scripts/share-accuracy/capture.php b/scripts/share-accuracy/capture.php new file mode 100644 index 0000000..d5ac01a --- /dev/null +++ b/scripts/share-accuracy/capture.php @@ -0,0 +1,106 @@ + 0, 'beta' => 0, 'other' => 0]; + public function __construct(private readonly SpoolSink $spool) {} + public function send(Profile $profile): Delivery + { + foreach ($profile->stacks as $stack) { + $markers = []; + foreach ($stack->frameIds as $id) { + $name = $profile->frames[$id]->name(); + if ($name === 'shareAlpha') { $markers['alpha'] = true; } + if ($name === 'shareBeta') { $markers['beta'] = true; } + } + if (count($markers) > 1) { throw new RuntimeException('Nested phase markers'); } + $phase = array_key_first($markers) ?? 'other'; + $this->events[$phase] += $stack->count; + } + return $this->spool->send($profile); + } +} + +$spec = json_decode(file_get_contents($argv[1]), true, flags: JSON_THROW_ON_ERROR); +$out = $argv[2]; +if (!extension_loaded('excimer')) { throw new RuntimeException('Excimer is required for this probe'); } +mt_srand($spec['seed']); +// Warm up both functions before the measured/profiled region. +shareAlpha(500_000_000); +shareBeta(500_000_000, $spec['sleep_beta']); +$sink = new ShareSink(new SpoolSink($spec['application'], new SpoolConfig($out . '/spool'))); +$profiler = new UnitOfWorkProfiler( + new ExcimerSampler(new SamplerConfig(periodNs: $spec['period_ns'], maxSamples: 1_000)), + $sink, + new ProfilerConfig(sampleRate: 1.0), +); +$elapsed = ['alpha' => 0, 'beta' => 0]; +$cycles = []; +$profiler->start(); +$started = hrtime(true); +do { + $cycle = mt_rand(20_000, 80_000) * 1_000; + $alpha = intdiv($cycle * $spec['alpha_percent'], 100); + $order = mt_rand(0, 1) === 0 ? ['alpha', 'beta'] : ['beta', 'alpha']; + $measured = []; + foreach ($order as $phase) { + $before = hrtime(true); + if ($phase === 'alpha') { shareAlpha($alpha); } + else { shareBeta($cycle - $alpha, $spec['sleep_beta']); } + // The oracle reads elapsed wall time, never the sampler or native log. + $duration = hrtime(true) - $before; + $elapsed[$phase] += $duration; + $measured[$phase] = $duration; + } + $cycles[] = ['requested_ns' => $cycle, 'order' => $order, 'elapsed_ns' => $measured]; +} while (hrtime(true) - $started < $spec['duration_ns']); +$workNs = hrtime(true) - $started; +$profiler->stop(); +$profiler->flush(); +$d = $profiler->diagnostics(); +$result = [ + 'spec' => $spec, + 'elapsed_ns' => $elapsed, + 'work_ns' => $workNs, + 'source_events' => $sink->events, + 'diagnostics' => get_object_vars($d), + 'cycles' => $cycles, + 'runtime' => ['php' => PHP_VERSION, 'excimer' => phpversion('excimer'), + 'jit' => ini_get('opcache.jit'), 'opcache_cli' => ini_get('opcache.enable_cli')], +]; +file_put_contents($out . '/oracle.json', json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR) . "\n"); +if ($d->collectedProfiles !== 1 || $d->deliveredProfiles !== 1 || $d->swallowedErrors !== 0 + || $d->droppedProfiles !== 0 || $d->failedProfiles !== 0 || $d->samplerFailures !== 0 + || $d->inactiveSampler !== null) { + throw new RuntimeException('Unexpected profiler diagnostics'); +} diff --git a/scripts/share-accuracy/plot.py b/scripts/share-accuracy/plot.py new file mode 100644 index 0000000..f29167a --- /dev/null +++ b/scripts/share-accuracy/plot.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +"""Optional report figure from the complete summary; requires Matplotlib.""" +import argparse +import json +import pathlib + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('summary', type=pathlib.Path) + parser.add_argument('output', type=pathlib.Path) + args = parser.parse_args() + summary = json.loads(args.summary.read_text()) + if not summary['complete'] or len(summary['results']) != 18: + raise ValueError('Only complete 18-run evidence can be plotted') + import matplotlib + matplotlib.use('Agg') + import matplotlib.pyplot as plt + fig, ax = plt.subplots(figsize=(11, 4.5)) + keys = [(scenario, hz) for scenario in ('busy-70', 'busy-20', 'mixed-70') for hz in (100, 1000)] + for index, (scenario, hz) in enumerate(keys): + rows = [r for r in summary['results'] if r['id'].startswith(f'{scenario}-{hz}hz-')] + if len(rows) != 3: + raise ValueError('Missing matrix cell') + for offset, result in zip((-0.15, 0, 0.15), sorted(rows, key=lambda r: r['id'])): + ax.scatter(index + offset, max(result['error_pp'].values()), color='#146b99', s=45, zorder=3) + ax.axhline(5, color='#b73c2f', linestyle='--', label='Per-run acceptance limit: 5 pp') + ax.set_xticks(range(len(keys)), [f'{s}\n{hz} Hz' for s, hz in keys]) + ax.set_ylabel('Absolute wall-time share error (percentage points)') + ax.set_ylim(-0.1, 5.5) + ax.set_title('Known-function wall-time shares: all 18 predeclared runs') + ax.grid(axis='y', alpha=0.25) + ax.legend(loc='upper right') + fig.tight_layout() + if args.output.suffix == '.svg': + fig.savefig(args.output, metadata={'Date': None, 'Creator': None}) + args.output.write_text('\n'.join(line.rstrip() for line in args.output.read_text().splitlines()) + '\n') + else: + fig.savefig(args.output) + plt.close(fig) + + +if __name__ == '__main__': + main() diff --git a/scripts/share-accuracy/run.py b/scripts/share-accuracy/run.py new file mode 100644 index 0000000..ed8e5a3 --- /dev/null +++ b/scripts/share-accuracy/run.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python3 +"""Serial, isolated known-function-share experiment. Not a load/overhead run.""" +import argparse +import copy +import datetime +import hashlib +import importlib.util +import json +import os +import pathlib +import platform +import random +import socket +import subprocess +import time +import urllib.error +import urllib.request + +HERE = pathlib.Path(__file__).resolve().parent +BENCH = HERE.parents[1] +WORKSPACE = BENCH.parent +spec = importlib.util.spec_from_file_location('share_analysis', HERE / 'analyze.py') +analysis = importlib.util.module_from_spec(spec) +spec.loader.exec_module(analysis) +OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({})) + + +def command(args, **kwargs): + return subprocess.check_output(args, text=True, **kwargs).strip() + + +def write(path, value): + path.write_text(json.dumps(value, indent=2) + '\n') + + +def query(base, method, body): + req = urllib.request.Request(base + '/querier.v1.QuerierService/' + method, + json.dumps(body).encode(), {'Content-Type': 'application/json'}) + with OPENER.open(req, timeout=15) as response: + return json.load(response) + + +def matrix(run_id): + cases = [] + for hz in (100, 1000): + for name, share, sleep in [('busy-70', 70, False), ('busy-20', 20, False), ('mixed-70', 70, True)]: + for repeat in range(1, 4): + key = f'{name}-{hz}hz-r{repeat}' + cases.append({'id': key, 'application': f'share-{run_id}-{key}', + 'seed': 83000 + len(cases), 'period_ns': 1_000_000_000 // hz, + 'duration_ns': (40 if hz == 100 else 12) * 1_000_000_000, + 'min_periods': 3000 if hz == 100 else 9000, + 'alpha_percent': share, 'sleep_beta': sleep}) + random.Random(411).shuffle(cases) + return cases + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--php-image', default='tracewick-uow-php:8.5') + parser.add_argument('--pyroscope-image', default='grafana/pyroscope:2.4.3') + parser.add_argument('--port', type=int, default=14040) + args = parser.parse_args() + with socket.socket() as probe: + probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + probe.bind(('127.0.0.1', args.port)) + run_id = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ') + out = BENCH / 'reports' / '_local' / ('share-' + run_id) + out.mkdir(parents=True) + revisions = {} + for name in ('tracewick', 'agent'): + repo = WORKSPACE / name + if command(['git', 'status', '--porcelain'], cwd=repo): + raise RuntimeError(f'{name} must have a clean source tree') + revisions[name] = command(['git', 'rev-parse', 'HEAD'], cwd=repo) + revisions['benchmarks_base'] = command(['git', 'rev-parse', 'HEAD'], cwd=BENCH) + image_ids = {key: command(['docker', 'image', 'inspect', value, '--format', '{{.Id}}']) + for key, value in [('php', args.php_image), ('pyroscope', args.pyroscope_image)]} + manifest = {'revisions': revisions, 'images': vars(args), 'image_ids': image_ids, + 'host': {'platform': platform.platform(), 'cpus_visible': os.cpu_count()}, + 'files_sha256': {p.name: hashlib.sha256(p.read_bytes()).hexdigest() + for p in HERE.glob('*') if p.is_file()}, + 'matrix': matrix(run_id), 'run_id': run_id, + 'thresholds': {'max_error_pp': analysis.MAX_ERROR_PP, + 'max_other_percent': analysis.MAX_OTHER_PERCENT}} + write(out / 'manifest.json', manifest) + agent = out / 'tracewick-agent' + subprocess.run(['go', 'build', '-o', str(agent), './cmd/tracewick-agent'], + cwd=WORKSPACE / 'agent', check=True) + name = 'share-pyroscope-' + run_id.lower() + base = 'http://127.0.0.1:' + str(args.port) + results = [] + try: + subprocess.run(['docker', 'run', '-d', '--name', name, '-p', f'127.0.0.1:{args.port}:4040', + '-e', 'HTTP_PROXY=', '-e', 'HTTPS_PROXY=', '-e', 'ALL_PROXY=', '-e', 'NO_PROXY=*', + args.pyroscope_image, '-server.http-listen-port=4040', + '-metastore.min-ready-duration=0', '-ingester.min-ready-duration=0', + '-segment-writer.min-ready-duration=0'], check=True, stdout=subprocess.DEVNULL) + deadline = time.monotonic() + 90 + while True: + try: + with OPENER.open(base + '/ready', timeout=2) as response: + if response.status == 200: + break + except (OSError, urllib.error.HTTPError): + if time.monotonic() >= deadline: + raise + time.sleep(1) + for i, case in enumerate(manifest['matrix'], 1): + directory = out / case['id'] + directory.mkdir() + write(directory / 'spec.json', case) + with (directory / 'capture.log').open('w') as log: + subprocess.run(['docker', 'run', '--rm', '--user', f'{os.getuid()}:{os.getgid()}', + '-v', f'{WORKSPACE}:/workspace', '-w', '/workspace/benchmarks', args.php_image, + 'php', '/workspace/benchmarks/scripts/share-accuracy/capture.php', + str(directory / 'spec.json'), str(directory)], + check=True, stdout=log, stderr=subprocess.STDOUT, timeout=120) + oracle = json.loads((directory / 'oracle.json').read_text()) + with (directory / 'agent.log').open('w') as log: + subprocess.run([str(agent), 'run', '--once', '--spool-dir=' + str(directory / 'spool'), + '--pyroscope-url=' + base, '--reader-id=share-check'], + check=True, stdout=log, stderr=subprocess.STDOUT, timeout=90) + if list((directory / 'spool').rglob('*.spool')) or list((directory / 'spool').rglob('*.claimed-*')): + raise RuntimeError('Unacknowledged spool remains') + deadline = time.monotonic() + 300 + while True: + now = int(time.time() * 1000) + types = query(base, 'ProfileTypes', {'start': now - 3600000, 'end': now + 60000}) + write(directory / 'profile-types.json', types) + ids = [t.get('ID', t.get('id')) for t in types.get('profileTypes', []) + if t.get('name') == 'wall' and t.get('sampleUnit') == 'nanoseconds'] + if ids: + response = query(base, 'SelectMergeStacktraces', { + 'profileTypeID': ids[0], 'labelSelector': '{service_name="' + case['application'] + '"}', + 'start': now - 3600000, 'end': now + 60000}) + write(directory / 'querier.json', response) + if int(response.get('flamegraph', {}).get('total', 0)) > 0: + break + if time.monotonic() >= deadline: + raise RuntimeError('No live backend profile') + time.sleep(1) + weights = analysis.phase_weights(response) + result = analysis.assess(oracle, weights) + # A deliberate label swap preserves total signal but must fail share validation. + swapped = copy.deepcopy(weights) + swapped['alpha'], swapped['beta'] = weights['beta'], weights['alpha'] + negative = analysis.assess(oracle, swapped) + if 'share_error' not in negative['failures']: + raise RuntimeError('Swapped-symbol negative control did not fail') + result.update({'id': case['id'], 'negative_control': negative}) + write(directory / 'result.json', result) + results.append(result) + write(out / 'summary.json', {'complete': len(results) == len(manifest['matrix']), + 'pass': len(results) == len(manifest['matrix']) and all(r['pass'] for r in results), + 'results': results}) + print(f"{i}/18 {case['id']}: error={max(result['error_pp'].values()):.3f}pp " + f"other={result['other_percent']:.3f}% periods={result['weighted_periods']:.0f} " + f"{'PASS' if result['pass'] else 'FAIL'}", flush=True) + if not all(r['pass'] for r in results): + raise SystemExit('Share accuracy gate failed; all runs retained at ' + str(out)) + print('PASS: all 18 predeclared runs; artifacts: ' + str(out), flush=True) + finally: + exists = subprocess.run(['docker', 'inspect', name], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + if exists.returncode == 0: + (out / 'pyroscope.log').write_text(command(['docker', 'logs', name], stderr=subprocess.STDOUT)) + subprocess.run(['docker', 'rm', '-f', name], check=True, stdout=subprocess.DEVNULL) + + +if __name__ == '__main__': + main() diff --git a/tests/test_share_accuracy.py b/tests/test_share_accuracy.py new file mode 100644 index 0000000..140575e --- /dev/null +++ b/tests/test_share_accuracy.py @@ -0,0 +1,99 @@ +"""The share checker must reject a wrong split even when total weight is preserved.""" +import importlib.util +import pathlib +import unittest + +ROOT = pathlib.Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location('share_analysis', ROOT / 'scripts/share-accuracy/analyze.py') +analysis = importlib.util.module_from_spec(spec) +spec.loader.exec_module(analysis) + + +def graph(alpha=7000, beta=3000, other=0): + total = alpha + beta + other + return {'flamegraph': {'names': ['total', 'shareAlpha', 'shareBeta', 'leaf'], 'total': str(total), + 'levels': [{'values': [0, total, other, 0]}, + {'values': [0, alpha, 0, 1, alpha, beta, beta, 2]}, + {'values': [0, alpha, alpha, 3]}]}} + + +def oracle(): + return {'elapsed_ns': {'alpha': 7_000_000, 'beta': 3_000_000}, + 'spec': {'period_ns': 1, 'min_periods': 3000}} + + +class ShareAccuracyTest(unittest.TestCase): + def test_uses_inclusive_phase_weight_not_leaf_self_weight(self): + weights = analysis.phase_weights(graph()) + self.assertEqual(weights, {'alpha': 7000, 'beta': 3000, 'other': 0, 'total': 10000}) + self.assertTrue(analysis.assess(oracle(), weights)['pass']) + + def test_swapped_symbols_fail_while_total_stays_equal(self): + weights = analysis.phase_weights(graph(alpha=3000, beta=7000)) + result = analysis.assess(oracle(), weights) + self.assertEqual(weights['total'], 10000) + self.assertEqual(result['failures'], ['share_error']) + self.assertAlmostEqual(result['error_pp']['alpha'], 40) + + def test_hidden_unclassified_weight_fails_despite_correct_normalized_split(self): + result = analysis.assess(oracle(), analysis.phase_weights(graph(other=10000))) + self.assertEqual(result['failures'], ['unclassified_weight']) + self.assertEqual(result['error_pp']['alpha'], 0) + + def test_too_few_weighted_periods_fail(self): + result = analysis.assess(oracle(), analysis.phase_weights(graph(alpha=700, beta=300))) + self.assertEqual(result['failures'], ['insufficient_period_weight']) + + def test_reference_comes_from_elapsed_time_not_nominal_ratio(self): + reference = oracle() + reference['elapsed_ns'] = {'alpha': 3, 'beta': 7} + reference['spec']['alpha_percent'] = 70 + result = analysis.assess(reference, analysis.phase_weights(graph(alpha=3000, beta=7000))) + self.assertTrue(result['pass']) + + def test_exactly_five_percentage_points_pass(self): + self.assertTrue(analysis.assess(oracle(), analysis.phase_weights(graph(alpha=7500, beta=2500)))['pass']) + + def test_just_above_five_percentage_points_fails(self): + self.assertIn('share_error', analysis.assess(oracle(), analysis.phase_weights(graph(alpha=7501, beta=2499)))['failures']) + + def test_exactly_one_percent_unclassified_passes(self): + self.assertTrue(analysis.assess(oracle(), analysis.phase_weights(graph(alpha=6930, beta=2970, other=100)))['pass']) + + def test_just_above_one_percent_unclassified_fails(self): + self.assertIn('unclassified_weight', analysis.assess(oracle(), analysis.phase_weights(graph(alpha=6930, beta=2970, other=101)))['failures']) + + def test_exactly_minimum_period_weight_passes(self): + self.assertTrue(analysis.assess(oracle(), analysis.phase_weights(graph(alpha=2100, beta=900)))['pass']) + + def test_fixed_matrix_contains_every_cell_and_unique_seed(self): + runner_spec = importlib.util.spec_from_file_location('share_runner', ROOT / 'scripts/share-accuracy/run.py') + runner = importlib.util.module_from_spec(runner_spec) + runner_spec.loader.exec_module(runner) + cases = runner.matrix('test') + self.assertEqual(len(cases), 18) + self.assertEqual(len({c['seed'] for c in cases}), 18) + self.assertEqual(len({c['id'] for c in cases}), 18) + for period in (10000000, 1000000): + for share, sleep in ((70, False), (20, False), (70, True)): + self.assertEqual(sum(c['period_ns'] == period and c['alpha_percent'] == share and c['sleep_beta'] == sleep for c in cases), 3) + + def test_missing_phase_is_not_reported_as_zero_error(self): + with self.assertRaises(ValueError): + analysis.phase_weights(graph(beta=0)) + + def test_overlapping_phase_nodes_are_rejected(self): + value = graph() + value['flamegraph']['levels'].append({'values': [0, 7000, 0, 1]}) + with self.assertRaises(ValueError): + analysis.phase_weights(value) + + def test_malformed_graph_is_rejected(self): + value = graph() + value['flamegraph']['levels'][0]['values'].append(10) + with self.assertRaises(ValueError): + analysis.phase_weights(value) + + +if __name__ == '__main__': + unittest.main()