From a2a475f624e3f6dab9f244e35c6d6af68f00dc68 Mon Sep 17 00:00:00 2001 From: Alexandr Date: Tue, 17 Nov 2026 17:58:00 +0300 Subject: [PATCH 1/3] feat: add observed soak telemetry and validity gates --- .env.example | 14 +- .github/workflows/checks.yml | 22 ++ .gitignore | 2 + CONTRIBUTING.md | 6 + LIMITATIONS.md | 10 + METHOD.md | 11 + Makefile | 27 ++- README.md | 27 +-- compose.yaml | 21 +- docs/soak.md | 158 +++++++++++++ generators/k6/soak.js | 14 +- scenarios/README.md | 2 +- scripts/plot-soak.py | 52 +++++ scripts/run-soak-legacy.sh | 179 +++++++++++++++ scripts/run-soak-matrix.sh | 2 +- scripts/run-soak.sh | 171 +------------- scripts/soak.py | 428 +++++++++++++++++++++++++++++++++++ scripts/soak_probe.sh | 29 +++ scripts/soak_spool.php | 39 ++++ scripts/soaklib.py | 288 +++++++++++++++++++++++ stand/agent/Dockerfile | 31 ++- stand/app/Dockerfile | 32 ++- stand/app/install-excimer.sh | 22 ++ stand/app/worker.php | 2 + tests/test_soak.py | 151 ++++++++++++ 25 files changed, 1517 insertions(+), 223 deletions(-) create mode 100644 .github/workflows/checks.yml create mode 100644 docs/soak.md create mode 100644 scripts/plot-soak.py create mode 100755 scripts/run-soak-legacy.sh create mode 100644 scripts/soak.py create mode 100644 scripts/soak_probe.sh create mode 100644 scripts/soak_spool.php create mode 100644 scripts/soaklib.py create mode 100644 stand/app/install-excimer.sh create mode 100644 tests/test_soak.py diff --git a/.env.example b/.env.example index e048620..d0dc990 100644 --- a/.env.example +++ b/.env.example @@ -1,6 +1,6 @@ # Copy to .env for local overrides. Never commit .env. -# Pinned Tracewick package version used by the workload app (must match stand/app/composer.json). +# Actual Composer package constraint used by image builds (exact source refs supported). TRACEWICK_VERSION=0.1.0 # Image pins (defaults match compose.yaml). @@ -40,3 +40,15 @@ TRACEWICK_SPOOL_MAX_FILES=500 # M3 chaos: drain URL override (default http://pyroscope:4040) # TRACEWICK_PYROSCOPE_URL=http://toxiproxy:14040 + +# Observed soak requires explicit exported pins; see docs/soak.md. +# TRACEWICK_VERSION=dev-develop# +# AGENT_REF= +# AGENT_VERSION=0.2.1 # release mode, when AGENT_REF is unset +# EXCIMER_REF= # optional exact source build +# EXCIMER_VERSION=1.2.7 +# BASELINE_DURATION=5m +# WARMUP_DURATION=5m +# COOLDOWN_DURATION=2m +# DRAIN_TIMEOUT=2m +# STATS_INTERVAL=15 diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml new file mode 100644 index 0000000..42ffac9 --- /dev/null +++ b/.github/workflows/checks.yml @@ -0,0 +1,22 @@ +name: Checks +on: + pull_request: + push: + branches: [main] +permissions: + contents: read +jobs: + checks: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v6 + with: + python-version: '3.12' + - name: Soak regression tests + run: python3 -m unittest discover -s tests -v + - name: Shell syntax and Compose configuration + run: | + bash -n scripts/run-soak.sh scripts/run-soak-matrix.sh scripts/run-soak-legacy.sh + sh -n scripts/soak_probe.sh + docker compose config --quiet diff --git a/.gitignore b/.gitignore index 4fdb99b..a75accd 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,5 @@ Thumbs.db # Cursor / agent scratch .cursor/ scripts/__pycache__/ + +tests/__pycache__/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 155a2e5..9708aef 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -28,3 +28,9 @@ k6 runs via a pinned Docker image (`K6_IMAGE` in the Makefile). Host-installed k - Link the scenario / report you changed. - If you change methodology, update `METHOD.md` and call it out in the PR. - Library API changes belong upstream in [tracewick/tracewick](https://github.com/tracewick/tracewick) — open an issue there rather than forking behavior here. + +For observed-soak changes, run `make check-soak` and a short real-Excimer +RR/agent/Pyroscope pilot using [docs/soak.md](docs/soak.md). Include negative +controls for worker replacement or missing telemetry when changing validity gates. +A managed shared-cgroup smoke is harness evidence only, never resource attribution +or a completed long soak. Optional plotting needs Matplotlib after collection. diff --git a/LIMITATIONS.md b/LIMITATIONS.md index e6ea00c..468d47a 100644 --- a/LIMITATIONS.md +++ b/LIMITATIONS.md @@ -38,3 +38,13 @@ capacity, or 72h stability. - Secrets never belong in git; use `.env` from `.env.example`. - Toxiproxy chaos scenarios are optional and documented when enabled; default smoke does not require them. + +## Observed-soak instrumentation + +The new [soak runner](docs/soak.md) separates process RSS from cgroup memory and +checks worker/container continuity. Historical Docker-stats CSVs do not provide +per-process RSS, FD, thread, queue or restart evidence. Current instrumentation +does not retroactively close the 72h depth-48 gate. Shared-cgroup managed runners +can test the harness only; resource attribution must be validated on the actual +Linux benchmark server. k6 REST quantiles are cumulative, not hourly quantiles; +Go goroutine/heap and FPM/Swoole writer-drop totals are not collected. diff --git a/METHOD.md b/METHOD.md index 490035b..63b66e7 100644 --- a/METHOD.md +++ b/METHOD.md @@ -73,3 +73,14 @@ Use `reports/TEMPLATE.md`. Every checked-in report should record: - Metric table for layers A/B (and C if checked) - Screenshots (relative paths under `reports/…`) - Honesty paragraph: what was *not* measured + +## Observed soak validity + +The [observed-soak runbook](docs/soak.md) specifies exact source/runtime identity, +a short unprofiled baseline, profiling warmup, steady load, drain and cooldown. +Process RSS/anonymous memory are separate from container memory. Worker recycling, +container changes, missing telemetry and undelivered work invalidate continuity. +Record both first/last windows and whole-series growth slopes, CPU per completed +k6 HTTP request, queue and delivery counters. A valid observation is not an +automatic leak-free verdict; the elapsed steady duration and resource trends must +be reviewed. No new 72-hour result is implied by adding this instrumentation. diff --git a/Makefile b/Makefile index ba5b58b..4681704 100644 --- a/Makefile +++ b/Makefile @@ -17,7 +17,7 @@ PYROSCOPE_PORT ?= 4040 RATE ?= 20 DURATION ?= 2m -.PHONY: 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: 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) @@ -142,16 +142,16 @@ bench-chaos: ## M3 optional: Toxiproxy latency toward Pyroscope (READER=drain|ag READER="$${READER:-drain}" \ ./scripts/run-chaos-pyroscope.sh -bench-soak: ## Soak: fixed RPS + workload/reader RSS·CPU (RUNTIME=fpm|rr|swoole READER=drain|agent) +bench-soak: ## Observed soak: explicit pins + process/queue/CPU telemetry (default RR + agent) @chmod +x scripts/run-soak.sh scripts/sample-container-stats.sh scripts/summarize-soak.py scripts/ensure-reader.sh scripts/recreate-workload.sh - RATE="$${RATE:-10}" DURATION="$${DURATION:-72h}" BASE_URL="$(BASE_URL)" K6_IMAGE="$(K6_IMAGE)" \ - COMPOSE="$(COMPOSE)" REPORTS_DIR="$(REPORTS_DIR)" STATS_INTERVAL="$${STATS_INTERVAL:-60}" \ + RATE="$${RATE:-10}" DURATION="$${DURATION:-72h}" BASE_URL="$${BASE_URL:-}" K6_IMAGE="$(K6_IMAGE)" \ + COMPOSE="$(COMPOSE)" REPORTS_DIR="$(REPORTS_DIR)" STATS_INTERVAL="$${STATS_INTERVAL:-15}" \ TRACEWICK_SAMPLE_RATE="$${TRACEWICK_SAMPLE_RATE:-0.1}" \ - READER="$${READER:-drain}" RUNTIME="$${RUNTIME:-fpm}" \ - WORK_STACK_DEPTH="$${WORK_STACK_DEPTH:-0}" \ - PHP_FPM_MAX_CHILDREN="$${PHP_FPM_MAX_CHILDREN:-4}" \ - RR_NUM_WORKERS="$${RR_NUM_WORKERS:-4}" \ - SWOOLE_WORKER_NUM="$${SWOOLE_WORKER_NUM:-4}" \ + READER="$${READER:-agent}" RUNTIME="$${RUNTIME:-rr}" \ + WORK_STACK_DEPTH="$${WORK_STACK_DEPTH:-48}" \ + PHP_FPM_MAX_CHILDREN="$${PHP_FPM_MAX_CHILDREN:-1}" \ + RR_NUM_WORKERS="$${RR_NUM_WORKERS:-1}" \ + SWOOLE_WORKER_NUM="$${SWOOLE_WORKER_NUM:-1}" \ ./scripts/run-soak.sh bench-rps: ## High-RPS pipeline: deep stacks + spool (RUNTIME=fpm|rr|swoole READER=drain|agent|off) @@ -188,3 +188,12 @@ collect-report: ## Gather local host meta under reports/_local/ @echo "BASE_URL=$(BASE_URL)" >> "$(CURDIR)/$(REPORTS_DIR)/meta.txt" @git rev-parse HEAD >> "$(CURDIR)/$(REPORTS_DIR)/meta.txt" 2>/dev/null || true @echo "Wrote $(REPORTS_DIR)/uname.txt and meta.txt" + +check-soak: ## Soak telemetry/validity regression tests and configuration syntax + python3 -m unittest discover -s tests -v + bash -n scripts/run-soak.sh scripts/run-soak-legacy.sh scripts/run-soak-matrix.sh + sh -n scripts/soak_probe.sh stand/app/install-excimer.sh + $(COMPOSE) config --quiet + +plot-soak: ## Render preserved soak telemetry (RUN_DIR=..., requires python3-matplotlib) + python3 scripts/plot-soak.py "$(RUN_DIR)" diff --git a/README.md b/README.md index cdceac7..8b3dbf8 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ cp .env.example .env # optional make up # build + Pyroscope + Grafana + PHP workload + drain make bench-smoke # wiring smoke (profiles → Pyroscope) make bench-overhead # M2: baseline vs on @ fixed RPS (~2× duration) -make bench-soak # soak: RSS/CPU series (default 10 RPS / 72h; use tmux) +# Long soaks run separately: see docs/soak.md for pins and the pilot. make down ``` @@ -63,29 +63,22 @@ reports/ checked-in reports; local scratch under reports/_local/ | `make bench-overhead` | M2 A/B at `RATE` req/s (default 20) for `DURATION` (default `2m`) | | `make bench-spool-pressure` | M3: stop drain, fill spool, measure catch-up | | `make bench-chaos` | M3: Toxiproxy latency toward Pyroscope | -| `make bench-soak` | Soak: fixed RPS + FPM/drain RSS·CPU (default `10` / `72h`) | +| `make bench-soak` | Observed soak: explicit pins, RR/agent by default; [runbook](docs/soak.md) | | `make bench-rps` | High-RPS pipeline: deep stacks + spool series (default `500` / `5m`) | | `make collect-report` | Stash host meta under `reports/_local/` | -### Soak (manual / tmux) +### Observed soak (manual) -Run on the VPS outside an IDE terminal so logout does not kill k6: - -```bash -cd /root/benchmarks && git pull --ff-only && make up -tmux new -s soak -# inside tmux: -make bench-soak -# Detach: Ctrl-b d | Reattach: tmux attach -t soak -# Agent + depth-48 short matrix (FPM → RR → Swoole), e.g. 6h each: -# DURATION=6h RATE=10 READER=agent WORK_STACK_DEPTH=48 ./scripts/run-soak-matrix.sh -``` - -Defaults: `RATE=10`, `DURATION=72h`, `STATS_INTERVAL=60`, `sampleRate=0.1`. `RUNTIME=fpm|rr|swoole`, `READER=drain|agent`. Artifacts: `reports/_local/soak-/` and `soak-latest.md`. +Follow [docs/soak.md](docs/soak.md): explicit source pins → short pilot → calibrated +72-hour run under tmux. The runner starts its own Compose project; do not run +`make up` alongside it on the same ports. Defaults: RR/agent, one RR worker, +depth 48, sample rate 0.1, 15-second telemetry. Raw evidence and validity/resource +reports are under `reports/_local/soak-/`. `make check-soak` runs regression +checks; `make plot-soak RUN_DIR=...` renders preserved telemetry. ### High-RPS pipeline (manual) -Uses the same `/work` wall budget (`WORK_BUSY_MS` / `WORK_SLEEP_MS`) as overhead/soak. Opt-in `WORK_STACK_DEPTH` deepens call stacks so spool payloads are larger (closer to a real app). Default scenarios keep `WORK_STACK_DEPTH=0`. +Uses the same `/work` wall budget (`WORK_BUSY_MS` / `WORK_SLEEP_MS`) as overhead/soak. Opt-in `WORK_STACK_DEPTH` deepens call stacks so spool payloads are larger (closer to a real app). Other legacy scenarios keep `WORK_STACK_DEPTH=0`; observed soak defaults to 48. **Honesty:** these runs are **one instance** (typically app + drain + Pyroscope + k6 on a single VPS). The sustained RPS you publish is the **ceiling of that server configuration and synthetic work unit**, not “Tracewick handles N RPS everywhere” and not a multi-node fleet result. On the Timeweb 8 vCPU stand with depth-48 `/work` (~25 ms busy + 10 ms sleep, 32 FPM workers), overload probes showed ~760 achieved RPS with multi-second latency — so a clean hold is expected around **~700 RPS**, not 1.5–3k. diff --git a/compose.yaml b/compose.yaml index 3273141..fb55677 100644 --- a/compose.yaml +++ b/compose.yaml @@ -14,6 +14,7 @@ x-app-build: &app-build args: PHP_VERSION: ${PHP_VERSION:-8.4} EXCIMER_VERSION: ${EXCIMER_VERSION:-1.2.6} + EXCIMER_REF: ${EXCIMER_REF:-} TRACEWICK_VERSION: ${TRACEWICK_VERSION:-0.1.0} x-app-env: &app-env @@ -66,7 +67,7 @@ services: app-fpm: build: *app-build - image: tracewick-benchmarks-fpm:${TRACEWICK_VERSION:-0.1.0} + image: tracewick-benchmarks-fpm:${TRACEWICK_IMAGE_TAG:-${TRACEWICK_VERSION:-0.1.0}} environment: <<: *app-env volumes: @@ -74,13 +75,13 @@ services: - app-spool:/var/spool/tracewick depends_on: [pyroscope] healthcheck: - test: [CMD-SHELL, php -r 'exit(extension_loaded("excimer")?0:1);'] + test: ["CMD-SHELL", "php -r 'exit(extension_loaded(\"excimer\")?0:1);'"] interval: 10s timeout: 3s retries: 12 app-drain: - image: tracewick-benchmarks-fpm:${TRACEWICK_VERSION:-0.1.0} + image: tracewick-benchmarks-fpm:${TRACEWICK_IMAGE_TAG:-${TRACEWICK_VERSION:-0.1.0}} user: www-data entrypoint: [vendor/bin/tracewick-drain] command: [--memory-limit=128M] @@ -101,7 +102,9 @@ services: context: stand/agent args: AGENT_VERSION: ${AGENT_VERSION:-0.1.0} - image: tracewick-benchmarks-agent:${AGENT_VERSION:-0.1.0} + AGENT_REF: ${AGENT_REF:-} + AGENT_BUILD_TARGET: ${AGENT_BUILD_TARGET:-release} + image: tracewick-benchmarks-agent:${AGENT_IMAGE_TAG:-${AGENT_VERSION:-0.1.0}} user: "33:33" environment: TRACEWICK_SPOOL_DIR: ${TRACEWICK_SPOOL_DIR:-/var/spool/tracewick} @@ -148,9 +151,10 @@ services: args: PHP_VERSION: ${PHP_VERSION:-8.4} EXCIMER_VERSION: ${EXCIMER_VERSION:-1.2.6} + EXCIMER_REF: ${EXCIMER_REF:-} TRACEWICK_VERSION: ${TRACEWICK_VERSION:-0.1.0} ROADRUNNER_VERSION: ${ROADRUNNER_VERSION:-2025.1.15} - image: tracewick-benchmarks-rr:${TRACEWICK_VERSION:-0.1.0} + image: tracewick-benchmarks-rr:${TRACEWICK_IMAGE_TAG:-${TRACEWICK_VERSION:-0.1.0}} user: "33:33" environment: <<: *app-env @@ -161,7 +165,7 @@ services: - 127.0.0.1:${RR_PORT:-8082}:8080 depends_on: [pyroscope] healthcheck: - test: [CMD-SHELL, php -r 'exit(extension_loaded("excimer")?0:1);'] + test: ["CMD-SHELL", "php -r 'exit(extension_loaded(\"excimer\")?0:1);'"] interval: 10s timeout: 3s retries: 12 @@ -174,9 +178,10 @@ services: args: PHP_VERSION: ${PHP_VERSION:-8.4} EXCIMER_VERSION: ${EXCIMER_VERSION:-1.2.6} + EXCIMER_REF: ${EXCIMER_REF:-} TRACEWICK_VERSION: ${TRACEWICK_VERSION:-0.1.0} SWOOLE_VERSION: ${SWOOLE_VERSION:-6.0.2} - image: tracewick-benchmarks-swoole:${TRACEWICK_VERSION:-0.1.0} + image: tracewick-benchmarks-swoole:${TRACEWICK_IMAGE_TAG:-${TRACEWICK_VERSION:-0.1.0}} user: "33:33" environment: <<: *app-env @@ -187,7 +192,7 @@ services: - 127.0.0.1:${SWOOLE_PORT:-8083}:8080 depends_on: [pyroscope] healthcheck: - test: [CMD-SHELL, php -r 'exit(extension_loaded("excimer")&&extension_loaded("swoole")?0:1);'] + test: ["CMD-SHELL", "php -r 'exit(extension_loaded(\"excimer\")&&extension_loaded(\"swoole\")?0:1);'"] interval: 10s timeout: 3s retries: 12 diff --git a/docs/soak.md b/docs/soak.md new file mode 100644 index 0000000..4198a41 --- /dev/null +++ b/docs/soak.md @@ -0,0 +1,158 @@ +# Observed 72-hour soak + +Methodology: [METHOD.md](../METHOD.md). Limitations: [LIMITATIONS.md](../LIMITATIONS.md). + +`make bench-soak` runs **baseline → warmup → steady → drain → cooldown**, with +one normal reader. Warmup must demonstrate successful delivery and drain before +steady load is allowed to start. Its default is one persistent RoadRunner worker, Go agent, +depth 48 and sample rate 0.1. No Grafana is started. FPM/drain and Swoole are also +selectable; RR uses exactly one worker so its diagnostics have a single owner. +The existing RR memory supervisor stays enabled at 256 MiB. A process identity +change invalidates continuity, including recycling within a running container. + +This is sustained-load/resource-growth evidence, not a maximum-RPS test. Calibrate +RATE first on the actual host and hold it fixed afterwards. The short unprofiled +baseline is a sanity comparison, not a separate full overhead campaign. Record +CPU/RAM/OS, resource limits and competing work. Configure Docker proxy bypass for the local Pyroscope/network +when your Docker installation injects proxy environment variables. A 2 vCPU / 4 GiB host is a starting +configuration for a pilot, not a capacity guarantee. + +## Requirements and exact pins + +Use Linux, a local Docker Unix socket, Compose v2, Python 3, git, make and tmux. +Root or equivalent Docker access is needed for read-only `/proc` probes inside +the benchmark containers. No PHP, Go, k6 or Prometheus server is needed on the host. + +Package and agent pins must be explicitly exported. This example pins the merged +17 November 2026 changes; select and review new SHAs deliberately for later runs: + +```bash +export TRACEWICK_VERSION='dev-develop#55eb7bdb91cd4269a86bb0dd8ce22a243e5486b4' +export AGENT_REF=a15f0d310ba6d5942e67b37d3c3c55dc1b3b8100 +export EXCIMER_VERSION=1.2.7 +export EXCIMER_REF=23f541b9d970db0524a1b2506b4df727e5e59998 +``` + +An exact published `TRACEWICK_VERSION=0.2.0` and `AGENT_VERSION=0.2.1` are also +supported (unset AGENT_REF to use a release). Those older releases do **not** +contain the current UoW/env changes. Floating constraints and branch-only core +pins are rejected. The PHP build argument now changes the actual Composer +constraint; it is not just an image label. Agent source builds verify the full +Git SHA. Before traffic, the runner compares installed package reference/version +and agent identity with the requested pins, then records image IDs, harness hashes/dirty status and runtime +versions in `identity.json`. The complete Composer lock is retained in the image. + +EXCIMER_REF optionally builds the extension from an exact Git SHA and checks its +reported version against EXCIMER_VERSION. Without it the older PECL stand path +is preserved. Optional `proxy_ca` BuildKit secrets can provide a network CA for +Composer/Git source builds; this is not a request to disable TLS verification. + +## Pilot, then 72 hours + +Do not run `make up` alongside this scenario: the soak starts its own dedicated +Compose project `tracewick-soak` and uses the same default loopback ports. The +runner checks for an empty spool before starting its reader, and refuses an existing project or an occupied k6 REST endpoint. Use +SOAK_PROJECT and the port variables in compose.yaml for independent runs. The +scenario does not stop unrelated projects. + +First check the harness on the target host: + +```bash +make check-soak +BASELINE_DURATION=20s WARMUP_DURATION=20s DURATION=60s \ + COOLDOWN_DURATION=10s STATS_INTERVAL=5 TRACEWICK_SAMPLE_RATE=1 \ + SOAK_PROJECT=soak-pilot make bench-soak +``` + +Inspect `result.json`, reports and the resolved versions. A pilot is not long-soak +evidence. Stop the pilot project before reusing its ports: + +```bash +docker compose -p soak-pilot --profile agent down +``` + +Then, after calibrating RATE (10 below is an example, not a universal target): + +```bash +tmux new -s tracewick-soak +RATE=10 DURATION=72h BASELINE_DURATION=5m WARMUP_DURATION=5m \ + COOLDOWN_DURATION=2m DRAIN_TIMEOUT=2m STATS_INTERVAL=15 \ + TRACEWICK_SAMPLE_RATE=0.1 make bench-soak +``` + +Leave the session with Ctrl-b d; reattach with `tmux attach -t tracewick-soak`. +The script keeps benchmark containers for inspection after success or failure. +After preserving the evidence, stop only this project: + +```bash +docker compose -p tracewick-soak --profile agent down +``` + +Do not remove volumes until the drain result and artifacts have been inspected. +The older Docker-stats-only runner remains `scripts/run-soak-legacy.sh` for +historical reproduction; its memory column is container memory, not process RSS. +Its reports cannot satisfy the new observed-soak criteria. + +## What is collected + +Every STATS_INTERVAL seconds, `telemetry.jsonl` records: + +- Container identity/start time/restart count; cumulative cgroup CPU, throttling, + memory usage, anonymous/file memory and resource limits for app/reader/Pyroscope, + plus k6 while it runs. Container memory is never called RSS. +- Process PID/start ticks, RSS, anonymous memory, cumulative CPU, FD and OS-thread + counts for app and reader. Root probes inspect only the container PID namespace and select PHP/RR/agent + service processes, excluding transient runc/exec/healthcheck helpers. +- Actual spool pending files/bytes/age including claims and temporary files, plus + rejected-file count; traversal fails above 100,000 entries instead of doing + unbounded work or reporting an empty queue on errors. +- Agent queue/delivery/retry/reject metrics, and the single RR worker's profiler + diagnostics. FPM/Swoole writer-drop totals are not available from this harness. + Go goroutine/heap metrics are not currently exported; OS threads are not goroutines. +- k6 cumulative request/drop/error/latency checkpoints. REST polling avoids storing + per-request events for 72 hours. Quantiles are cumulative checkpoints; only the + final per-phase summaries are full-window p95/p99, not independent hourly quantiles. + +`resource-series.csv` is a flattened export; `hourly.json` summarizes fixed-hour +CPU/request and memory observations. `result.json` and `soak-report.md` separate +validity from resource trends. RSS/anonymous slopes use the whole steady series; +first/last window averages and cumulative CPU per k6 HTTP request are also saved. +Process RSS sums count shared mappings per process. Container CPU includes observer +execs and health probes, so it is not pure profiler overhead. Baseline/warmup use +separate generator lifecycles; steady load uses one uninterrupted k6 process. + +At the end of steady load the reader must empty the actual spool, including claims, +within DRAIN_TIMEOUT. Collection continues through cooldown. Sequential UoW should +create no new files after draining; continuous Swoole may still write idle process +profiles, which is recorded rather than treated as a sequential-worker failure. + +DELIVERY_STALL_TIMEOUT defaults to 2m: old pending files or no agent delivery +progress with a nonempty queue abort the run during collection. Increasing +writer/delivery failure counters and rejected files also abort promptly. + +Missing/malformed telemetry, counter resets, container/worker replacement, OOM, +large collection gaps, wrong pins/disabled profiling, missed HTTP checks, dropped +load-generator iterations, absent delivery or increasing RR writer failures make +the observation invalid and the command exits nonzero. Raw artifacts and an invalid +report survive failures. A **valid observation** only means these validity checks +passed; inspect trends, queue and duration before deciding whether the soak passed. +RSS growth alone does not prove a leak: allocator retention and shared pages matter. + +## Plots after collection + +Optional plotting uses Matplotlib; it is not required during the load: + +```bash +# Ubuntu, only if plots are wanted on this host: +sudo apt-get install python3-matplotlib +make plot-soak RUN_DIR=reports/_local/soak- +``` + +`resources.png` plots process RSS/anonymous memory, FD/threads, CPU per request and +pending files, with phase boundaries. Preserve JSONL/CSV/identity alongside plots. + +Some managed Docker environments expose shared parent-cgroup statistics. The +collector rejects implausible lifetime CPU values. A local harness-only escape +hatch, SOAK_SMOKE_SHARED_CGROUP=1, permits **at most 60 seconds per phase**, labels +the result as a harness smoke and omits container CPU/request attribution. This +mode cannot produce a valid 72h observation and must not be used for capacity claims. diff --git a/generators/k6/soak.js b/generators/k6/soak.js index bb7c9f1..1ca47fa 100644 --- a/generators/k6/soak.js +++ b/generators/k6/soak.js @@ -1,5 +1,5 @@ import http from "k6/http"; -import { check, sleep } from "k6"; +import { check, fail, sleep } from "k6"; /** * Long soak at fixed arrival rate (METHOD.md soak / RSS growth). @@ -9,6 +9,7 @@ const RATE = Number(__ENV.RATE || 10); const DURATION = __ENV.DURATION || "72h"; const PRE_VUS = Number(__ENV.PRE_VUS || 20); const MAX_VUS = Number(__ENV.MAX_VUS || 40); +const EXPECT_PROFILING = (__ENV.EXPECT_PROFILING || "1") === "1"; export const options = { summaryTrendStats: ["avg", "min", "med", "max", "p(90)", "p(95)", "p(99)"], @@ -24,7 +25,9 @@ export const options = { }, // Soft gates: soak cares about survival + growth, not tight latency SLOs. thresholds: { - http_req_failed: ["rate<0.05"], + http_req_failed: ["rate==0"], + checks: ["rate==1"], + dropped_iterations: ["count==0"], }, }; @@ -32,7 +35,7 @@ const BASE_URL = (__ENV.BASE_URL || "http://127.0.0.1:8080").replace(/\/$/, ""); export function setup() { const health = http.get(`${BASE_URL}/health`); - check(health, { + const healthy = check(health, { "health is 200": (r) => r.status === 200, "excimer loaded": (r) => { try { @@ -41,14 +44,15 @@ export function setup() { return false; } }, - "profiling on": (r) => { + "expected profiling state": (r) => { try { - return r.json("profiling_enabled") === true; + return r.json("profiling_enabled") === EXPECT_PROFILING; } catch (e) { return false; } }, }); + if (!healthy) fail("Health/profiler preconditions failed"); sleep(1); return { baseUrl: BASE_URL }; } diff --git a/scenarios/README.md b/scenarios/README.md index d155c00..8e6b075 100644 --- a/scenarios/README.md +++ b/scenarios/README.md @@ -8,5 +8,5 @@ Named capacity profiles. Each Make target `bench-` maps to one scenario an | `overhead` | Fixed RPS: baseline (`TRACEWICK_ENABLED=0`) vs on (`sampleRate` 0.1); optional `WORK_STACK_DEPTH` | `make bench-overhead` | | `spool-pressure` | Stop drain, fill toward `max_files`, catch-up lag; optional `WORK_STACK_DEPTH` | `make bench-spool-pressure` | | `chaos-pyroscope` | Toxiproxy latency to Pyroscope; optional `WORK_STACK_DEPTH` | `make bench-chaos` | -| `soak` / `soak-72h` | Long RSS/CPU growth (FPM + drain series) | `make bench-soak` (default `RATE=10` `DURATION=72h`) | +| `soak` / `soak-72h` | Observed process/CPU/queue growth, default RR + agent; [runbook](../docs/soak.md) | `make bench-soak` (explicit pins; pilot first) | | `rps-pipeline` | High-RPS hold + spool files/bytes; deeper stacks via `WORK_STACK_DEPTH` | `make bench-rps` (default `RATE=500` `DURATION=5m`, depth 48) | diff --git a/scripts/plot-soak.py b/scripts/plot-soak.py new file mode 100644 index 0000000..69b92fa --- /dev/null +++ b/scripts/plot-soak.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +"""Optional static plots from preserved telemetry (requires matplotlib, not needed during load).""" +import argparse +import json +import os +import tempfile +from pathlib import Path + +os.environ.setdefault('MPLCONFIGDIR', str(Path(tempfile.gettempdir()) / 'tracewick-matplotlib')) +import matplotlib +matplotlib.use('Agg') +import matplotlib.pyplot as plt + +parser = argparse.ArgumentParser() +parser.add_argument('run_directory', type=Path) +args = parser.parse_args() +rows = [json.loads(line) for line in (args.run_directory / 'telemetry.jsonl').read_text().splitlines()] +start = rows[0]['monotonic'] +x = [(r['monotonic'] - start) / 3600 for r in rows] +fig, axes = plt.subplots(3, 2, figsize=(13, 11), sharex=True) +for role in ('app', 'reader'): + for field, axis, scale in [('rss_bytes', axes[0, 0], 1048576), ('anon_bytes', axes[0, 1], 1048576), + ('fds', axes[1, 0], 1), ('threads', axes[1, 1], 1)]: + axis.plot(x, [sum(p[field] for p in r['containers'][role]['processes']) / scale for r in rows], label=role) + times, cpu = [], [] + for a, b in zip(rows, rows[1:]): + requests = b['k6']['requests'] - a['k6']['requests'] + if a['phase'] != b['phase'] or requests <= 0: + continue + old = sum(p['cpu_seconds'] for p in a['containers'][role]['processes']) + new = sum(p['cpu_seconds'] for p in b['containers'][role]['processes']) + times.append((b['monotonic'] - start) / 3600) + cpu.append((new - old) * 1000 / requests) + axes[2, 0].plot(times, cpu, label=role) +axes[2, 1].plot(x, [r['spool']['pending_files'] for r in rows], label='pending incl. claims/temp') +for axis, title in zip(axes.flat, ['Process RSS (MiB, shared mappings counted per process)', + 'Process anonymous memory (MiB)', 'Open file descriptors', + 'OS threads (not Go goroutines)', 'Process CPU ms/k6 HTTP request', 'Spool files']): + axis.set_title(title, fontsize=10) + axis.legend() + axis.grid(alpha=.2) + axis.set_xlabel('Hours since first observation') +phases = [json.loads(line) for line in (args.run_directory / 'phases.jsonl').read_text().splitlines()] +for axis in axes.flat: + for phase in phases: + at = (phase['monotonic'] - start) / 3600 + if at >= 0: + axis.axvline(at, color='grey', alpha=.3, linewidth=.8) +fig.suptitle('Soak resource observations — inspect result.json for validity') +fig.tight_layout() +fig.savefig(args.run_directory / 'resources.png', dpi=150) +print(args.run_directory / 'resources.png') diff --git a/scripts/run-soak-legacy.sh b/scripts/run-soak-legacy.sh new file mode 100755 index 0000000..f2b5793 --- /dev/null +++ b/scripts/run-soak-legacy.sh @@ -0,0 +1,179 @@ +#!/usr/bin/env bash +# Long soak: fixed RPS + docker stats for workload + reader → report. +# Designed to run under tmux/nohup so SSH logout does not stop the load. +# RUNTIME=fpm|rr|swoole READER=drain|agent +set -euo pipefail + +# This report generator contains historical 0.1.0 pins; do not mislabel modern runs. +if [[ "${TRACEWICK_VERSION:-0.1.0}" != "0.1.0" || "${AGENT_VERSION:-0.1.0}" != "0.1.0" || -n "${AGENT_REF:-}" ]]; then + echo "legacy soak requires 0.1.0 package/agent pins; use run-soak.sh for current versions" >&2 + exit 2 +fi + +ROOT=$(cd "$(dirname "$0")/.." && pwd) +cd "$ROOT" + +COMPOSE=${COMPOSE:-docker compose} +K6_IMAGE=${K6_IMAGE:-grafana/k6:1.8.2} +REPORTS_DIR=${REPORTS_DIR:-reports/_local} +BASE_URL=${BASE_URL:-http://127.0.0.1:8080} +RATE=${RATE:-10} +DURATION=${DURATION:-72h} +SAMPLE_RATE=${TRACEWICK_SAMPLE_RATE:-0.1} +STATS_INTERVAL=${STATS_INTERVAL:-60} +READER=${READER:-drain} # drain | agent +RUNTIME=${RUNTIME:-fpm} # fpm | rr | swoole +STACK_DEPTH=${WORK_STACK_DEPTH:-0} +FPM_CHILDREN=${PHP_FPM_MAX_CHILDREN:-4} +RR_WORKERS=${RR_NUM_WORKERS:-4} +SWOOLE_WORKERS=${SWOOLE_WORKER_NUM:-4} + +case "$RUNTIME" in + fpm|rr|swoole) ;; + *) + echo "run-soak: RUNTIME must be fpm|rr|swoole (got: $RUNTIME)" >&2 + exit 2 + ;; +esac +case "$READER" in + drain|agent) ;; + *) + echo "run-soak: READER must be drain|agent (got: $READER)" >&2 + exit 2 + ;; +esac + +if [[ "$RUNTIME" == "rr" && "$BASE_URL" == "http://127.0.0.1:8080" ]]; then + BASE_URL=http://127.0.0.1:8082 +fi +if [[ "$RUNTIME" == "swoole" && "$BASE_URL" == "http://127.0.0.1:8080" ]]; then + BASE_URL=http://127.0.0.1:8083 +fi + +if [[ "$REPORTS_DIR" != /* ]]; then + REPORTS_DIR="$ROOT/$REPORTS_DIR" +fi + +mkdir -p "$REPORTS_DIR" +chmod a+rwx "$REPORTS_DIR" || true + +stamp=$(date -u +%Y%m%dT%H%M%SZ) +run_dir="$REPORTS_DIR/soak-$stamp" +mkdir -p "$run_dir" +chmod a+rwx "$run_dir" || true + +log="$run_dir/soak.log" +exec > >(tee -a "$log") 2>&1 + +echo "==> Soak start $(date -u +%Y-%m-%dT%H:%M:%SZ)" +echo " RATE=$RATE DURATION=$DURATION SAMPLE_RATE=$SAMPLE_RATE STATS_INTERVAL=${STATS_INTERVAL}s" +echo " RUNTIME=$RUNTIME READER=$READER WORK_STACK_DEPTH=$STACK_DEPTH" +echo " run_dir=$run_dir" +echo " tip: run inside tmux (tmux new -s soak) so logout does not kill k6" + +{ + echo "started_at_utc=$(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo "RATE=$RATE" + echo "DURATION=$DURATION" + echo "TRACEWICK_SAMPLE_RATE=$SAMPLE_RATE" + echo "STATS_INTERVAL=$STATS_INTERVAL" + echo "READER=$READER" + echo "RUNTIME=$RUNTIME" + echo "WORK_STACK_DEPTH=$STACK_DEPTH" + echo "PHP_FPM_MAX_CHILDREN=$FPM_CHILDREN" + echo "RR_NUM_WORKERS=$RR_WORKERS" + echo "SWOOLE_WORKER_NUM=$SWOOLE_WORKERS" + echo "BASE_URL=$BASE_URL" + echo "K6_IMAGE=$K6_IMAGE" + echo "repo_sha=$(git rev-parse HEAD 2>/dev/null || echo unknown)" + echo "host=$(uname -a)" +} > "$run_dir/meta.txt" + +chmod +x "$ROOT/scripts/recreate-workload.sh" "$ROOT/scripts/ensure-reader.sh" +# Stop sibling runtimes so one VPS soak is not contended. +$COMPOSE stop app-fpm app-nginx app-rr app-swoole 2>/dev/null || true + +TRACEWICK_ENABLED=1 \ +TRACEWICK_SAMPLE_RATE="$SAMPLE_RATE" \ +WORK_STACK_DEPTH="$STACK_DEPTH" \ +PHP_FPM_MAX_CHILDREN="$FPM_CHILDREN" \ +RR_NUM_WORKERS="$RR_WORKERS" \ +SWOOLE_WORKER_NUM="$SWOOLE_WORKERS" \ +RUNTIME="$RUNTIME" \ +BASE_URL="$BASE_URL" \ + "$ROOT/scripts/recreate-workload.sh" | tee "$run_dir/health.json" + +READER="$READER" "$ROOT/scripts/ensure-reader.sh" + +case "$RUNTIME" in + fpm) app_svc=app-fpm ;; + rr) app_svc=app-rr ;; + swoole) app_svc=app-swoole ;; +esac +if [[ "$READER" == "agent" ]]; then + reader_svc=app-agent +else + reader_svc=app-drain +fi + +app_stats="$run_dir/${app_svc}-stats.csv" +reader_stats="$run_dir/${reader_svc}-stats.csv" +# Keep legacy filename for older summarize callers / muscle memory. +cp_link_fpm="$run_dir/app-fpm-stats.csv" + +echo "==> Sampling docker stats every ${STATS_INTERVAL}s ($app_svc + $reader_svc)" +COMPOSE="$COMPOSE" "$ROOT/scripts/sample-container-stats.sh" "$app_svc" "$app_stats" "$STATS_INTERVAL" & +app_pid=$! +COMPOSE="$COMPOSE" "$ROOT/scripts/sample-container-stats.sh" "$reader_svc" "$reader_stats" "$STATS_INTERVAL" & +reader_pid=$! + +cleanup() { + kill "$app_pid" "$reader_pid" 2>/dev/null || true + wait "$app_pid" 2>/dev/null || true + wait "$reader_pid" 2>/dev/null || true +} +trap cleanup EXIT INT TERM + +sleep "$STATS_INTERVAL" + +echo "==> k6 soak RATE=$RATE DURATION=$DURATION BASE_URL=$BASE_URL" +docker run --rm --network host \ + -v "$ROOT/generators/k6:/scripts:ro" \ + -v "$run_dir:/out" \ + -e BASE_URL="$BASE_URL" \ + -e RATE="$RATE" \ + -e DURATION="$DURATION" \ + "$K6_IMAGE" run /scripts/soak.js --summary-export=/out/k6.json + +cleanup +trap - EXIT INT TERM + +# Alias for summarize when runtime is fpm (historical path name). +if [[ "$app_svc" == "app-fpm" && ! -e "$cp_link_fpm" ]]; then + ln -sf "$(basename "$app_stats")" "$cp_link_fpm" 2>/dev/null || cp "$app_stats" "$cp_link_fpm" +fi + +host=$(uname -a) +sha=$(git rev-parse HEAD 2>/dev/null || echo unknown) +report="$run_dir/soak-report.md" + +python3 "$ROOT/scripts/summarize-soak.py" \ + --k6 "$run_dir/k6.json" \ + --app-stats "$app_stats" \ + --reader-stats "$reader_stats" \ + --out "$report" \ + --repo-sha "$sha" \ + --host "$host" \ + --rate "$RATE" \ + --duration "$DURATION" \ + --sample-rate "$SAMPLE_RATE" \ + --runtime "$RUNTIME" \ + --reader "$READER" \ + --stack-depth "$STACK_DEPTH" \ + --app-service "$app_svc" \ + --reader-service "$reader_svc" + +cp "$report" "$REPORTS_DIR/soak-latest.md" +echo "finished_at_utc=$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$run_dir/meta.txt" +echo "Report: $report" +echo "Also: $REPORTS_DIR/soak-latest.md" diff --git a/scripts/run-soak-matrix.sh b/scripts/run-soak-matrix.sh index d15e9f5..f0061ff 100755 --- a/scripts/run-soak-matrix.sh +++ b/scripts/run-soak-matrix.sh @@ -16,7 +16,7 @@ REPORTS_DIR=${REPORTS_DIR:-reports/_local} # Modest pools — soak is about growth, not max RPS. FPM_CHILDREN=${PHP_FPM_MAX_CHILDREN:-8} -RR_WORKERS=${RR_NUM_WORKERS:-8} +RR_WORKERS=${RR_NUM_WORKERS:-1} SWOOLE_WORKERS=${SWOOLE_WORKER_NUM:-8} RUNTIMES=${RUNTIMES:-"fpm rr swoole"} diff --git a/scripts/run-soak.sh b/scripts/run-soak.sh index 4e42cb6..8303baf 100755 --- a/scripts/run-soak.sh +++ b/scripts/run-soak.sh @@ -1,173 +1,6 @@ #!/usr/bin/env bash -# Long soak: fixed RPS + docker stats for workload + reader → report. -# Designed to run under tmux/nohup so SSH logout does not stop the load. -# RUNTIME=fpm|rr|swoole READER=drain|agent +# Observed soak: explicit pins, baseline/warmup/steady/drain/cooldown and validity gates. set -euo pipefail - ROOT=$(cd "$(dirname "$0")/.." && pwd) cd "$ROOT" - -COMPOSE=${COMPOSE:-docker compose} -K6_IMAGE=${K6_IMAGE:-grafana/k6:1.8.2} -REPORTS_DIR=${REPORTS_DIR:-reports/_local} -BASE_URL=${BASE_URL:-http://127.0.0.1:8080} -RATE=${RATE:-10} -DURATION=${DURATION:-72h} -SAMPLE_RATE=${TRACEWICK_SAMPLE_RATE:-0.1} -STATS_INTERVAL=${STATS_INTERVAL:-60} -READER=${READER:-drain} # drain | agent -RUNTIME=${RUNTIME:-fpm} # fpm | rr | swoole -STACK_DEPTH=${WORK_STACK_DEPTH:-0} -FPM_CHILDREN=${PHP_FPM_MAX_CHILDREN:-4} -RR_WORKERS=${RR_NUM_WORKERS:-4} -SWOOLE_WORKERS=${SWOOLE_WORKER_NUM:-4} - -case "$RUNTIME" in - fpm|rr|swoole) ;; - *) - echo "run-soak: RUNTIME must be fpm|rr|swoole (got: $RUNTIME)" >&2 - exit 2 - ;; -esac -case "$READER" in - drain|agent) ;; - *) - echo "run-soak: READER must be drain|agent (got: $READER)" >&2 - exit 2 - ;; -esac - -if [[ "$RUNTIME" == "rr" && "$BASE_URL" == "http://127.0.0.1:8080" ]]; then - BASE_URL=http://127.0.0.1:8082 -fi -if [[ "$RUNTIME" == "swoole" && "$BASE_URL" == "http://127.0.0.1:8080" ]]; then - BASE_URL=http://127.0.0.1:8083 -fi - -if [[ "$REPORTS_DIR" != /* ]]; then - REPORTS_DIR="$ROOT/$REPORTS_DIR" -fi - -mkdir -p "$REPORTS_DIR" -chmod a+rwx "$REPORTS_DIR" || true - -stamp=$(date -u +%Y%m%dT%H%M%SZ) -run_dir="$REPORTS_DIR/soak-$stamp" -mkdir -p "$run_dir" -chmod a+rwx "$run_dir" || true - -log="$run_dir/soak.log" -exec > >(tee -a "$log") 2>&1 - -echo "==> Soak start $(date -u +%Y-%m-%dT%H:%M:%SZ)" -echo " RATE=$RATE DURATION=$DURATION SAMPLE_RATE=$SAMPLE_RATE STATS_INTERVAL=${STATS_INTERVAL}s" -echo " RUNTIME=$RUNTIME READER=$READER WORK_STACK_DEPTH=$STACK_DEPTH" -echo " run_dir=$run_dir" -echo " tip: run inside tmux (tmux new -s soak) so logout does not kill k6" - -{ - echo "started_at_utc=$(date -u +%Y-%m-%dT%H:%M:%SZ)" - echo "RATE=$RATE" - echo "DURATION=$DURATION" - echo "TRACEWICK_SAMPLE_RATE=$SAMPLE_RATE" - echo "STATS_INTERVAL=$STATS_INTERVAL" - echo "READER=$READER" - echo "RUNTIME=$RUNTIME" - echo "WORK_STACK_DEPTH=$STACK_DEPTH" - echo "PHP_FPM_MAX_CHILDREN=$FPM_CHILDREN" - echo "RR_NUM_WORKERS=$RR_WORKERS" - echo "SWOOLE_WORKER_NUM=$SWOOLE_WORKERS" - echo "BASE_URL=$BASE_URL" - echo "K6_IMAGE=$K6_IMAGE" - echo "repo_sha=$(git rev-parse HEAD 2>/dev/null || echo unknown)" - echo "host=$(uname -a)" -} > "$run_dir/meta.txt" - -chmod +x "$ROOT/scripts/recreate-workload.sh" "$ROOT/scripts/ensure-reader.sh" -# Stop sibling runtimes so one VPS soak is not contended. -$COMPOSE stop app-fpm app-nginx app-rr app-swoole 2>/dev/null || true - -TRACEWICK_ENABLED=1 \ -TRACEWICK_SAMPLE_RATE="$SAMPLE_RATE" \ -WORK_STACK_DEPTH="$STACK_DEPTH" \ -PHP_FPM_MAX_CHILDREN="$FPM_CHILDREN" \ -RR_NUM_WORKERS="$RR_WORKERS" \ -SWOOLE_WORKER_NUM="$SWOOLE_WORKERS" \ -RUNTIME="$RUNTIME" \ -BASE_URL="$BASE_URL" \ - "$ROOT/scripts/recreate-workload.sh" | tee "$run_dir/health.json" - -READER="$READER" "$ROOT/scripts/ensure-reader.sh" - -case "$RUNTIME" in - fpm) app_svc=app-fpm ;; - rr) app_svc=app-rr ;; - swoole) app_svc=app-swoole ;; -esac -if [[ "$READER" == "agent" ]]; then - reader_svc=app-agent -else - reader_svc=app-drain -fi - -app_stats="$run_dir/${app_svc}-stats.csv" -reader_stats="$run_dir/${reader_svc}-stats.csv" -# Keep legacy filename for older summarize callers / muscle memory. -cp_link_fpm="$run_dir/app-fpm-stats.csv" - -echo "==> Sampling docker stats every ${STATS_INTERVAL}s ($app_svc + $reader_svc)" -COMPOSE="$COMPOSE" "$ROOT/scripts/sample-container-stats.sh" "$app_svc" "$app_stats" "$STATS_INTERVAL" & -app_pid=$! -COMPOSE="$COMPOSE" "$ROOT/scripts/sample-container-stats.sh" "$reader_svc" "$reader_stats" "$STATS_INTERVAL" & -reader_pid=$! - -cleanup() { - kill "$app_pid" "$reader_pid" 2>/dev/null || true - wait "$app_pid" 2>/dev/null || true - wait "$reader_pid" 2>/dev/null || true -} -trap cleanup EXIT INT TERM - -sleep "$STATS_INTERVAL" - -echo "==> k6 soak RATE=$RATE DURATION=$DURATION BASE_URL=$BASE_URL" -docker run --rm --network host \ - -v "$ROOT/generators/k6:/scripts:ro" \ - -v "$run_dir:/out" \ - -e BASE_URL="$BASE_URL" \ - -e RATE="$RATE" \ - -e DURATION="$DURATION" \ - "$K6_IMAGE" run /scripts/soak.js --summary-export=/out/k6.json - -cleanup -trap - EXIT INT TERM - -# Alias for summarize when runtime is fpm (historical path name). -if [[ "$app_svc" == "app-fpm" && ! -e "$cp_link_fpm" ]]; then - ln -sf "$(basename "$app_stats")" "$cp_link_fpm" 2>/dev/null || cp "$app_stats" "$cp_link_fpm" -fi - -host=$(uname -a) -sha=$(git rev-parse HEAD 2>/dev/null || echo unknown) -report="$run_dir/soak-report.md" - -python3 "$ROOT/scripts/summarize-soak.py" \ - --k6 "$run_dir/k6.json" \ - --app-stats "$app_stats" \ - --reader-stats "$reader_stats" \ - --out "$report" \ - --repo-sha "$sha" \ - --host "$host" \ - --rate "$RATE" \ - --duration "$DURATION" \ - --sample-rate "$SAMPLE_RATE" \ - --runtime "$RUNTIME" \ - --reader "$READER" \ - --stack-depth "$STACK_DEPTH" \ - --app-service "$app_svc" \ - --reader-service "$reader_svc" - -cp "$report" "$REPORTS_DIR/soak-latest.md" -echo "finished_at_utc=$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$run_dir/meta.txt" -echo "Report: $report" -echo "Also: $REPORTS_DIR/soak-latest.md" +exec python3 scripts/soak.py diff --git a/scripts/soak.py b/scripts/soak.py new file mode 100644 index 0000000..8e18f25 --- /dev/null +++ b/scripts/soak.py @@ -0,0 +1,428 @@ +#!/usr/bin/env python3 +"""Observed soak runner. Requires Linux, local Docker, Compose v2, Python 3 and k6 image.""" +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import re +import shlex +import signal +import subprocess +import sys +import time +import urllib.error +import urllib.request +from collections import deque +from datetime import datetime, timezone +from pathlib import Path + +from soaklib import (ROOT, Continuity, Docker, agent_metrics, command, get_json, + k6_metrics, summarize, write_report, export_csv) + + +def seconds(value): + parts = re.findall(r'(\d+(?:\.\d+)?)(ms|s|m|h)', value) + if not parts or ''.join(n + u for n, u in parts) != value: + raise ValueError(f'Invalid duration: {value}') + result = sum(float(n) * {'ms': .001, 's': 1, 'm': 60, 'h': 3600}[u] for n, u in parts) + if result <= 0: + raise ValueError('Durations must be positive') + return result + + +def pin(value): + if not re.fullmatch(r'v?\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?|dev-develop#[0-9a-f]{40}', value): + raise ValueError('TRACEWICK_VERSION must be an exact version or dev-develop#<40-hex SHA>') + return value + + +class Soak: + def __init__(self): + self.env = dict(os.environ) + self.runtime = self.env.get('RUNTIME', 'rr') + self.reader = self.env.get('READER', 'agent') + if self.runtime not in ('fpm', 'rr', 'swoole') or self.reader not in ('agent', 'drain'): + raise ValueError('RUNTIME=fpm|rr|swoole and READER=agent|drain required') + self.package = pin(self.env['TRACEWICK_VERSION']) + if self.reader == 'agent': + ref = self.env.get('AGENT_REF', '') + if ref: + if not re.fullmatch('[0-9a-f]{40}', ref): + raise ValueError('AGENT_REF must be a full commit SHA') + self.env['AGENT_BUILD_TARGET'] = 'source' + elif not re.fullmatch(r'\d+\.\d+\.\d+', self.env.get('AGENT_VERSION', '')): + raise ValueError('Set AGENT_REF=<40-hex SHA> or explicit AGENT_VERSION') + self.project = self.env.get('SOAK_PROJECT', 'tracewick-soak') + if not re.fullmatch('[a-z0-9][a-z0-9_-]*', self.project): + raise ValueError('Invalid SOAK_PROJECT') + self.env['TRACEWICK_IMAGE_TAG'] = self.project + self.env['AGENT_IMAGE_TAG'] = self.project + self.env.setdefault('RR_NUM_WORKERS', '1') + if self.runtime == 'rr' and self.env['RR_NUM_WORKERS'] != '1': + raise ValueError('Observed RR soak uses one persistent worker for diagnostic attribution') + self.env.setdefault('WORK_STACK_DEPTH', '48') + self.env.setdefault('PHP_FPM_MAX_CHILDREN', '1') + self.env.setdefault('SWOOLE_WORKER_NUM', '1') + self.rate = int(self.env.get('RATE', '10')) + self.interval = float(self.env.get('STATS_INTERVAL', '15')) + self.sample_rate = float(self.env.get('TRACEWICK_SAMPLE_RATE', '0.1')) + if self.rate <= 0 or self.interval <= 0 or not 0 < self.sample_rate <= 1: + raise ValueError('Positive RATE/STATS_INTERVAL and 0 < TRACEWICK_SAMPLE_RATE <= 1 required') + self.env['TRACEWICK_SAMPLE_RATE'] = str(self.sample_rate) + self.env.setdefault('EXCIMER_VERSION', '1.2.7') + self.durations = {p: self.env.get(k, default) for p, k, default in ( + ('baseline', 'BASELINE_DURATION', '5m'), ('warmup', 'WARMUP_DURATION', '5m'), + ('steady', 'DURATION', '72h'), ('cooldown', 'COOLDOWN_DURATION', '2m'))} + for value in self.durations.values(): + seconds(value) + if seconds(self.durations['steady']) < self.interval * 3: + raise ValueError('Steady duration must cover at least three telemetry intervals') + self.drain_timeout = seconds(self.env.get('DRAIN_TIMEOUT', '2m')) + self.stall_timeout = seconds(self.env.get('DELIVERY_STALL_TIMEOUT', '2m')) + self.delivery_progress = time.monotonic() + self.delivered = 0 + self.app = {'rr': 'app-rr', 'fpm': 'app-fpm', 'swoole': 'app-swoole'}[self.runtime] + self.reader_service = 'app-' + self.reader + self.base_url = self.env.get('BASE_URL') or { + 'fpm': 'http://127.0.0.1:8080', 'rr': 'http://127.0.0.1:8082', + 'swoole': 'http://127.0.0.1:8083'}[self.runtime] + self.k6_url = self.env.get('K6_API_URL', 'http://127.0.0.1:6565') + self.agent_url = 'http://127.0.0.1:' + self.env.get('AGENT_METRICS_PORT', '9090') + '/metrics' + self.pyroscope_url = 'http://127.0.0.1:' + self.env.get('PYROSCOPE_PORT', '4040') + self.compose = shlex.split(self.env.get('COMPOSE', 'docker compose')) + ['-p', self.project] + self.docker = Docker() + self.shared_smoke = self.env.get('SOAK_SMOKE_SHARED_CGROUP') == '1' + if self.shared_smoke and any(seconds(v) > 60 for v in self.durations.values()): + raise ValueError('Shared-cgroup harness smoke is limited to 60 seconds per phase') + self.directory = Path(self.env.get('REPORTS_DIR', 'reports/_local')).resolve() / ( + 'soak-' + datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')) + self.directory.mkdir(parents=True, mode=0o755) + self.harness = self.directory / 'harness' + self.harness.mkdir() + shutil.copyfile(ROOT / 'generators/k6/soak.js', self.harness / 'soak.js') + self.spool_script = (ROOT / 'scripts/soak_spool.php').read_text() + self.load_name = self.project + '-load' + self.ids = {} + self.guard = Continuity(self.interval) + self.load = None + self.last_k6 = {'requests': 0} + self.phase = 'prepare' + self.records = deque(maxlen=2) + self.phases = [] + self.identity = {'parameters': {k: self.env.get(k) for k in ( + 'TRACEWICK_VERSION', 'AGENT_VERSION', 'AGENT_REF', 'WORK_STACK_DEPTH', + 'RR_NUM_WORKERS', 'PHP_FPM_MAX_CHILDREN', 'SWOOLE_WORKER_NUM', 'EXCIMER_VERSION', 'EXCIMER_REF', + 'WORK_BUSY_MS', 'WORK_SLEEP_MS')}, 'rate': self.rate, + 'sample_rate': self.sample_rate, 'durations': self.durations, + 'stats_interval': self.interval, 'host': command(['uname', '-a']), + 'cpu_count': os.cpu_count(), 'clock_ticks': os.sysconf('SC_CLK_TCK'), + 'meminfo': Path('/proc/meminfo').read_text(), + 'repo_sha': command(['git', 'rev-parse', 'HEAD'], cwd=ROOT), + 'git_status': command(['git', 'status', '--porcelain'], cwd=ROOT), + 'harness_sha256': {name: hashlib.sha256((ROOT / name).read_bytes()).hexdigest() for name in ( + 'scripts/soak.py', 'scripts/soaklib.py', 'scripts/soak_probe.sh', + 'scripts/soak_spool.php', 'generators/k6/soak.js', 'compose.yaml')}, + 'docker': {k: v for k, v in self.docker.get('/info').items() if k in ( + 'ServerVersion', 'Architecture', 'CgroupVersion', 'Driver', 'NCPU', 'MemTotal')}} + + def compose_run(self, *args): + subprocess.run(self.compose + list(args), env=self.env, cwd=ROOT, check=True) + + def cid(self, service): + return command(self.compose + ['--profile', 'agent', 'ps', '-q', service], env=self.env, cwd=ROOT) + + def phase_start(self, name): + self.phase = name + record = {'phase': name, 'ts': time.time(), 'monotonic': time.monotonic()} + self.phases.append(record) + with (self.directory / 'phases.jsonl').open('a') as stream: + stream.write(json.dumps(record) + '\n') + print(f'==> {name}: {self.directory}', flush=True) + + def wait_ready(self, url): + deadline = time.monotonic() + 120 + while True: + try: + with urllib.request.urlopen(url, timeout=3) as response: + if response.status == 200: + return + except (OSError, urllib.error.URLError): + pass + if time.monotonic() >= deadline: + raise RuntimeError(f'Not ready: {url}') + time.sleep(1) + + def health(self, enabled): + health = get_json(self.base_url + '/health') + if not health.get('ok') or not health.get('excimer') or not health.get('tracewick'): + raise ValueError('Health must confirm app, Tracewick and real Excimer') + if health.get('profiling_enabled') is not enabled: + raise ValueError('Wrong profiling state') + if health.get('work_stack_depth') != int(self.env['WORK_STACK_DEPTH']): + raise ValueError('Wrong workload depth') + diagnostics = health.get('diagnostics') + if enabled and diagnostics and diagnostics.get('inactiveSampler') is not None: + raise ValueError('Inactive sampler despite enabled profiling') + return health + + def take(self, generator=None): + sample = {'ts': time.time(), 'monotonic': time.monotonic(), 'phase': self.phase, + 'containers': {role: self.docker.sample(cid, processes=role in ('app', 'reader'), allow_shared=self.shared_smoke) + for role, cid in self.ids.items()}} + if generator: + sample['containers']['generator'] = self.docker.sample(generator, allow_shared=self.shared_smoke) + sample['k6'] = k6_metrics(self.k6_url) + self.last_k6 = sample['k6'] + else: + sample['k6'] = self.last_k6 + if self.reader == 'agent': + sample['agent'] = agent_metrics(self.agent_url) + if self.phase != 'baseline': + sample['health'] = self.health(True) + else: + sample['health'] = self.health(False) + probe = subprocess.run(['docker', 'exec', '-i', self.ids['app'], 'php'], + input=self.spool_script, text=True, + capture_output=True, timeout=15) + if probe.returncode: + raise RuntimeError('Spool probe failed: ' + probe.stderr.strip()) + sample['spool'] = json.loads(probe.stdout) + with (self.directory / 'telemetry.jsonl').open('a') as stream: + stream.write(json.dumps(sample) + '\n') + self.records.append(sample) + core = {**sample, 'containers': {k: v for k, v in sample['containers'].items() if k != 'generator'}} + self.guard.check(core) + if len(self.records) > 1 and self.phase != 'baseline': + previous = self.records[-2] + if sample.get('agent') and previous.get('agent'): + for key in ('profiles_rejected_total', 'profiles_retried_total'): + if sample['agent'][key] > previous['agent'][key]: + raise ValueError('Delivery failures increased: ' + key) + if self.runtime == 'rr' and previous['health'].get('diagnostics'): + for key in ('droppedProfiles', 'skippedProfiles', 'failedProfiles', 'rejectedProfiles', 'swallowedErrors', 'samplerFailures'): + if sample['health']['diagnostics'][key] > previous['health']['diagnostics'][key]: + raise ValueError('Writer diagnostics increased: ' + key) + now = time.monotonic() + if sample.get('agent') and sample['agent']['profiles_delivered_total'] != self.delivered: + self.delivered = sample['agent']['profiles_delivered_total'] + self.delivery_progress = now + if sample['spool']['pending_files'] == 0: + self.delivery_progress = now + elif (sample['spool']['oldest_age_seconds'] > self.stall_timeout or + (self.reader == 'agent' and now - self.delivery_progress > self.stall_timeout)): + raise ValueError('Delivery stalled with pending spool work') + if len(self.records) > 1 and sample['spool']['rejected_files'] > self.records[-2]['spool']['rejected_files']: + raise ValueError('Rejected spool files increased') + return sample + + def run_load(self, phase): + self.phase_start(phase) + self.last_k6 = {'requests': 0} + duration = self.durations[phase] + output = (self.directory / (phase + '-k6.log')).open('w') + args = ['docker', 'run', '--name', self.load_name, '--network', 'host', + '--user', f'{os.getuid()}:{os.getgid()}', + '-v', str(self.harness) + ':/scripts:ro', + '-v', str(self.directory) + ':/out', '-e', 'BASE_URL=' + self.base_url, + '-e', 'RATE=' + str(self.rate), '-e', 'DURATION=' + duration, + '-e', 'EXPECT_PROFILING=' + ('0' if phase == 'baseline' else '1'), + self.env.get('K6_IMAGE', 'grafana/k6:1.8.2'), 'run', + '--address=' + self.k6_url.removeprefix('http://'), '/scripts/soak.js', + '--summary-export=/out/' + phase + '-k6.json'] + started = time.monotonic() + self.load = subprocess.Popen(args, stdout=output, stderr=subprocess.STDOUT) + try: + generator = None + while self.load.poll() is None: + try: + generator = self.docker.inspect(self.load_name)['Id'] + k6_metrics(self.k6_url) + break + except (OSError, RuntimeError, ValueError, KeyError, urllib.error.URLError): + if time.monotonic() - started > 30: + raise RuntimeError('k6 REST telemetry did not become ready') + time.sleep(.2) + if generator is None or self.load.poll() is not None: + raise RuntimeError('k6 exited before telemetry became ready') + while self.load.poll() is None: + # Stop sampling before the normal generator exit can race a stats read. + if time.monotonic() - started >= seconds(duration): + break + if not self.docker.inspect(generator)['State']['Running']: + break + self.take(generator) + time.sleep(self.interval) + code = self.load.wait(timeout=30) + if code: + raise RuntimeError(f'{phase}: k6 failed ({code}), see {phase}-k6.log') + if time.monotonic() - started < seconds(duration): + raise ValueError('Load ended before the requested duration') + summary = json.loads((self.directory / (phase + '-k6.json')).read_text()) + metrics = summary['metrics'] + if metrics['http_reqs']['count'] <= 0 or metrics.get('dropped_iterations', {}).get('count', 0): + raise ValueError('No requests or dropped load-generator iterations') + finally: + subprocess.run(['docker', 'rm', '-f', self.load_name], capture_output=True, timeout=30) + self.load.wait(timeout=30) + self.load = None + output.close() + + def runtime_identity(self): + script = ('require "vendor/autoload.php"; echo json_encode([' + '"php"=>PHP_VERSION,"excimer"=>phpversion("excimer"),' + '"version"=>Composer\\InstalledVersions::getPrettyVersion("tracewick/tracewick"),' + '"reference"=>Composer\\InstalledVersions::getReference("tracewick/tracewick")]);') + actual = json.loads(command(['docker', 'exec', self.ids['app'], 'php', '-r', script])) + if '#' in self.package: + if actual['reference'] != self.package.split('#')[1]: + raise ValueError('Installed core reference does not match requested SHA') + elif actual['version'].lstrip('v') != self.package.lstrip('v'): + raise ValueError('Installed core version does not match requested version') + if self.reader == 'agent': + actual['agent_version'] = command(['docker', 'exec', self.ids['reader'], 'tracewick-agent', 'version']) + if self.env.get('AGENT_REF'): + actual['agent_reference'] = command(['docker', 'exec', self.ids['reader'], 'cat', '/agent-reference']) + if actual['agent_reference'] != self.env['AGENT_REF']: + raise ValueError('Agent build reference mismatch') + elif self.env['AGENT_VERSION'] != actual['agent_version']: + raise ValueError('Installed agent version mismatch') + actual['containers'] = {} + for role, cid in self.ids.items(): + info = self.docker.inspect(cid) + actual['containers'][role] = {'id': info['Id'], 'image_id': info['Image'], + 'image': info['Config']['Image'], 'command': info['Config']['Cmd'], + 'started_at': info['State']['StartedAt'], + 'limits': {k: info['HostConfig'].get(k) for k in ('Memory', 'NanoCpus', 'CpuQuota', 'CpuPeriod', 'RestartPolicy')}} + self.identity.setdefault('runtimes', []).append(actual) + (self.directory / 'identity.json').write_text(json.dumps(self.identity, indent=2) + '\n') + + def read_records(self): + path = self.directory / 'telemetry.jsonl' + return [json.loads(line) for line in path.read_text().splitlines()] if path.exists() else [] + + def drain(self): + deadline = time.monotonic() + self.drain_timeout + while True: + snapshot = self.take() + if snapshot['spool']['pending_files'] == 0 and snapshot.get('agent', {}).get('inflight_uploads', 0) == 0: + return snapshot['spool'] + if time.monotonic() >= deadline: + raise ValueError('Spool did not drain within DRAIN_TIMEOUT') + time.sleep(self.interval) + + def run(self): + result = {'status': 'invalid', 'error': None} + try: + existing = command(self.compose + ['--profile', 'agent', 'ps', '-aq'], env=self.env, cwd=ROOT) + if existing: + raise ValueError(f'Project {self.project} already exists; inspect/clean it or choose SOAK_PROJECT') + # Never silently send a second generator to an existing k6 REST endpoint. + try: + get_json(self.k6_url + '/v1/status') + except OSError: + pass + else: + raise ValueError('k6 REST port already in use') + self.compose_run('--profile', 'agent', 'build', self.app, self.reader_service, + *(['app-nginx'] if self.runtime == 'fpm' else [])) + self.compose_run('up', '-d', '--no-deps', 'pyroscope') + self.wait_ready(self.pyroscope_url + '/ready') + self.env['TRACEWICK_ENABLED'] = '0' + self.compose_run('up', '-d', '--no-deps', self.app, + *(['app-nginx'] if self.runtime == 'fpm' else [])) + self.wait_ready(self.base_url + '/health') + app = self.cid(self.app) + probe = subprocess.run(['docker', 'exec', '-i', app, 'php'], input=self.spool_script, + text=True, capture_output=True, check=True, timeout=15) + initial_spool = json.loads(probe.stdout) + if initial_spool['pending_files'] or initial_spool['rejected_files']: + raise ValueError('Spool is not empty before the run; refusing to consume prior evidence') + self.compose_run('--profile', 'agent', 'up', '-d', '--no-deps', self.reader_service) + self.ids = {'app': app, 'reader': self.cid(self.reader_service), + 'pyroscope': self.cid('pyroscope')} + self.runtime_identity() + self.health(False) + self.run_load('baseline') + self.env['TRACEWICK_ENABLED'] = '1' + self.compose_run('up', '-d', '--no-deps', '--force-recreate', self.app) + self.wait_ready(self.base_url + '/health') + self.ids['app'] = self.cid(self.app) + self.guard = Continuity(self.interval) # Baseline recreation is intentional and recorded. + self.runtime_identity() + self.run_load('warmup') + warmup = [r for r in self.read_records() if r['phase'] == 'warmup'] + if self.reader == 'agent' and (len(warmup) < 2 or warmup[-1]['agent']['profiles_delivered_total'] <= warmup[0]['agent']['profiles_delivered_total']): + raise ValueError('Warmup did not demonstrate delivery; refusing to start steady load') + self.phase_start('preflight-drain') + self.drain() + self.run_load('steady') + self.phase_start('drain') + result['drain'] = self.drain() + self.phase_start('cooldown') + deadline = time.monotonic() + seconds(self.durations['cooldown']) + while time.monotonic() < deadline: + cooldown = self.take() + if self.runtime != 'swoole' and cooldown['spool']['pending_files']: + raise ValueError('New pending spool files after drain') + time.sleep(self.interval) + self.records = self.read_records() + steady = [r for r in self.records if r['phase'] == 'steady'] + if len(steady) < 3 or steady[-1]['monotonic'] - steady[0]['monotonic'] < seconds(self.durations['steady']) - 2 * self.interval - 5: + raise ValueError('Insufficient coverage of the requested steady window') + if self.reader == 'agent': + if steady[-1]['agent']['profiles_delivered_total'] <= steady[0]['agent']['profiles_delivered_total']: + raise ValueError('No delivered profiles during steady window') + for key in ('profiles_rejected_total', 'profiles_retried_total'): + if steady[-1]['agent'][key] > steady[0]['agent'][key]: + raise ValueError(f'Delivery failures during steady window: {key}') + if self.runtime == 'rr': + first = steady[0]['health']['diagnostics'] + last = steady[-1]['health']['diagnostics'] + for key in ('droppedProfiles', 'skippedProfiles', 'failedProfiles', 'rejectedProfiles', 'swallowedErrors', 'samplerFailures'): + if last[key] > first[key]: + raise ValueError('Writer diagnostics increased: ' + key) + if last['collectedProfiles'] <= first['collectedProfiles']: + raise ValueError('No profiles collected by the writer') + result['summary'] = summarize(self.records) + result['baseline_summary'] = summarize([{**r, 'phase': 'steady'} for r in self.records if r['phase'] == 'baseline']) + hours = [] + for offset in range(0, int(seconds(self.durations['steady'])), 3600): + rows = [s for s in steady if offset <= s['monotonic'] - steady[0]['monotonic'] < offset + 3600] + if len(rows) >= 2: + hours.append({'hour': offset // 3600, **summarize(rows)}) + (self.directory / 'hourly.json').write_text(json.dumps(hours, indent=2) + '\n') + result['status'] = ('harness smoke only; shared cgroup statistics' if self.shared_smoke + else 'valid observation; inspect resource trends') + except (Exception, KeyboardInterrupt) as error: + result['error'] = str(error) or type(error).__name__ + print('INVALID: ' + result['error'], file=sys.stderr, flush=True) + finally: + if self.load is not None: + subprocess.run(['docker', 'rm', '-f', self.load_name], capture_output=True, timeout=30) + result['phases'] = self.phases + result['shared_cgroup_smoke'] = self.shared_smoke + try: + export_csv(self.directory, self.read_records()) + except Exception as error: + result['status'] = 'invalid' + result['error'] = 'Telemetry artifact export failed: ' + str(error) + write_report(self.directory, result) + print('Report: ' + str(self.directory / 'soak-report.md'), flush=True) + return 0 if result['status'] != 'invalid' else 1 + + +def main(): + def interrupted(*_): + raise KeyboardInterrupt() + signal.signal(signal.SIGTERM, interrupted) + try: + return Soak().run() + except (Exception, KeyboardInterrupt) as error: + print('soak: ' + str(error), file=sys.stderr) + return 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/scripts/soak_probe.sh b/scripts/soak_probe.sh new file mode 100644 index 0000000..0a817ce --- /dev/null +++ b/scripts/soak_probe.sh @@ -0,0 +1,29 @@ +#!/bin/sh +# Read only this container's process namespace. The probe itself is excluded. +set -eu +self=$$ +for path in /proc/[0-9]*; do + pid=${path##*/} + [ "$pid" = "$self" ] && continue + [ -r "$path/stat" ] && [ -r "$path/status" ] || continue + # Observe service/worker processes, not transient runc/exec/healthcheck helpers. + name=$(cat "$path/comm" 2>/dev/null) || { + [ ! -e "$path" ] && continue + exit 1 + } + case "$name" in rr|php|php-fpm*|tracewick-agent) ;; *) continue ;; esac + # Compose's extension healthcheck is a transient diagnostic, not a worker. + args=$(tr '\000' ' ' < "$path/cmdline" 2>/dev/null) || { + [ ! -e "$path" ] && continue + exit 1 + } + case "$args" in *'exit(extension_loaded'*) continue ;; esac + printf '@ %s\n' "$pid" + cat "$path/stat" 2>/dev/null || exit 1 + cat "$path/status" 2>/dev/null || exit 1 + printf 'FDs:\t' + # Failure must not become a convincing zero descriptor count. + fds=$(find "$path/fd" -mindepth 1 -maxdepth 1 2>/dev/null) || exit 1 + if [ -n "$fds" ]; then printf '%s\n' "$fds" | wc -l; else printf '0\n'; fi + printf '@end\n' +done diff --git a/scripts/soak_spool.php b/scripts/soak_spool.php new file mode 100644 index 0000000..71bcae2 --- /dev/null +++ b/scripts/soak_spool.php @@ -0,0 +1,39 @@ + 100000) { + throw new RuntimeException('Spool probe scan budget exceeded'); + } + if (!$file->isFile()) { + continue; + } + try { + $size = $file->getSize(); + $modified = $file->getMTime(); + } catch (RuntimeException $error) { + // A concurrent ack/rename is normal; other filesystem failures are not zero backlog. + if (!file_exists($file->getPathname())) { + continue; + } + throw $error; + } + if (str_contains($file->getPathname(), '/rejected/')) { + ++$rejected; + } else { + // Include claims and in-progress temporary files: neither means an empty spool. + ++$pending; + $bytes += $size; + $oldest = min($oldest, $modified); + } +} +echo json_encode(['pending_files' => $pending, 'pending_bytes' => $bytes, + 'oldest_age_seconds' => $pending ? max(0, time() - $oldest) : 0, + 'rejected_files' => $rejected], JSON_THROW_ON_ERROR); diff --git a/scripts/soaklib.py b/scripts/soaklib.py new file mode 100644 index 0000000..9aabe90 --- /dev/null +++ b/scripts/soaklib.py @@ -0,0 +1,288 @@ +"""Linux/Docker soak telemetry and validity checks (standard library only).""" +from __future__ import annotations + +import csv +import copy +import http.client +import json +import math +import os +import socket +import statistics +import subprocess +import time +import urllib.request +from datetime import datetime, timezone +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +PROBE = (ROOT / 'scripts/soak_probe.sh').read_text() + + +def command(args, **kwargs): + return subprocess.check_output(args, text=True, timeout=30, **kwargs).strip() + + +class UnixHTTP(http.client.HTTPConnection): + def __init__(self, path): + super().__init__('localhost', timeout=10) + self.path = path + + def connect(self): + self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.sock.settimeout(self.timeout) + self.sock.connect(self.path) + + +class Docker: + def __init__(self): + host = os.environ.get('DOCKER_HOST') or command([ + 'docker', 'context', 'inspect', '--format', '{{.Endpoints.docker.Host}}']) + if not host.startswith('unix://'): + raise ValueError('Observed soak requires local Linux Docker with a Unix socket') + self.socket = host[7:] + + def get(self, path): + conn = UnixHTTP(self.socket) + try: + conn.request('GET', path) + response = conn.getresponse() + body = response.read() + if response.status != 200: + raise RuntimeError(f'Docker {path}: HTTP {response.status}') + return json.loads(body) + finally: + conn.close() + + def inspect(self, cid): + return self.get(f'/containers/{cid}/json') + + def sample(self, cid, processes=False, allow_shared=False): + info = self.inspect(cid) + state = info['State'] + if not state['Running'] or state.get('OOMKilled'): + raise RuntimeError(f'Container {cid[:12]} stopped or OOM-killed') + stats = self.get(f'/containers/{cid}/stats?stream=false&one-shot=true') + memory = stats['memory_stats'] + detail = memory.get('stats', {}) + cpu = stats['cpu_stats'] + started = datetime.fromisoformat(state['StartedAt'].replace('Z', '+00:00')) + age = max(0, (datetime.now(timezone.utc) - started).total_seconds()) + implausible = cpu['cpu_usage']['total_usage'] / 1e9 > age * os.cpu_count() + 5 + if implausible and not allow_shared: + raise ValueError('Implausible container CPU counter: shared/incorrect cgroup accounting') + result = { + 'id': info['Id'], 'image': info['Image'], 'shared_cgroup_smoke': allow_shared, + 'started_at': state['StartedAt'], 'restarts': info['RestartCount'], + 'cpu_ns': cpu['cpu_usage']['total_usage'], + 'throttled_ns': cpu.get('throttling_data', {}).get('throttled_time', 0), + 'memory_bytes': memory['usage'], + 'anon_bytes': detail.get('anon', detail.get('total_rss', detail.get('rss'))), + 'file_bytes': detail.get('file', detail.get('total_cache', detail.get('cache'))), + 'memory_limit_bytes': memory.get('limit'), + 'pids': stats.get('pids_stats', {}).get('current'), + } + if processes: + raw = subprocess.run(['docker', 'exec', '-i', '-u', '0', cid, 'sh'], + input=PROBE, text=True, capture_output=True, timeout=15) + if raw.returncode: + raise RuntimeError(f'/proc probe failed: {raw.stderr.strip()}') + result['processes'] = parse_processes(raw.stdout) + return result + + +def parse_processes(raw): + records = [] + current = None + for line in raw.splitlines(): + if line.startswith('@ '): + current = {'pid': int(line[2:])} + elif line == '@end': + if current is None or not {'start_ticks', 'rss_bytes', 'anon_bytes', 'fds', + 'threads', 'cpu_seconds'} <= current.keys(): + raise ValueError('Incomplete /proc record') + records.append(current) + current = None + elif current is not None: + if line.startswith(str(current['pid']) + ' ('): + fields = line[line.rfind(')') + 2:].split() + current['comm'] = line[line.find('(') + 1:line.rfind(')')] + current['start_ticks'] = int(fields[19]) + current['cpu_seconds'] = (int(fields[11]) + int(fields[12])) / os.sysconf('SC_CLK_TCK') + else: + key, _, value = line.partition(':') + if key in ('VmRSS', 'RssAnon', 'FDs', 'Threads'): + name = {'VmRSS': 'rss_bytes', 'RssAnon': 'anon_bytes', + 'FDs': 'fds', 'Threads': 'threads'}[key] + current[name] = int(value.split()[0]) * (1024 if key in ('VmRSS', 'RssAnon') else 1) + if current is not None or not records: + raise ValueError('Empty or truncated /proc telemetry') + return records + + +def get_json(url): + with urllib.request.urlopen(url, timeout=5) as response: + return json.load(response) + + +def k6_metrics(url): + data = get_json(url + '/v1/metrics')['data'] + metrics = {item['id']: item['attributes']['sample'] for item in data} + # k6 REST trend percentiles are cumulative checkpoints, not interval percentiles. + return {'requests': metrics['http_reqs']['count'], + 'failed': metrics.get('http_req_failed', {}), + 'duration': metrics.get('http_req_duration', {}), + 'dropped': metrics.get('dropped_iterations', {}).get('count', 0)} + + +def prometheus(text): + result = {} + for line in text.splitlines(): + if not line or line.startswith('#'): + continue + key, value = line.split() + if '{' not in key: + result[key] = float(value) + required = {'spool_files', 'spool_bytes', 'spool_oldest_age_seconds', + 'profiles_delivered_total', 'profiles_rejected_total', + 'profiles_retried_total', 'inflight_uploads'} + if not required <= result.keys() or any(not math.isfinite(v) for v in result.values()): + raise ValueError('Missing or invalid agent metrics') + return result + + +def agent_metrics(url): + with urllib.request.urlopen(url, timeout=5) as response: + return prometheus(response.read().decode()) + + +def process_identity(container): + return sorted((p['pid'], p['start_ticks']) for p in container['processes']) + + +class Continuity: + def __init__(self, interval): + self.interval = interval + self.previous = None + + def check(self, sample): + previous = self.previous + if previous: + elapsed = sample['monotonic'] - previous['monotonic'] + if elapsed > max(self.interval * 2.5, self.interval + 30): + raise ValueError(f'Telemetry gap: {elapsed:.1f}s') + if sample['containers'].keys() != previous['containers'].keys(): + raise ValueError('Missing monitored container') + for role, current in sample['containers'].items(): + old = previous['containers'][role] + for key in ('id', 'started_at', 'restarts'): + if current[key] != old[key]: + raise ValueError(f'{role}: container restarted or was replaced') + if current['cpu_ns'] < old['cpu_ns']: + raise ValueError(f'{role}: CPU counter reset') + if 'processes' in current and process_identity(current) != process_identity(old): + raise ValueError(f'{role}: worker/process identity changed') + if sample.get('agent') and previous.get('agent'): + for key in ('profiles_delivered_total', 'profiles_rejected_total', 'profiles_retried_total'): + if sample['agent'][key] < previous['agent'][key]: + raise ValueError(f'Agent counter reset: {key}') + self.previous = copy.deepcopy(sample) + + +def summarize(samples): + rows = [s for s in samples if s['phase'] == 'steady'] + if len(rows) < 2: + raise ValueError('Insufficient steady telemetry') + span = rows[-1]['monotonic'] - rows[0]['monotonic'] + if span <= 0: + raise ValueError('Invalid telemetry timestamps') + output = {} + for role in rows[0]['containers']: + data = [s['containers'][role] for s in rows] + window = min(3600, span * 0.1) + first = [s['containers'][role] for s in rows if s['monotonic'] <= rows[0]['monotonic'] + window] + last = [s['containers'][role] for s in rows if s['monotonic'] >= rows[-1]['monotonic'] - window] + # Container memory and process RSS are deliberately separate measurements. + mean = lambda group, key: statistics.fmean(r[key] for r in group) + delta = mean(last, 'memory_bytes') - mean(first, 'memory_bytes') + cpu = (data[-1]['cpu_ns'] - data[0]['cpu_ns']) / 1e9 + requests = rows[-1]['k6']['requests'] - rows[0]['k6']['requests'] + metrics = { + 'container_memory_first_bytes': mean(first, 'memory_bytes'), + 'container_memory_last_bytes': mean(last, 'memory_bytes'), + 'container_memory_delta_bytes': delta, + 'cpu_seconds': cpu, 'cpu_ms_per_request': cpu * 1000 / requests if requests and not data[0].get('shared_cgroup_smoke') else None, + 'throttled_seconds': (data[-1]['throttled_ns'] - data[0]['throttled_ns']) / 1e9, + } + if 'processes' in data[0]: + process_cpu = sum(p['cpu_seconds'] for p in data[-1]['processes']) - sum(p['cpu_seconds'] for p in data[0]['processes']) + metrics['process_cpu_ms_per_request'] = process_cpu * 1000 / requests if requests else None + for key in ('rss_bytes', 'anon_bytes', 'fds', 'threads'): + totals = [sum(p[key] for p in r['processes']) for r in data] + # Least-squares slope uses the whole series, not only endpoints. + xs = [(s['monotonic'] - rows[0]['monotonic']) / 3600 for s in rows] + xm, ym = statistics.fmean(xs), statistics.fmean(totals) + slope = sum((x - xm) * (y - ym) for x, y in zip(xs, totals)) / sum((x - xm)**2 for x in xs) + metrics[key] = {'first': totals[0], 'last': totals[-1], 'max': max(totals), + 'first_window_mean': statistics.fmean(sum(p[key] for p in r['processes']) for r in first), + 'last_window_mean': statistics.fmean(sum(p[key] for p in r['processes']) for r in last), + 'slope_per_hour': slope} + output[role] = metrics + return {'observed_seconds': span, 'services': output} + + +def write_report(directory, result): + directory = Path(directory) + (directory / 'result.json').write_text(json.dumps(result, indent=2) + '\n') + lines = ['# Observed soak', '', 'Method: [METHOD.md](../../../METHOD.md).', '', + f"Validity: **{result['status']}**", '', + 'A valid short run checks the harness only; it is not 72h evidence or proof of no leaks.', ''] + if result.get('error'): + lines += ['Failure: ' + result['error'], ''] + summary = result.get('summary', {}) + if summary: + lines += ['## Steady window', '', f"Observed: {summary['observed_seconds']:.1f} seconds.", '', + '| Service | Container memory Δ MiB | CPU ms/request | Process RSS slope MiB/h | Anonymous slope MiB/h |', + '| --- | ---: | ---: | ---: | ---: |'] + for role, values in summary['services'].items(): + slope = lambda key: f"{values[key]['slope_per_hour']/1048576:.3f}" if key in values else 'not collected' + per_request = values['cpu_ms_per_request'] + cpu_text = f"{per_request:.3f}" if per_request is not None else 'not attributable' + lines.append(f"| {role} | {values['container_memory_delta_bytes']/1048576:.3f} | " + f"{cpu_text} | {slope('rss_bytes')} | {slope('anon_bytes')} |") + baseline = result.get('baseline_summary') + if baseline: + lines += ['', '## Short unprofiled baseline', ''] + for role, values in baseline['services'].items(): + lines.append(f"- {role}: {values['cpu_ms_per_request']} CPU ms/k6 HTTP request.") + lines += ['', '## Evidence and interpretation', '', + '- `identity.json`: resolved package/source references, image IDs, host and limits.', + '- `telemetry.jsonl`: process identity, RSS/anonymous memory/FD/threads, cgroup CPU/memory/throttling, agent queue/delivery counters and k6 cumulative checkpoints.', + '- `phases.jsonl`: phase boundaries; `*-k6.json`: complete per-phase latency/RPS/error summaries.', + '- `hourly.json`: fixed-hour CPU/request and memory endpoints; latency checkpoints are cumulative, not hourly quantiles.', + '- PID/start-time or container changes invalidate continuity. Resource limits remain enabled.', + '- RSS includes shared mappings and retained allocator memory; a positive slope is a diagnosis trigger, not proof of a leak.', + '- No goroutine/heap metrics are invented: current agent exposes delivery metrics only.', + '- Writer diagnostics are available for the single RR worker; FPM/Swoole writer drops are not measured by this harness.', + '- The short baseline uses a separate worker lifecycle and is not a full overhead capacity campaign.', + '- No statistical symbol-share accuracy, chaos, maximum-RPS or production-readiness claim.', ''] + (directory / 'soak-report.md').write_text('\n'.join(lines)) + + +def export_csv(directory, records): + fields = ['ts', 'phase', 'role', 'container_memory_bytes', 'container_anon_bytes', + 'container_cpu_ns', 'shared_cgroup_smoke', 'process_rss_bytes', + 'process_anon_bytes', 'process_cpu_seconds', 'fds', 'threads', + 'k6_requests', 'pending_files', 'pending_bytes'] + with (Path(directory) / 'resource-series.csv').open('w') as stream: + writer = csv.DictWriter(stream, fieldnames=fields) + writer.writeheader() + for row in records: + for role, data in row['containers'].items(): + processes = data.get('processes') + total = lambda key: sum(p[key] for p in processes) if processes else None + writer.writerow(dict(zip(fields, [row['ts'], row['phase'], role, + data['memory_bytes'], data.get('anon_bytes'), data['cpu_ns'], + data.get('shared_cgroup_smoke', False), total('rss_bytes'), total('anon_bytes'), + total('cpu_seconds'), total('fds'), total('threads'), row['k6']['requests'], + row['spool']['pending_files'], row['spool']['pending_bytes']]))) diff --git a/stand/agent/Dockerfile b/stand/agent/Dockerfile index e6b0581..0101c1f 100644 --- a/stand/agent/Dockerfile +++ b/stand/agent/Dockerfile @@ -1,6 +1,22 @@ # Thin image: public GitHub release binary (avoids private GHCR pulls). # Runs as UID/GID 33 to match PHP-FPM www-data on the spool volume. -FROM debian:bookworm-slim +ARG AGENT_BUILD_TARGET=release + +FROM golang:1.27.4-bookworm AS source-build +ARG AGENT_REF +WORKDIR /src +RUN --mount=type=secret,id=proxy_ca \ + if [ -f /run/secrets/proxy_ca ]; then export GIT_SSL_CAINFO=/run/secrets/proxy_ca SSL_CERT_FILE=/run/secrets/proxy_ca; fi; \ + test "${#AGENT_REF}" -eq 40 \ + && git init . \ + && git remote add origin https://github.com/tracewick/agent.git \ + && git fetch --depth=1 origin "${AGENT_REF}" \ + && git checkout --detach FETCH_HEAD \ + && test "$(git rev-parse HEAD)" = "${AGENT_REF}" \ + && CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X github.com/tracewick/agent/internal/version.Version=dev-${AGENT_REF}" -o /tracewick-agent ./cmd/tracewick-agent \ + && git rev-parse HEAD > /agent-reference + +FROM debian:bookworm-slim AS release ARG AGENT_VERSION=0.1.0 ARG TARGETARCH=amd64 @@ -21,3 +37,16 @@ RUN apt-get update \ USER www-data:www-data ENTRYPOINT ["tracewick-agent"] CMD ["run", "--reader-id=bench-agent", "--sleep=2s"] + +# Same runtime/UID contract, with a binary built from the exact source commit. +FROM debian:bookworm-slim AS source +RUN apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates \ + && rm -rf /var/lib/apt/lists/* +COPY --from=source-build /tracewick-agent /usr/local/bin/tracewick-agent +COPY --from=source-build /agent-reference /agent-reference +USER 33:33 +ENTRYPOINT ["tracewick-agent"] +CMD ["run", "--reader-id=bench-agent", "--sleep=2s"] + +FROM ${AGENT_BUILD_TARGET} AS final diff --git a/stand/app/Dockerfile b/stand/app/Dockerfile index 1971f5e..50d6ab6 100644 --- a/stand/app/Dockerfile +++ b/stand/app/Dockerfile @@ -15,8 +15,11 @@ ARG TRACEWICK_VERSION=0.1.0 WORKDIR /app COPY composer.json ./ -# Pin is in composer.json; TRACEWICK_VERSION must match that constraint when rebuilding. -RUN test -n "${TRACEWICK_VERSION}" \ +# The build argument is the actual Composer constraint, including dev-develop#. +RUN --mount=type=secret,id=proxy_ca \ + if [ -f /run/secrets/proxy_ca ]; then export COMPOSER_CAFILE=/run/secrets/proxy_ca; fi; \ + test -n "${TRACEWICK_VERSION}" \ + && composer require --no-update --no-interaction "tracewick/tracewick:${TRACEWICK_VERSION}" \ && composer update --no-interaction --no-progress --no-dev \ --ignore-platform-req=ext-sockets \ && composer clear-cache \ @@ -27,13 +30,14 @@ FROM ghcr.io/roadrunner-server/roadrunner:${ROADRUNNER_VERSION} AS roadrunner-bi FROM php:${PHP_VERSION}-cli-bookworm AS php-base ARG EXCIMER_VERSION=1.2.6 +ARG EXCIMER_REF +COPY install-excimer.sh /tmp/install-excimer.sh -RUN apt-get update \ +RUN --mount=type=secret,id=proxy_ca apt-get update \ && apt-get install -y --no-install-recommends git unzip \ && rm -rf /var/lib/apt/lists/* \ && docker-php-ext-install -j"$(nproc)" pcntl sockets \ - && pecl install "excimer-${EXCIMER_VERSION}" \ - && docker-php-ext-enable excimer \ + && sh /tmp/install-excimer.sh \ && rm -rf /tmp/pear \ && php -r 'exit(extension_loaded("excimer") ? 0 : 1);' \ && install -d -o www-data -g www-data /var/spool/tracewick @@ -46,6 +50,9 @@ COPY src /srv/app/src COPY worker.php /srv/app/worker.php COPY swoole-server.php /srv/app/swoole-server.php COPY .rr.yaml /srv/app/.rr.yaml +RUN chmod 0644 worker.php swoole-server.php .rr.yaml \ + && find public src -type d -exec chmod 0755 {} + \ + && find public src -type f -exec chmod 0644 {} + ENV TRACEWICK_SPOOL_DIR=/var/spool/tracewick \ TRACEWICK_SAMPLE_RATE=1.0 \ @@ -55,13 +62,14 @@ ENV TRACEWICK_SPOOL_DIR=/var/spool/tracewick \ FROM php:${PHP_VERSION}-fpm-bookworm AS fpm ARG EXCIMER_VERSION=1.2.6 +ARG EXCIMER_REF +COPY install-excimer.sh /tmp/install-excimer.sh -RUN apt-get update \ +RUN --mount=type=secret,id=proxy_ca apt-get update \ && apt-get install -y --no-install-recommends git unzip \ && rm -rf /var/lib/apt/lists/* \ && docker-php-ext-install -j"$(nproc)" pcntl \ - && pecl install "excimer-${EXCIMER_VERSION}" \ - && docker-php-ext-enable excimer \ + && sh /tmp/install-excimer.sh \ && rm -rf /tmp/pear \ && php -r 'exit(extension_loaded("excimer") ? 0 : 1);' \ && install -d -o www-data -g www-data /var/spool/tracewick @@ -73,7 +81,9 @@ COPY public /srv/app/public COPY src /srv/app/src COPY php-fpm.conf /usr/local/etc/php-fpm.d/zz-benchmarks.conf COPY docker-fpm-entrypoint.sh /usr/local/bin/docker-fpm-entrypoint.sh -RUN chmod +x /usr/local/bin/docker-fpm-entrypoint.sh +RUN chmod 0755 /usr/local/bin/docker-fpm-entrypoint.sh \ + && find public src -type d -exec chmod 0755 {} + \ + && find public src -type f -exec chmod 0644 {} + ENV TRACEWICK_SPOOL_DIR=/var/spool/tracewick \ TRACEWICK_SAMPLE_RATE=1.0 \ @@ -88,7 +98,7 @@ CMD ["php-fpm"] FROM php-base AS roadrunner COPY --from=roadrunner-binary /usr/bin/rr /usr/local/bin/rr COPY docker-rr-entrypoint.sh /usr/local/bin/docker-rr-entrypoint.sh -RUN chmod +x /usr/local/bin/docker-rr-entrypoint.sh +RUN chmod 0755 /usr/local/bin/docker-rr-entrypoint.sh ENV RR_NUM_WORKERS=4 USER www-data ENTRYPOINT ["/usr/local/bin/docker-rr-entrypoint.sh"] @@ -105,7 +115,7 @@ RUN apt-get update \ && rm -rf /var/lib/apt/lists/* /tmp/pear \ && php -r 'exit(extension_loaded("swoole") ? 0 : 1);' COPY docker-swoole-entrypoint.sh /usr/local/bin/docker-swoole-entrypoint.sh -RUN chmod +x /usr/local/bin/docker-swoole-entrypoint.sh +RUN chmod 0755 /usr/local/bin/docker-swoole-entrypoint.sh ENV SWOOLE_WORKER_NUM=4 \ SWOOLE_LISTEN_HOST=0.0.0.0 \ SWOOLE_LISTEN_PORT=8080 diff --git a/stand/app/install-excimer.sh b/stand/app/install-excimer.sh new file mode 100644 index 0000000..e83cceb --- /dev/null +++ b/stand/app/install-excimer.sh @@ -0,0 +1,22 @@ +#!/bin/sh +# Optional exact source pin for benchmark builds; otherwise retain the PECL stand path. +set -eu +if [ -f /run/secrets/proxy_ca ]; then export GIT_SSL_CAINFO=/run/secrets/proxy_ca; fi +if [ -n "${EXCIMER_REF:-}" ]; then + test "${#EXCIMER_REF}" -eq 40 + git init /tmp/excimer + git -C /tmp/excimer remote add origin https://github.com/wikimedia/php-excimer.git + git -C /tmp/excimer fetch --depth=1 origin "$EXCIMER_REF" + git -C /tmp/excimer checkout --detach FETCH_HEAD + test "$(git -C /tmp/excimer rev-parse HEAD)" = "$EXCIMER_REF" + cd /tmp/excimer + phpize + ./configure + make -j2 + make install + rm -rf /tmp/excimer +else + pecl install "excimer-${EXCIMER_VERSION}" +fi +docker-php-ext-enable excimer +php -r 'exit(phpversion("excimer") === getenv("EXCIMER_VERSION") ? 0 : 1);' diff --git a/stand/app/worker.php b/stand/app/worker.php index 344f2a3..7bd920b 100644 --- a/stand/app/worker.php +++ b/stand/app/worker.php @@ -73,6 +73,8 @@ 'work_stack_depth' => $stackDepth, 'runtime' => 'roadrunner', 'rr_num_workers' => max(1, (int) (getenv('RR_NUM_WORKERS') ?: '4')), + 'pid' => getmypid(), + 'diagnostics' => $profiler?->diagnostics(), ], JSON_THROW_ON_ERROR); $rr->respond(new Response(200, ['Content-Type' => 'application/json'], $body)); diff --git a/tests/test_soak.py b/tests/test_soak.py new file mode 100644 index 0000000..3401a93 --- /dev/null +++ b/tests/test_soak.py @@ -0,0 +1,151 @@ +"""Behavioral regression tests for misleading soak results and telemetry loss.""" +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts')) +from soaklib import Docker, Continuity, parse_processes, prometheus, summarize, write_report +from soak import Soak, pin, seconds + + +def sample(t=0, requests=1): + container = {'id': 'container', 'started_at': 'start', 'restarts': 0, + 'cpu_ns': int(t * 2e9), 'throttled_ns': 0, 'memory_bytes': 1000 + t, + 'processes': [{'pid': 1, 'start_ticks': 123, 'rss_bytes': 2000 + t, + 'anon_bytes': 1000 + t, 'fds': 4, 'threads': 2, 'cpu_seconds': t}]} + return {'monotonic': t, 'ts': t, 'phase': 'steady', 'k6': {'requests': requests}, + 'containers': {'app': container}} + + +class ContinuityTest(unittest.TestCase): + def test_worker_recycling_cannot_hide_memory_growth(self): + guard = Continuity(15) + guard.check(sample()) + restarted = sample(15, 150) + restarted['containers']['app']['processes'][0]['start_ticks'] += 1 + with self.assertRaisesRegex(ValueError, 'identity changed'): + guard.check(restarted) + + def test_detects_container_restart_and_replacement(self): + for key, value in [('id', 'replacement'), ('started_at', 'new'), ('restarts', 1)]: + with self.subTest(key=key): + guard = Continuity(15) + guard.check(sample()) + row = sample(15, 150) + row['containers']['app'][key] = value + with self.assertRaisesRegex(ValueError, 'restarted or was replaced'): + guard.check(row) + + def test_missing_samples_and_counter_resets_invalidate(self): + for t, cpu in [(120, 100), (15, -1)]: + guard = Continuity(15) + guard.check(sample()) + row = sample(t) + row['containers']['app']['cpu_ns'] = cpu + with self.assertRaises(ValueError): + guard.check(row) + + def test_snapshot_is_not_mutated_by_added_observations(self): + row = sample() + guard = Continuity(15) + guard.check(row) + row['containers']['generator'] = {} + guard.check(sample(15, 150)) + + +class EvidenceTest(unittest.TestCase): + def test_process_rss_and_container_memory_are_separate_and_cpu_is_normalized(self): + rows = [sample(0, 0), sample(1800, 18000), sample(3600, 36000)] + report = summarize(rows)['services']['app'] + self.assertEqual(200, report['cpu_ms_per_request']) + self.assertEqual(3600, report['rss_bytes']['slope_per_hour']) + self.assertEqual(1000, report['container_memory_first_bytes']) + self.assertEqual(2000, report['rss_bytes']['first']) + + def test_no_or_truncated_telemetry_does_not_pass(self): + for rows in ([], [sample()]): + with self.assertRaises(ValueError): + summarize(rows) + for raw in ('', '@ 1\n', '@ 1\n@end\n'): + with self.assertRaises(ValueError): + parse_processes(raw) + + def test_real_proc_record_including_parentheses_in_comm(self): + # Fields 3..22 include utime/stime at indexes 11/12 and starttime at 19. + stat = ['S'] + ['0'] * 19 + stat[11], stat[12], stat[19] = '100', '50', '12345' + raw = '@ 1\n1 (php (worker)) ' + ' '.join(stat) + '\nVmRSS:\t8 kB\nRssAnon:\t4 kB\nThreads:\t2\nFDs:\t3\n@end\n' + row = parse_processes(raw)[0] + self.assertEqual(8192, row['rss_bytes']) + self.assertEqual(4096, row['anon_bytes']) + self.assertEqual(12345, row['start_ticks']) + self.assertEqual('php (worker)', row['comm']) + + def test_absent_or_nonfinite_agent_metrics_are_not_zero_queue(self): + for text in ('', 'spool_files 0\n', 'spool_files NaN\n'): + with self.assertRaises(ValueError): + prometheus(text) + + def test_failure_report_is_written_without_false_green(self): + with tempfile.TemporaryDirectory() as directory: + write_report(directory, {'status': 'invalid', 'error': 'missing telemetry'}) + result = json.loads((Path(directory) / 'result.json').read_text()) + self.assertEqual('invalid', result['status']) + self.assertIn('missing telemetry', (Path(directory) / 'soak-report.md').read_text()) + + + + def test_parent_cgroup_cpu_is_not_attributed_to_a_new_container(self): + from datetime import datetime, timezone + engine = Docker.__new__(Docker) + engine.inspect = lambda _: {'State': {'Running': True, 'StartedAt': datetime.now(timezone.utc).isoformat()}, + 'Id': 'new', 'Image': 'image', 'RestartCount': 0} + engine.get = lambda _: {'cpu_stats': {'cpu_usage': {'total_usage': 10**18}}, + 'memory_stats': {'usage': 100, 'stats': {}}} + with self.assertRaisesRegex(ValueError, 'cgroup accounting'): + engine.sample('new') + + def test_shared_cgroup_cannot_be_used_for_a_long_soak(self): + env = {'TRACEWICK_VERSION': '0.2.0', 'AGENT_VERSION': '0.2.1', + 'SOAK_SMOKE_SHARED_CGROUP': '1', 'DURATION': '72h'} + with patch.dict(os.environ, env, clear=True), patch('soak.Docker'): + with self.assertRaisesRegex(ValueError, '60 seconds'): + Soak() + + def test_disabled_or_inactive_profiling_is_not_a_healthy_run(self): + runner = Soak.__new__(Soak) + runner.base_url = 'http://localhost' + runner.env = {'WORK_STACK_DEPTH': '48'} + healthy = {'ok': True, 'excimer': True, 'tracewick': True, + 'profiling_enabled': True, 'work_stack_depth': 48} + for changes in ({'excimer': False}, {'profiling_enabled': False}, + {'work_stack_depth': 0}, {'diagnostics': {'inactiveSampler': 'disabled'}}): + with patch('soak.get_json', return_value={**healthy, **changes}): + with self.assertRaises(ValueError): + runner.health(True) + + def test_wrong_installed_reference_is_rejected_before_traffic(self): + runner = Soak.__new__(Soak) + runner.package = 'dev-develop#' + 'a' * 40 + runner.ids = {'app': 'test-container'} + with patch('soak.command', return_value=json.dumps({'reference': 'b' * 40})): + with self.assertRaisesRegex(ValueError, 'reference'): + runner.runtime_identity() + + def test_exact_pins_and_combined_durations(self): + self.assertEqual(5400, seconds('1h30m')) + self.assertEqual('dev-develop#' + 'a' * 40, pin('dev-develop#' + 'a' * 40)) + for value in ('latest', 'dev-develop', '^0.2', '0.2'): + with self.assertRaises(ValueError): + pin(value) + for value in ('0s', '-1h', '72hours'): + with self.assertRaises(ValueError): + seconds(value) + + +if __name__ == '__main__': + unittest.main() From ba805025208751edd0f9ce3ddc1ff110dc3896d4 Mon Sep 17 00:00:00 2001 From: Alexandr Kazakov Date: Tue, 17 Nov 2026 21:02:26 +0300 Subject: [PATCH 2/3] fix: verify observed soak workload and runtime settings --- docs/soak.md | 11 ++++++----- scripts/soak.py | 16 +++++++++++++--- tests/test_soak.py | 33 +++++++++++++++++++++++++++++++-- 3 files changed, 50 insertions(+), 10 deletions(-) diff --git a/docs/soak.md b/docs/soak.md index 4198a41..b91eba2 100644 --- a/docs/soak.md +++ b/docs/soak.md @@ -109,9 +109,10 @@ Every STATS_INTERVAL seconds, `telemetry.jsonl` records: - Agent queue/delivery/retry/reject metrics, and the single RR worker's profiler diagnostics. FPM/Swoole writer-drop totals are not available from this harness. Go goroutine/heap metrics are not currently exported; OS threads are not goroutines. -- k6 cumulative request/drop/error/latency checkpoints. REST polling avoids storing - per-request events for 72 hours. Quantiles are cumulative checkpoints; only the - final per-phase summaries are full-window p95/p99, not independent hourly quantiles. +- k6 cumulative request, drop, error and latency checkpoints. The runner saves + interval snapshots. k6 itself retains trend samples for end-of-phase quantiles, + so track the generator's memory separately. REST includes cumulative p95 and + the per-phase summary includes full-window p95 and p99. `resource-series.csv` is a flattened export; `hourly.json` summarizes fixed-hour CPU/request and memory observations. `result.json` and `soak-report.md` separate @@ -131,8 +132,8 @@ progress with a nonempty queue abort the run during collection. Increasing writer/delivery failure counters and rejected files also abort promptly. Missing/malformed telemetry, counter resets, container/worker replacement, OOM, -large collection gaps, wrong pins/disabled profiling, missed HTTP checks, dropped -load-generator iterations, absent delivery or increasing RR writer failures make +large collection gaps, wrong pins or RoadRunner profiling settings, missed HTTP +checks, dropped or incomplete load iterations, absent delivery or increasing RR writer failures make the observation invalid and the command exits nonzero. Raw artifacts and an invalid report survive failures. A **valid observation** only means these validity checks passed; inspect trends, queue and duration before deciding whether the soak passed. diff --git a/scripts/soak.py b/scripts/soak.py index 8e18f25..358584f 100644 --- a/scripts/soak.py +++ b/scripts/soak.py @@ -162,6 +162,9 @@ def health(self, enabled): raise ValueError('Wrong profiling state') if health.get('work_stack_depth') != int(self.env['WORK_STACK_DEPTH']): raise ValueError('Wrong workload depth') + if self.runtime == 'rr' and (health.get('rr_num_workers') != 1 + or health.get('sample_rate') != self.sample_rate): + raise ValueError('Wrong RoadRunner worker count or profiling sample rate') diagnostics = health.get('diagnostics') if enabled and diagnostics and diagnostics.get('inactiveSampler') is not None: raise ValueError('Inactive sampler despite enabled profiling') @@ -260,15 +263,20 @@ def run_load(self, phase): if time.monotonic() - started < seconds(duration): raise ValueError('Load ended before the requested duration') summary = json.loads((self.directory / (phase + '-k6.json')).read_text()) - metrics = summary['metrics'] - if metrics['http_reqs']['count'] <= 0 or metrics.get('dropped_iterations', {}).get('count', 0): - raise ValueError('No requests or dropped load-generator iterations') + self.check_load_summary(summary, duration) finally: subprocess.run(['docker', 'rm', '-f', self.load_name], capture_output=True, timeout=30) self.load.wait(timeout=30) self.load = None output.close() + def check_load_summary(self, summary, duration): + metrics = summary['metrics'] + expected = self.rate * seconds(duration) + completed = metrics['iterations']['count'] + if completed != expected or metrics['dropped_iterations']['count'] != 0: + raise ValueError(f'Incomplete load: completed {completed} of {expected} scheduled iterations') + def runtime_identity(self): script = ('require "vendor/autoload.php"; echo json_encode([' '"php"=>PHP_VERSION,"excimer"=>phpversion("excimer"),' @@ -280,6 +288,8 @@ def runtime_identity(self): raise ValueError('Installed core reference does not match requested SHA') elif actual['version'].lstrip('v') != self.package.lstrip('v'): raise ValueError('Installed core version does not match requested version') + if actual['excimer'] != self.env['EXCIMER_VERSION']: + raise ValueError('Installed Excimer version does not match requested version') if self.reader == 'agent': actual['agent_version'] = command(['docker', 'exec', self.ids['reader'], 'tracewick-agent', 'version']) if self.env.get('AGENT_REF'): diff --git a/tests/test_soak.py b/tests/test_soak.py index 3401a93..7e60ec2 100644 --- a/tests/test_soak.py +++ b/tests/test_soak.py @@ -119,11 +119,17 @@ def test_shared_cgroup_cannot_be_used_for_a_long_soak(self): def test_disabled_or_inactive_profiling_is_not_a_healthy_run(self): runner = Soak.__new__(Soak) runner.base_url = 'http://localhost' + runner.runtime = 'rr' + runner.sample_rate = 0.1 runner.env = {'WORK_STACK_DEPTH': '48'} healthy = {'ok': True, 'excimer': True, 'tracewick': True, - 'profiling_enabled': True, 'work_stack_depth': 48} + 'profiling_enabled': True, 'work_stack_depth': 48, + 'rr_num_workers': 1, 'sample_rate': 0.1} + with patch('soak.get_json', return_value=healthy): + self.assertEqual(healthy, runner.health(True)) for changes in ({'excimer': False}, {'profiling_enabled': False}, - {'work_stack_depth': 0}, {'diagnostics': {'inactiveSampler': 'disabled'}}): + {'work_stack_depth': 0}, {'rr_num_workers': 2}, {'sample_rate': 1}, + {'diagnostics': {'inactiveSampler': 'disabled'}}): with patch('soak.get_json', return_value={**healthy, **changes}): with self.assertRaises(ValueError): runner.health(True) @@ -136,6 +142,29 @@ def test_wrong_installed_reference_is_rejected_before_traffic(self): with self.assertRaisesRegex(ValueError, 'reference'): runner.runtime_identity() + def test_wrong_excimer_version_is_rejected_before_traffic(self): + runner = Soak.__new__(Soak) + runner.package = '0.2.0' + runner.env = {'EXCIMER_VERSION': '1.2.7'} + runner.ids = {'app': 'test-container'} + actual = {'version': '0.2.0', 'excimer': '1.2.6'} + with patch('soak.command', return_value=json.dumps(actual)): + with self.assertRaisesRegex(ValueError, 'Excimer version'): + runner.runtime_identity() + + def test_k6_must_complete_the_scheduled_workload(self): + runner = Soak.__new__(Soak) + runner.rate = 10 + for iterations, drops in ((600, 0), (599, 0), (601, 0), (600, 1)): + with self.subTest(iterations=iterations, drops=drops): + summary = {'metrics': {'iterations': {'count': iterations}, + 'dropped_iterations': {'count': drops}}} + if (iterations, drops) == (600, 0): + runner.check_load_summary(summary, '1m') + else: + with self.assertRaisesRegex(ValueError, 'Incomplete load'): + runner.check_load_summary(summary, '1m') + def test_exact_pins_and_combined_durations(self): self.assertEqual(5400, seconds('1h30m')) self.assertEqual('dev-develop#' + 'a' * 40, pin('dev-develop#' + 'a' * 40)) From e4835846fd0ba04b895ea81c0bb4a128da82e103 Mon Sep 17 00:00:00 2001 From: Alexandr Kazakov Date: Tue, 17 Nov 2026 21:07:06 +0300 Subject: [PATCH 3/3] fix: account for the k6 arrival deadline boundary --- docs/soak.md | 2 ++ scripts/soak.py | 6 ++++-- tests/test_soak.py | 4 ++-- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/docs/soak.md b/docs/soak.md index b91eba2..001ff33 100644 --- a/docs/soak.md +++ b/docs/soak.md @@ -137,6 +137,8 @@ checks, dropped or incomplete load iterations, absent delivery or increasing RR the observation invalid and the command exits nonzero. Raw artifacts and an invalid report survive failures. A **valid observation** only means these validity checks passed; inspect trends, queue and duration before deciding whether the soak passed. +Allow one iteration at either side of the scheduled count for the k6 deadline +boundary, while requiring zero reported drops. RSS growth alone does not prove a leak: allocator retention and shared pages matter. ## Plots after collection diff --git a/scripts/soak.py b/scripts/soak.py index 358584f..4c9b247 100644 --- a/scripts/soak.py +++ b/scripts/soak.py @@ -274,8 +274,10 @@ def check_load_summary(self, summary, duration): metrics = summary['metrics'] expected = self.rate * seconds(duration) completed = metrics['iterations']['count'] - if completed != expected or metrics['dropped_iterations']['count'] != 0: - raise ValueError(f'Incomplete load: completed {completed} of {expected} scheduled iterations') + dropped = metrics['dropped_iterations']['count'] + # The final k6 arrival timer can race the scenario deadline. + if abs(completed - expected) > 1 or dropped != 0: + raise ValueError(f'Incomplete load: completed {completed} of {expected} scheduled iterations, {dropped} dropped') def runtime_identity(self): script = ('require "vendor/autoload.php"; echo json_encode([' diff --git a/tests/test_soak.py b/tests/test_soak.py index 7e60ec2..da495ba 100644 --- a/tests/test_soak.py +++ b/tests/test_soak.py @@ -155,11 +155,11 @@ def test_wrong_excimer_version_is_rejected_before_traffic(self): def test_k6_must_complete_the_scheduled_workload(self): runner = Soak.__new__(Soak) runner.rate = 10 - for iterations, drops in ((600, 0), (599, 0), (601, 0), (600, 1)): + for iterations, drops in ((600, 0), (599, 0), (601, 0), (598, 0), (602, 0), (600, 1)): with self.subTest(iterations=iterations, drops=drops): summary = {'metrics': {'iterations': {'count': iterations}, 'dropped_iterations': {'count': drops}}} - if (iterations, drops) == (600, 0): + if abs(iterations - 600) <= 1 and drops == 0: runner.check_load_summary(summary, '1m') else: with self.assertRaisesRegex(ValueError, 'Incomplete load'):